text_plain_output_5.png text_plain_output_4.png image_output_5.png text_plain_output_3.png image_output_4.png text_plain_output_2.png text_plain_output_1.png image_output_3.png image_output_2.png image_output_1.png
from scipy.sparse import csr_matrix

from sklearn.neighbors import KNeighborsClassifier

import matplotlib.pyplot as plt

import pandas as pd

import random

train_data = pd.read_csv('../input/digit-recognizer/train.csv')
test_data = pd.read_csv('../input/digit-recognizer/test.csv')
train_size = round(0.8 * len(train_data))
val_size = round(0.2 * len(train_data))
train_features = train_data[:train_size]
val_features = train_data[train_size:]
train_labels = train_features.pop('label')
val_labels = val_features.pop('label')

model = KNeighborsClassifier(n_neighbors=3)
train_matrix = csr_matrix(train_features.values)
model.fit(train_matrix, train_labels.values)

def show_image(img):
    plt.figure()
    plt.imshow(img, cmap=plt.cm.binary)
    plt.colorbar()
    plt.grid(False)
    plt.show()
def predict(model, image_num):
    image = test_data.iloc[image_num, 0:].values.reshape(28, 28)
    image_matrix = csr_matrix(test_data.iloc[image_num, 0:].values)
    class_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    prediction = model.predict(image_matrix)
    print('Prediction: ' + str(prediction[0]))
    show_image(image)
def make_n_predictions(model, n):
    for i in range(n):
        random_image = random.randint(0, 27999)
        predict(model, random_image)
make_n_predictions(model, 5)