[英]How to extract predictions and actual values vectors from a matrix to use them with confusionMatrix() in R?
Say i have the matrix说我有矩阵
> a <- matrix(c(1,2,3,4,5,6,7,8,9),nrow=3)
> rownames(a)=c('A','B','C')
> colnames(a)=c('A','B','C')
> a
A B C
A 1 4 7
B 2 5 8
C 3 6 9
Considering that columns would represent the actual class and rows the predicted class, how can I extract the predictions and actual values vectors to use them in confusionMatrix()?.考虑到列代表实际类,行代表预测类,我如何提取预测和实际值向量以在混淆矩阵()中使用它们?
I guess you are referring to confusionMatrix()
from caret
.我猜你指的是caret
confusionMatrix()
。 This is already a confusion matrix, and you can just pass the predictions into the function using as.table(), see example, where we set up a model and train / test data:这已经是一个混淆矩阵,您可以使用 as.table() 将预测传递给函数,请参见示例,我们在其中设置模型并训练/测试数据:
library(caret)
set.seed(111)
idx = sample(1:nrow(iris),100)
trainData = iris[idx,]
testData = iris[-idx,]
mdl = train(Species ~ .,data=trainData,
method="rf",trControl=trainControl(method="cv"))
pred = predict(mdl,testData)
actual = testData$Species
Confusion matrix with labels:带有标签的混淆矩阵:
confusionMatrix(pred,actual)
Confusion Matrix and Statistics
Reference
Prediction setosa versicolor virginica
setosa 20 0 0
versicolor 0 11 2
virginica 0 0 17
Confusion matrix with table or a matrix :混淆矩阵与表或矩阵:
a = matrix(table(pred,actual),nrow=3)
colnames(a) = levels(testData$Species)
rownames(a) = levels(testData$Species)
setosa versicolor virginica
setosa 20 0 0
versicolor 0 11 2
virginica 0 0 17
confusionMatrix(as.table(a))
Confusion Matrix and Statistics
setosa versicolor virginica
setosa 20 0 0
versicolor 0 11 2
virginica 0 0 17
Overall Statistics
Accuracy : 0.96
95% CI : (0.8629, 0.9951)
No Information Rate : 0.4
P-Value [Acc > NIR] : < 2.2e-16
If you really need them in a vector, (this sounds super bizarre for me) using a:如果你真的需要在向量中使用它们,(这对我来说听起来非常奇怪)使用:
actual_vector = rep(colnames(a),colSums(a))
pred_vector = rep(rownames(a),rowSums(a))
table(actual_vector) == table(actual)
actual_vector
setosa versicolor virginica
TRUE TRUE TRUE
table(pred_vector) == table(pred)
pred_vector
setosa versicolor virginica
TRUE TRUE TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.