我正在使用 knn 来估计随机数据,并且我正在从向量中选择不同的 k。每个 knn 返回一个长度为 200 的向量,我有 13 个 k,所以我需要在 for 循环之前初始化一个 13x200 的向量。我想做类似的事情
knn_train <- rep(0,1000)
但是对于多维向量。
这是我的代码:
library(class)
library(MASS)
#List of k's for use in knn
k <- c(1,4,7,10,13,16,30,45,60,80,100,150,200)
#Generate identity matrix for sigmas
sigma <- diag(2)
# Class 1
mu_green <- c(-.5,.5)
green_train <- mvrnorm(100, mu_green,sigma)
green_test <- mvrnorm(100, mu_green,sigma)
#Class 0
mu_red <-c(-.2,.6)
red_train<- mvrnorm(100, mu_red,sigma)
red_test<- mvrnorm(100, mu_red,sigma)
#Bind test and train data
train <- rbind(green_train,red_train)
test <- rbind(green_test,red_test)
cl <- rbind(c(rep(1,100),rep(0,100)))
for(i in 1:length(k))
{
#Train into train then train into test
knn_train[i] = knn(train,train,cl,k[i],prob=TRUE)
knn_test[i] = knn(train,test,cl,k[i],prob=TRUE)
#First 100 are class 1, second 100 are class 2
train_err[i]<- 100-sum(table(knn_train[i][1:100]))+sum(table(knn[i][100:200]))
test_err[i]<- 100-sum(table(knn_test[i][1:100]))+sum(table(knn[i][100:200]))
}