【问题标题】:R-task on Boston dataset part of MASS library in R. Task: Plot accuracy of KNN, K=1:50.R 中 MASS 库的波士顿数据集部分的 R 任务。任务:绘制 KNN 的精度,K=1:50。
【发布时间】:2018-03-23 12:45:46
【问题描述】:

我已经完成了以下操作,但它给了我一个错误,说 NAs 是由强制引入的

ourBoston=data.frame(Boston)
ourBoston$high.medv=NA
levels(ourBoston$high.medv)=c("no","yes")
ourBoston$high.medv[Boston$medv>25]<-"yes"
ourBoston$high.medv[Boston$medv<=25]<-"no"

result<-rep(0,50)
for (i in 1:50) {
   result=knn(train=data.frame(ourBoston$lstat),test=data.frame(ourBoston$lstat),cl=ourBoston$high.medv,k=i)
  result[i]=sum(as.integer(ourBoston$high.medv))/length(result)
}
qplot(1:50,result[1:50])

我创建了一个列并将其添加到一个新的数据框->ourBoston

lstat 变量是我必须为响应变量 high.medv 选择的最佳预测变量。

训练和测试数据集必须相同。

在运行代码时,我收到 50 条警告:In as.integer(ourBoston$high.medv) : NAs引入了强制

【问题讨论】:

    标签: r machine-learning data-science


    【解决方案1】:

    您的尝试中有一些不清楚的地方,我做了一些假设。

    首先要澄清一些关于你的代码的事情。 如果它已经是一个,你不应该需要在data.frame() 中包装一些东西,通过查看类来检查它,例如class(Boston).

    在分配对象时,坚持使用&lt;-= 会有所帮助,使用&lt;- 更容易阅读。

    您尝试创建因子的方式有点繁琐,您可以使用ifelse 根据布尔检查分配结果。输入?ifelse阅读更多内容。

    在您的for 循环中,您再次将knn 模型的结果分配给result,这会覆盖您为存储结果而创建的向量。这是您尝试的最大问题之一。

    之后您还不清楚您要计算什么,我提供了一个确定准确性的简单方法的示例。这通过检查预测值是否与Boston 中的原始值相等并计算mean 来工作。

    library(MASS)
    library(ggplot2)
    library(class)
    
    # The call to `data.frame` here is not required, its already one.
    # ourBoston=data.frame(Boston)
    ourBoston <- Boston
    
    # You are going about the assignment of high.medv poorly
    # You can create a factor like so:
    ourBoston$high.medv <- factor(ifelse(ourBoston$medv > 25, "yes", "no"))
    
    
    result <- rep(0, 50)
    
    # seq_along() is preferable, as it makes sure you iterate over each regardless
    for (i in seq_along(result)) {
    
      # you cant assign this to result, you overwrite your vector from before...
      knn_result <- knn(train = ourBoston['lstat'],
                        test = ourBoston['lstat'],
                        cl = ourBoston$high.medv,
                        k = i)
    
      # not sure what you are trying to do here
      # result[i] <- sum(as.integer(ourBoston$high.medv))/length(result)
    
      # calculating accuracy
      result[i] <- mean(knn_result == ourBoston$high.medv)
    
    }
    qplot(seq_along(result), result)
    

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多