[英]How to access values of predict() function in R for storage?
I'm training a K-nearest neighbors model for a class. The catch is that they ask us to train it with the whole database, except for the row being predicted.我正在为 class 训练一个 K-最近邻 model。问题是他们要求我们用整个数据库训练它,除了被预测的行。
My plan is to initialize a vector for storage and run a for loop to loop over every row omitting that specific row for training, then appending the prediction value to the vector, and calculating accuracy after the loop:我的计划是初始化一个用于存储的向量,并运行一个 for 循环以遍历每一行,省略特定行进行训练,然后将预测值附加到向量,并在循环后计算精度:
results <- c()
for (i in nrow(data) {
model.kknn <- train.kknn(data[-i,11]~., data = data[-i,1:10],kmax = 7, scale = TRUE)
pred <- predict(model,data[i,1:10])
results <- c(results,pred)
}
I'm expecting the vector results
to be a series of 1s and 0s.我期望矢量
results
是一系列 1 和 0。 However, I tried looping just the first row and the value of results
is 2
.但是,我尝试只循环第一行,
results
的值为2
。
When printing pred
the value is:打印
pred
时的值为:
[1] 1
Levels: 0 1
Any idea how I can get the 1 to append to the vector results
?知道如何将 1 到 append 转换为矢量
results
吗?
Specify 1:N
in the for() part, and it's best not to "grow" a vector but rather to initialize an empty vector of the appropriate length and fill it in.在 for() 部分指定
1:N
,最好不要“增长”一个向量,而是初始化一个适当长度的空向量并填充它。
N <- nrow(data)
results <- vector(length=N)
for (i in 1:N) {
model.knn <- train.kknn(data[-i,11]~., data=data[-i,1:10], kmax=7, scale=T)
results[i] <- predict(model.knn, data[i,1:10,drop=F])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.