我使用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]))
}
答案 0 :(得分:1)
初始化“多维向量”的常用方法是创建矩阵对象:
knn_train <- matrix(NA, nrow=1000, ncol=13)
如果您想填充值,那么:
knn_train[ , i] <- # 13 element vector