我试图使用train()
Caret 包中的函数来拟合 K 最近邻模型。这给了我一个错误。我的代码是:
"%+%" <- function(x,y) paste(x, y, sep = "")
set.seed(28)
ContEnt <- trainControl(method = "repeatedcv", number = 10, repeats = 3)
EducKnn <- train(as.formula("pp04b_cod ~ " %+% paste(VarEduc[!VarEduc %in% NoRel], collapse
= " + ")), EducPrueba, method = "knn", trctrl = ContEnt,
tuneLength = 10)
这给了我回报:
Warning: predictions failed for Resample01: k= 5 Error in knn3Train(train = structure(c(0.569069692629571, 0.569069692629571, :
unused argument (trctrl = list("cv", 10, NA, "grid", 0.75, NULL, 1, TRUE, 0, FALSE, TRUE, "final", FALSE, FALSE, function (data, lev = NULL, model = NULL)
{
if (is.character(data$obs)) data$obs <- factor(data$obs, levels = lev)
postResample(data[, "pred"], data[, "obs"])
}, "best", list(0.95, 3, 5, 19, 10, 0.9), NULL, NULL, NULL, NULL, 0, c(FALSE, FALSE), NA, list(5, 0.05, "gls", TRUE), FALSE, TRUE))
许多类似的警告信息,最后:
Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info =
trainInfo, :
There were missing values in resampled performance measures.
Something is wrong; all the Accuracy metric values are missing:
Accuracy Kappa
Min. : NA Min. : NA
1st Qu.: NA 1st Qu.: NA
Median : NA Median : NA
Mean :NaN Mean :NaN
3rd Qu.: NA 3rd Qu.: NA
Max. : NA Max. : NA
NA's :10 NA's :10
Error: Stopping
>
设置参数以避免交叉验证,似乎没有解决它。
ContEnt <- trainControl(method = "none")
此外,在 train() 中设置 na.action = na.omit 会得到相同的结果。有趣的是,类包的 knn() 函数完美地工作,使用 0.75 的训练集,在同一组变量上。
Entre <- createDataPartition(EducPrueba$pp04b_cod, 1, 0.75, list = FALSE)
EducKnn <- knn(train = EducPrueba[Entre, VarEduc[!VarEduc %in% NoRel]], test = EducPrueba[-Entre,
VarEduc[!VarEduc %in% NoRel]], cl = EducPrueba$pp04b_cod[Entre], k = 5)
最后,可以肯定的是,EducPrueba 没有 NA 或 NaN:
> any(is.na(EducPrueba))
[1] FALSE
> any(unlist(lapply(EducPrueba, is.nan)))
[1] FALSE
VarEduc 中的变量已经居中和缩放。有谁知道如何使它工作?我将 R Portable 3.5.2 与 RStudio 一起使用。包插入符号 6.0-81 和类 7.3-15。我不知道如何上传数据框,所以这可以是一个可重现的例子。