'knn- same k, different result

I have a matriz ZZ. After I ran prcomp and chose the first 5 PCs I get data_new:

P= prcomp(zz)
data_new = P$x[,1:5]

then I split into training set and test set

pca_train = data_new[1:121,]
pca_test = data_new[122:151,]

and use KNN:

k <- knn(pca_train, pca_test, tempGenre_train[,1], k = 5)
a <- data.frame(k)
res <- length(which(a!=tempGenre_test))

Each time I run these 3 last rows, I get a different value in res. Why?

Is there a better way to check what is the test error?



Solution 1:[1]

I don't know why but you can use np.random.seed(32) to fix it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 patL