列表给出一个空值到倒数第二个单元格
List giving an empty values upto penultimate cell
以下是我正在尝试的代码 run.The 主要 objective 是针对不同 K 值的模型 运行 然后在计算精度后选择最佳 K 值.
所以我想到了使用 for 循环,其中每个 model.Result 和各自的准确度都存储在列表中。然后在发送之后与各自的 k 值一起发送。
但问题在于以下代码......该列表没有来自 1:29 的任何值并且有 30..
的预测值
k = 1:30
for(l in k){
pre[[l]] = knn(train_dataset,test_dataset,cl = labels_train, k = l)
}
输出:
enter image description here
谁能帮我解决这个问题....比如为什么列表会这样,应该怎么做才能得到正确的结果..为什么会这样..?
这是一个解决方案,使用 中的代码拟合模型。
library(class)
set.seed(1) # Make the results reproducible
knn_list <- lapply(1:30, function(l){
knn(train_dataset, test_dataset, cl = labels_train, k = l)
})
ok <- sapply(knn_list, '==', labels_test)
acc <- colMeans(ok)
which(acc == max(acc))
plot(acc, type = "b")
题目中的for
循环也可以是运行,只要事先创建结果列表即可。结果是一样的。
set.seed(1) # Make the results reproducible
k <- 1:30
pre <- vector("list", length = 30)
for(l in k){
pre[[l]] <- knn(train_dataset, test_dataset, cl = labels_train, k = l)
}
identical(pre, knn_list)
#[1] TRUE
示例数据
set.seed(2021)
n <- nrow(iris)
i <- sample(n, 0.7*n)
train_dataset <- iris[i, -5]
test_dataset <- iris[-i, -5]
labels_train <- iris[i, 5]
labels_test <- iris[-i, 5]
以下是我正在尝试的代码 run.The 主要 objective 是针对不同 K 值的模型 运行 然后在计算精度后选择最佳 K 值.
所以我想到了使用 for 循环,其中每个 model.Result 和各自的准确度都存储在列表中。然后在发送之后与各自的 k 值一起发送。 但问题在于以下代码......该列表没有来自 1:29 的任何值并且有 30..
的预测值 k = 1:30
for(l in k){
pre[[l]] = knn(train_dataset,test_dataset,cl = labels_train, k = l)
}
输出:
enter image description here
谁能帮我解决这个问题....比如为什么列表会这样,应该怎么做才能得到正确的结果..为什么会这样..?
这是一个解决方案,使用
library(class)
set.seed(1) # Make the results reproducible
knn_list <- lapply(1:30, function(l){
knn(train_dataset, test_dataset, cl = labels_train, k = l)
})
ok <- sapply(knn_list, '==', labels_test)
acc <- colMeans(ok)
which(acc == max(acc))
plot(acc, type = "b")
题目中的for
循环也可以是运行,只要事先创建结果列表即可。结果是一样的。
set.seed(1) # Make the results reproducible
k <- 1:30
pre <- vector("list", length = 30)
for(l in k){
pre[[l]] <- knn(train_dataset, test_dataset, cl = labels_train, k = l)
}
identical(pre, knn_list)
#[1] TRUE
示例数据
set.seed(2021)
n <- nrow(iris)
i <- sample(n, 0.7*n)
train_dataset <- iris[i, -5]
test_dataset <- iris[-i, -5]
labels_train <- iris[i, 5]
labels_test <- iris[-i, 5]