简体   繁体   English

R 中的 KNN 混淆矩阵?

[英]Confusion matrix with KNN in R?

How do I produce a confusion matrix to see the precision, recall and F score for a KNN model in R?如何生成混淆矩阵以查看 R 中 KNN model 的精度、召回率和 F 分数? Here's my R code for the KNN model:这是我的 KNN model 的 R 代码:

nn <- knn(train = train.norm.df[, 1:14], test = new.norm.df, cl = train.norm.df[, 3], k = 3)

How do I display this model, nn in a confusion matrix?如何在混淆矩阵中显示这个 model, nn

Markdown file: https://rpubs.com/evanmullen36/840780 Markdown 文件: https://rpubs.com/evanmullen36/840780

You should always provide reproducible data with your question and code.您应该始终为您的问题和代码提供可重现的数据。 Here is an example of what you are trying to do using the iris data set which is included with R.这是您尝试使用 R 中包含的iris数据集执行的操作的示例。 First we need training and testing subsets of the data:首先,我们需要训练和测试数据子集:

library(class)
data(iris)

set.seed(42)
idx <- seq(nrow(iris))
train <- unname(unlist(tapply(idx, iris$Species, sample, size=25)))
train <- sort(train)
test <- idx[!idx %in% train]

Now you can use the nearest neighbor function:现在您可以使用最近邻 function:

predict <- knn(iris[train, 1:4], iris[test, 1:4], iris$Species[train])
(conftbl <- table(Species=iris$Species[test], Predict=predict))
#             Predict
# Species      setosa versicolor virginica
#   setosa         25          0         0
#   versicolor      0         25         0
#   virginica       0          2        23

Correct <- sum(diag(conftbl))/sum(conftbl) * 100
cat("Percent Correct = ", round(Correct, 2))
# Percent Correct =  97.33

Notice that in your example you included a column in both the train= and cl= arguments (column 3 is in both).请注意,在您的示例中,您在train=cl= arguments 中都包含了一列(两者都包含第 3 列)。 That means that you used the class membership to predict the class membership which is circular.这意味着您使用 class 成员资格来预测循环的 class 成员资格。 If column 3 is the class membership you should use train = train.norm.df[, c(1:2, 4:14)] and test = new.norm.df[, c(1:2, 4:14)] .如果第 3 列是 class 成员资格,则应使用train = train.norm.df[, c(1:2, 4:14)]test = new.norm.df[, c(1:2, 4:14)] .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM