训练集和验证集的混淆矩阵

Confusion matrix for training and validation sets

"newdata" 参数的目的是什么? 为什么我们不需要在第一种情况下指定 newdata = tlFLAG.t

pred <- predict(tree1, type = "class")
confusionMatrix(pred, factor(tlFLAG.t$TERM_FLAG)) 

pred.v <- predict(tree1, type = "class", newdata = tlFLAG.v)
confusionMatrix(pred.v, factor(tlFLAG.v$TERM_FLAG)) 

在每个机器学习过程中(在本例中为 classification 问题),您必须将数据拆分为 traintest 组。

这很有用,因为您可以在第一组中训练您的算法,在第二组中测试它。

必须这样做,否则(如果您使用所有数据)您将自己暴露于 overfitting,因为几乎每个算法都会尝试适应最好提供您提供的数据。

您最终会得到一个完美的数据模型,但这将非常预测新数据,它还没有看到。

因此,predict 函数允许您通过 newdata= 参数选择新数据,以 "test" 模型在未见数据上的优势。

在你的第一种情况下,你 "test" 你通过不指定 newdata= arg 在已经训练的数据上表现,所以 confusionMatrix 可能 -乐观.

在第二种情况下,您应该指定 newdata=test_set,这样您的预测将基于测试数据,因此性能会更准确,并且在第二种情况下更有趣。

我将在这里构建一个示例,供您查看经典方法:

data <- iris # iris dataset

# first split the data
set.seed(123) # for reproducibility
pos <- sample(100)

train <- data[pos, ] # random pick of 100 obs
test <- data[-pos, ] # remaining 50

# now you can start with your model - please not that this is a dummy example
library(rpart)

tree <- rpart(Species ~ ., data=train) # fit tree on train data

# make prediction on train data (no need to specify newclass= ) # NOT very useful
pred <- predict(tree, type = "class")
caret::confusionMatrix(pred, train$Species)

# make prediction on test data (remove the response)
pred <- predict(tree, type = "class", newdata = test[, -5]) # I removed Species (5th column in test)
# build confusion from predictions against the truth (ie the test$Species)
caret::confusionMatrix(pred, test$Species) 

请注意 test 数据的性能如何糟糕,而 train 数据的性能几乎完美。