简体   繁体   中英

k- Nearest Neighbor Kernel Regression in R

I am using "KernelKnn" package for k-NN kernel regression with single covariate. But there is some problem and this error is showing.

 Error in if (!is.numeric(k) || is.null(k) || (k >= nrow(data)) || k <  : 
      missing value where TRUE/FALSE needed

How to correct the following prog?

 require(KernelKnn)  
 require(KernSmooth)   
 nn<-function(m,n){ 
 x<-runif(n,-1,1)  
 sd<-sd(x)   
 res <- matrix(0, m, 2)  
 for(i in 1:m){   
 y<-rexp(n,1) 
 PI <- abs(dpik(x) )                        ###plug-in  
 RoT <-abs(1.06*sd(x)*(n^(-1/5)))          ###normal scale rule     

nn1<-KernelKnn(matrix(x),TEST_data=NULL,matrix(y),k=1,weights_function='gaussian', h=PI,method = 'euclidean', regression = TRUE) 
nn2<- KernelKnn(matrix(x), TEST_data = NULL, matrix(y), k =1,weights_function='gaussian', h=RoT,method = 'euclidean', regression = TRUE) 
D1=(y-nn1)^2  
D2=(y-nn2)^2   
MSE.NN1=sum(D1)/(n)
MSE.NN2=sum(D2)/(n) 
res[i,1] =MSE.NN1   
res[i,2] =MSE.NN2  
}  
(res) 
} 
apply(nn(500,25),2,mean)  
apply(nn(500,50),2,mean) 
apply(nn(500,100),2,mean) 
apply(nn(500,150),2,mean)

You can check the documentation by running ?KernelKnn and this will solve some of your problems.

1.- According to the documentation, x and y should be either matrices or dataframes, but you have two lists instead. So use matrix(x) and matrix(y) instead of x and y .

2.- kernel K -nearest neigbors is in some sense a simple k -nearest neighbors with weighted distances, so you have to choose the closest k observations, in your case between 1 and 9. Since you have 10 observations, if you choose one of them then you can't take the closest n=10 observations as there are only 9 left.

So in summary, something like this should work

nn1<- KernelKnn(matrix(x), TEST_data= NULL, matrix(y), k =9,weights_function='gaussian', h=RoT,method = 'euclidean', regression = TRUE)

Notice however that the previous will throw an error for k=1 and k=2 , unfortunately I'm not familiar with the detailed implementation of this algorithm so I can't tell you here why is it failing in those cases.

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