简体   繁体   中英

return the value of the nearest neighbor

I want to use the knn method for classification, but in addition to retrieving the appropriate label, I also need to retrieve the values of the nearest neighbor (to the test data). How can I retrieve the nearest neighbor in 1nn? For example, I have the following data

#this is the train data
X   Y   L
1   4   T
2   5   F
3   6   T
#this is the test data
X   Y   L
8   3   T
#knn with k=1
knn(train[,-3],test[,-3],train$L,k=1)

The response of this function is only the appropriate label("T"), but I want to return the value of the nearest neighbor(For example, here it is returned: row 3:3 6 T) please help me.

Several different packages have implementations of knn and you do not say which you are using. Not all of them provide the neighbor, but the version of knn in FNN does.

library(FNN)
KNN_Model = knn(train[,-3],test[,-3],train$L,k=1)
attr(KNN_Model, "nn.index")
     [,1]
[1,]    3

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