R中的KNN和K折叠

机器算法验证 r 分类 交叉验证 k-最近邻 插入符号
2022-04-15 14:34:33

我想使用 KNN 在 R 中构建分类器。

我想使用各种 K 数字,每次使用 5 倍 CV - 我将如何报告每个 K 值(KNN)的准确性。

我正在使用knn()R 中的函数 - 我也一直在使用caret,所以我可以使用traincontrol(),但我对如何做到这一点感到困惑?我知道我没有包含数据,但我正在寻找更多的方法。

1个回答

要在 中使用 5 折交叉验证caret,您可以按如下方式设置“列车控制”:

trControl <- trainControl(method  = "cv",
                          number  = 5)

然后,您可以使用交叉验证来评估具有不同 k 值的 KNN 分类器的准确性

fit <- train(Species ~ .,
             method     = "knn",
             tuneGrid   = expand.grid(k = 1:10),
             trControl  = trControl,
             metric     = "Accuracy",
             data       = iris)

输出:

k-Nearest Neighbors 

150 samples
  4 predictor
  3 classes: 'setosa', 'versicolor', 'virginica' 

No pre-processing
Resampling: Cross-Validated (5 fold) 
Summary of sample sizes: 120, 120, 120, 120, 120 
Resampling results across tuning parameters:

  k   Accuracy   Kappa
   1  0.9600000  0.94 
   2  0.9600000  0.94 
   3  0.9600000  0.94 
   4  0.9533333  0.93 
   5  0.9733333  0.96 
   6  0.9666667  0.95 
   7  0.9600000  0.94 
   8  0.9666667  0.95 
   9  0.9733333  0.96 
  10  0.9600000  0.94 

Accuracy was used to select the optimal model using  the largest value.
The final value used for the model was k = 9.

有用的参考:http ://topepo.github.io/caret/index.html