<jupyter_start><jupyter_text>K-nn for the  handwritten recognition dataset (MNIST) <NAME>iembre 2019 running time 30 minutes<jupyter_code>from __future__ import print_function
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import pandas as pd
import numpy as np
from skimage import exposure
import imutils
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
#Leyendo  el training y test dataset
train=pd.read_csv("c://datamining/mnist_train.csv",header=None)
test=pd.read_csv("c://datamining/mnist_test.csv",header=None)
train.info()
trainX=train.loc[:,1:785]/255
testX=test.loc[:,1:785]/255
trainY=train.loc[:,0]
testY=test.loc[:,0]
trainX.info()
#Visualizando los primeros 4 digitos
for row in trainX.head(n=4).itertuples():
        row=row[1:785]
        row=np.reshape(row,(28,28))
        print(type(row))
        plt.matshow(row)
model = KNeighborsClassifier(n_neighbors=5)
model.fit(trainX, trainY)

# Prediciendo los labels del conjunto de prueba
predictions = model.predict(testX)
# Evaluando el rendimiento del clasificador para cada uno de lpos digitos
print("EVALUATION ON TESTING DATA")
print(classification_report(testY, predictions))
confusion_matrix(testY,predictions)
# Cotejando las predicciones contra las imagenes 
# Eligiendo al azar una imagen
import numpy as np
from skimage import exposure
import imutils
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
test1=np.array(testX)
i=np.random.randint(0, 784)
image=test1[i].reshape(1,-1)
print(type(image))
prediction = model.predict(image)[0]
# Convirtiendo la imagen de un arreglo de dimension 728 a una imagen de dimension 64x64 compatibel con OpenVC
# rescalando luego a una imagen de 32x32 pixels para que se vea mejor
#image = image.reshape((28, 28)).astype("uint8")
image=np.reshape(image,(28,28))
#image = exposure.rescale_intensity(image, out_range=(0, 255))
#image = imutils.resize(image, width=32, inter=cv2.INTER_CUBIC)
# Mostrando la prediccion
print("The image represents the digit: {}".format(prediction))
#plt.gray() 
plt.matshow(image) 
#plt.show()<jupyter_output><class 'numpy.ndarray'>
The image represents the digit: 1
{'fraction_non_alphanumeric': 0.10385626643295355, 'fraction_numerical': 0.03155127081507449, 'mean_word_length': 6.388349514563107, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '163657', 'license': 'MIT', 'n_tokens_mistral': 821, 'n_tokens_neox': 778, 'n_words': 210, 'path': 'notebooks/handwrittenknn.ipynb', 'repo_name': 'eacunafer/Data-Mining-Machine-Learning-subgraduado-', 'size': '2291'}