首页 > 解决方案 > 如何在 KNN 中找到 K

问题描述

我正在重新创建示例代码

# k-NN using caret:
library(ISLR)
library(caret)

 # Split the data:


    data(iris)
    indxTrain <- createDataPartition(y = iris$Sepal.Length,p = 0.75,list = FALSE)
    training <- iris[indxTrain,]
    testing <- iris[-indxTrain,]

# Run k-NN:

    set.seed(400)
    ctrl <- trainControl(method="repeatedcv",repeats = 3)
    knnFit <- train(Species ~ ., data = training, method = "knn", trControl = ctrl, preProcess = c("center","scale"),tuneLength = 20)
    knnFit

# Use plots to see optimal number of clusters:
# Plotting yields Number of Neighbours Vs accuracy (based on repeated cross validation)
plot(knnFit)

使用上面的示例,在我的数据集上进行了尝试,但是在运行时出现错误

set.seed(400)
ctrl <- trainControl(method="repeatedcv",repeats = 3)
knnFit <- train(Engine ~ ., data =usedcars2, method = "knn", trControl = ctrl,preProcess = c("center","scale"),tuneLength = 20)

输出

Error in na.fail.default(list(Engine = c(1582, 1086, 1198, 998, 1197,  : 
  missing values in object

谁能帮我吗

标签: r

解决方案


推荐阅读