# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: 'Python 3.8.5 64-bit (''indicadores'': conda)'
#     name: python3
# ---

# +
from sklearn.datasets import fetch_openml
import pandas as pd

mnist = fetch_openml('mnist_784', version=1, as_frame=False)
mnist.keys()
# -

X, y = mnist['data'], mnist['target']
X.shape

# +
# %matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt

some_digit = X_test[0]
some_digit_image = some_digit.reshape(28, 28)
plt.imshow(some_digit_image, cmap=mpl.cm.binary)
plt.axis("off")
plt.show()
# -

X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]

# ## K-nearest neighbord

print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

# +
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import make_scorer


param_grid = [
        {'n_neighbors': [3, 5, 7, 9], 'weights': ['uniform','distance']}
        ]

scoring = {'accuracy': make_scorer(accuracy_score),
           'precision': make_scorer(precision_score, average = 'macro'),
           'recall': make_scorer(recall_score, average = 'macro'),
           'f1_macro': make_scorer(f1_score, average = 'macro'),
           'f1_weighted': make_scorer(f1_score, average = 'weighted')}

model = KNeighborsClassifier()

grid_search = GridSearchCV(model, param_grid, cv=2, 
                           scoring=scoring, verbose=3, refit=False)

grid_search.fit(X_train, y_train)
cv_results = pd.DataFrame.from_dict(grid_search.cv_results_)
# -

cv_results.dtypes

cv_results.loc[cv_results['rank_test_f1_weighted']==1]

from sklearn.metrics import accuracy_score
# %time
print('KNN Accuracy: %.3f' % accuracy_score(y_test,prediction))

StarcoderdataJupyterScriptsDedupFiltered