Hi theobroma22
My Initial matrix is 920x60. I used the 70% of this as training set and the rest 30% as test set. I did this 100 different times using sample() function and for k number 1:20. While the error rate i counted as below:
for(y in 1:100){
train_set = sample(...)
test_set = .....
accuracy = numeric()
# Repeat the prediction for 1:20 k values
for(k in 1:20){
# execute the kNN algorithm
predict = knn( train = train_set , test = test_set , cl = train_labels , k=k)
# Get the accuracy i.e the mean of the correctly predicted classes for each k value
accuracy = c(accuracy , mean(predict == test_set$classes))
}
# Store each accuracy variable into accuuracy matrix.
accuracy_matrix[s,] = accuracy
}
# Calculate the mean accuracy (mean of mean) for each k value
mean_accuracy = as.numeric(lapply(accuracy_matrix,mean))
# Plot the mean accuracy values for each k.
plot(1-mean_accuracy ,type="l",ylab="Mean error rate",
xlab="K",main="Error Rate for Treatments With Varying K (1:20) and 100 samples")
