import structimport itertoolsimport numpy as npfrom sklearn import neighbors, metricsimport matplotlib.pyplot as plt%matplotlib inline# Function to read imagesdef read_idx(filename):    with open(filename, ‘rb’) as f:        zero, data_type, dims = struct.unpack(‘>HBB’, f.read(4))        shape = tuple(struct.unpack(‘>I’, f.read(4))0 for d in range(dims))        return np.fromstring(f.read(), dtype=np.uint8).reshape(shape)def plot_confusion_matrix(cm, classes,                          normalize=False,                          title=’Confusion matrix’,                          cmap=plt.cm.Blues):    “””    This function prints and plots the confusion matrix.    Normalization can be applied by setting `normalize=True`.    “””    if normalize:        cm = cm.astype(‘float’) / cm.sum(axis=1):, np.newaxis        print(“Normalized confusion matrix”)    else:        print(‘Confusion matrix, without normalization’)    print(cm)    plt.imshow(cm, interpolation=’nearest’, cmap=cmap)    plt.title(title)    plt.colorbar()    tick_marks = np.arange(len(classes))    plt.xticks(tick_marks, classes, rotation=45)    plt.yticks(tick_marks, classes)    fmt = ‘.2f’ if normalize else ‘d’    thresh = cm.max() / 2.    for i, j in itertools.product(range(cm.shape0), range(cm.shape1)):        plt.text(j, i, format(cmi, j, fmt),                 horizontalalignment=”center”,                 color=”white” if cmi, j > thresh else “black”)    plt.tight_layout()    plt.ylabel(‘True label’)    plt.xlabel(‘Predicted label’)””” Load the training dataset “””# Load raw image training datasetraw_train = read_idx(‘train-images-idx3-ubyte’)# Reshape the (60000, 28, 28) array to two dimensionstrain_data = np.reshape(raw_train, (60000, 28*28))# Load training image label datasettrain_label = read_idx(‘train-labels-idx1-ubyte’)””” Load the testing dtaset “””# Load raw image testing datasetraw_test = read_idx(‘t10k-images-idx3-ubyte’)# Reshape the (10000, 28, 28) array to two dimensionstest_data = np.reshape(raw_test, (10000, 28*28))# Load testing image label datasettest_label = read_idx(‘t10k-labels-idx1-ubyte’)””” Train the KNN method using training data “””idx = (train_label == 2)|(train_label == 3)|(train_label == 8)X = train_dataidxY = train_labelidxknn = neighbors.KNeighborsClassifier(n_neighbors = 3).fit(X, Y)idx = (test_label == 2)|(test_label == 3)|(test_label == 8)x_test = test_dataidxy_true = test_labelidxy_pred = knn.predict(x_test)cm = metrics.confusion_matrix(y_true, y_pred)plot_confusion_matrix(cm, “2”, “3”, “8”, normalize=True)idx = np.where((y_pred == 2) & (y_true == 8))0fig = plt.figure(figsize = (5, 30))for i in range(len(idx)):    ax = fig.add_subplot(len(idx), 1, i+1)    imgplot = ax.imshow(np.reshape(x_testidxi, :, (28, 28)), cmap = plt.cm.get_cmap(“Greys”))    imgplot.set_interpolation(“nearest”)plt.show()