简体   繁体   中英

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.

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:

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. However, I tried looping just the first row and the value of results is 2 .

When printing pred the value is:

[1] 1

Levels: 0 1

Any idea how I can get the 1 to append to the vector 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.

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])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM