jius12 2023-05-07 17:47 采纳率: 0%
浏览 40

运行KNN,预测准确率一直为1,为什么(标签-R语言)

使用R语言中蘑菇数据运行KNN时,最后预测准确率一直为1,能帮我看看是为什么吗,非常感谢。下面是我的代码


library(cba)
data(Mushroom)
Mushroom
str(Mushroom)#查看基本信息
dim(Mushroom)
Mushroom$`veil-type`<- NULL
Mushroom<- na.omit(Mushroom)
sum(is.na(Mushroom))
dim(Mushroom)
#定义因子
Mushroom$class <- as.factor(Mushroom$class)
for (i in 2:ncol(Mushroom)) {
  Mushroom[, i] <- as.numeric(factor(Mushroom[, i]))
}#转换为数值型
Mushroom
str(Mushroom)
###标准化
Mushroom[,-1] <- scale(Mushroom[,-1])
Mushroom
# 划分训练集和测试集
set.seed(123)
train_index <- sample(1:nrow(Mushroom),size=nrow(Mushroom)*0.8,replace=F)
train<- Mushroom[train_index, ]
test<- Mushroom[-train_index, ]
dim(train)
dim(test)
train
# 运行KNN算法进行分类
library(class)
knn_pred <- knn(train = train[, -1], test = test[, -1], cl = train$class, k = 5)
# 计算预测准确率
sum(knn_pred == test[,1]) /dim(test)[1]
#交叉表展示
library(gmodels)
CrossTable(x=test[,1],y=knn_pred,prop.chisq = F)
#结果
> sum(knn_pred == test[,1]) /dim(test)[1]
[1] 1
##交叉表
             | knn_pred 
   test[, 1] |    edible | poisonous | Row Total | 
-------------|-----------|-----------|-----------|
      edible |       669 |         0 |       669 | 
             |     1.000 |     0.000 |     0.593 | 
             |     1.000 |     0.000 |           | 
             |     0.593 |     0.000 |           | 
-------------|-----------|-----------|-----------|
   poisonous |         0 |       460 |       460 | 
             |     0.000 |     1.000 |     0.407 | 
             |     0.000 |     1.000 |           | 
             |     0.000 |     0.407 |           | 
-------------|-----------|-----------|-----------|
Column Total |       669 |       460 |      1129 | 
             |     0.593 |     0.407 |           | 
-------------|-----------|-----------|-----------|
  • 写回答

2条回答 默认 最新

  • 轩Scott 新星创作者: 人工智能技术领域 2023-05-07 19:36
    关注

    根据您提供的代码,我发现您的KNN算法的预测准确率一直为1,可能是由于您的测试集和训练集之间存在重复数据导致的。在划分训练集和测试集时,您使用了以下代码:

    train_index <- sample(1:nrow(Mushroom),size=nrow(Mushroom)*0.8,replace=F)
    train<- Mushroom[train_index, ]
    test<- Mushroom[-train_index, ]
    

    其中,sample()函数用于随机抽取80%的数据作为训练集,剩余的20%作为测试集。但是,由于您没有设置replace参数为FALSE,因此在抽取数据时可能会出现重复数据。这会导致测试集中的某些数据在训练集中也存在,从而导致预测准确率为1。

    为了解决这个问题,您可以将replace参数设置为FALSE,即:

    train_index <- sample(1:nrow(Mushroom),size=nrow(Mushroom)*0.8,replace=FALSE)
    train<- Mushroom[train_index, ]
    test<- Mushroom[-train_index, ]
    

    这样可以确保训练集和测试集之间没有重复数据,从而得到更准确的预测准确率。

    另外,您还可以尝试调整K值,以获得更好的预测效果。

    评论

报告相同问题?

问题事件

  • 修改了问题 5月8日
  • 创建了问题 5月7日