I am trying to recreate Figure 2.4 from Elements of Statistical Learning, which shows the training error rate, test error rate, and optimal Bayes error rate for binary classification using $k$-nearest neighbors for various values of $k$ in $[1,150]$. The problem is, my test error rates are way too low and are below the Bayes error rate.
The data is generated hierarchically as follows. For group A, ten means $m_k$ are drawn from $N_2((1,0)',I_2)$. Observations are drawn by choosing a mean $m_k$ uniformly at random from $\{m_1,\dotsc,m_{10}\}$, and drawing the observation from $N_2(m_k, I_2/5)$. For group B, the means are drawn from $N_2((0,1)',I_2)$ instead of $N_2((1,0)',I_2)$.
Here is my code for generating training and test data:
library(MASS) # for mvn sampling "mvrnorm"
library(class) # for k-nearest neighbors "knn"
set.seed(1000)
meansA = mvrnorm(10,c(1,0),diag(rep(1,2)))
meansB = mvrnorm(10,c(0,1),diag(rep(1,2)))
trainingAhidden = sample(10,100,TRUE)
trainingBhidden = sample(10,100,TRUE)
testAhidden = sample(10,5000,TRUE)
testBhidden = sample(10,5000,TRUE)
trainingAdata = t(sapply(trainingAhidden,function(x) mvrnorm(1,meansA[x,],diag(rep(1,2)/5))))
trainingBdata = t(sapply(trainingBhidden,function(x) mvrnorm(1,meansB[x,],diag(rep(1,2)/5))))
testAdata = t(sapply(testAhidden,function(x) mvrnorm(1,meansA[x,],diag(rep(1,2)/5))))
testBdata = t(sapply(testBhidden,function(x) mvrnorm(1,meansB[x,],diag(rep(1,2)/5))))
trainingY = gl(2,100,200)
testY = gl(2,5000,10000)
training = list(X = rbind(trainingAdata,trainingBdata),Y = trainingY)
test = list(X = rbind(testAdata,testBdata), Y = testY)
Even 9-nearest neighbors gives a test error rate of 0.1388, way below the optimal Bayes error rate of 0.21 given in the book:
> results = knn(training$X,test$X,training$Y,k=9)
> tab = table(results,test$Y)
1 - sum(diag(tab))/sum(tab)
[1] 0.1388
What have I done wrong?