使用rpart的预测方法(R编程)计算树的预测精度

Ar2*_*254 4 r machine-learning decision-tree rpart

我使用rpart为数据集构建了一个决策树.

然后我将数据分为两部分 - 训练数据集和测试数据集.已使用训练数据为数据集构建树.我想根据创建的模型计算预测的准确性.

我的代码如下所示:

library(rpart)
#reading the data
data = read.table("source")
names(data) <- c("a", "b", "c", "d", "class")

#generating test and train data - Data selected randomly with a 80/20 split
trainIndex  <- sample(1:nrow(x), 0.8 * nrow(x))
train <- data[trainIndex,]
test <- data[-trainIndex,]

#tree construction based on information gain
tree = rpart(class ~ a + b + c + d, data = train, method = 'class', parms = list(split = "information"))
Run Code Online (Sandbox Code Playgroud)

我现在想要通过将结果与实际值训练和测试数据进行比较来计算模型生成的预测的准确性,但是这样做时我遇到了错误.

我的代码如下所示:

t_pred = predict(tree,test,type="class")
t = test['class']
accuracy = sum(t_pred == t)/length(t)
print(accuracy)
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息,指出 -

t_pred == t时出错:未实现这些类型的比较另外:警告消息:"=="的方法不兼容("Ops.factor","Ops.data.frame")

在检查t_pred的类型时,我发现它是整数类型但文档

(https://stat.ethz.ch/R-manual/R-devel/library/rpart/html/predict.rpart.html)

声明该predict()方法必须返回一个向量.

我无法理解为什么变量的类型是整数而不是列表.我在哪里犯了错误,我该如何解决?

mto*_*oto 7

首先尝试计算混淆矩阵:

confMat <- table(test$class,t_pred)
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过将矩阵的总和对角线 - 这是正确的预测 - 除以矩阵的总和来计算精度:

accuracy <- sum(diag(confMat))/sum(confMat)
Run Code Online (Sandbox Code Playgroud)