I am using the classic
iris dataset and trying to learn the Knn algorithm for different values of
k. I perform a
train-test-validation split to generate 3 partitions. After this, I use the train and test to fit a knn classifier. But I get an error after splitting.
spec = c(train = .5, test = .25, validate = .25) byparts = sample(cut( seq(nrow(iris)), nrow(iris)*cumsum(c(0,spec)), labels = names(spec) )) res = split(iris, byparts) addmargins(prop.table(table(byparts))) #Model fit library(class) train_feat <- res$train[,1:4] test_feat <- res$test[,1:4] set.seed(1) train_pred <- knn(train_feat, train_feat, res$train["Species"], k=1) train_acc <- mean(train_pred == res$train["Species"]) set.seed(1) test_pred <- knn(train_feat, test_feat, res$train["Species"], k=1) test_acc <- mean(valid_pred == res$test["Species"]) cat('Training Accuracy: ', train_acc, '\n', 'Validation Accuracy: ', valid_acc, sep='')
It says the
class have different lengths
Error in knn(train_feat, train_feat, res$train["Species"], k = 1) : 'train' and 'class' have different lengths
Is this due to the way how I split the partition or should I re-split it again? Would like to know what am I doing wrong?