text_plain_output_1.png
from sklearn.datasets import load_digits

from sklearn.metrics import accuracy_score

import numpy as np

digits = load_digits()
X = digits.data
y = digits.target

p = 0.75
idx = int(p * X.shape[0]) + 1
X_train, X_test = np.split(X, [idx])
y_train, y_test = np.split(y, [idx])

def euclidian_metric(x, y):
    return np.sqrt(np.sum((x - y) ** 2))

y_pred_knn = []
for test_value in X_test:
    ind_min_metric = 0
    min_metric = euclidian_metric(test_value, X_train[0])
    for index, train_value in enumerate(X_train):
        metric = euclidian_metric(test_value, train_value)
        if metric < min_metric:
            min_metric = metric
            ind_min_metric = index
    y_pred_knn.append(y_train[ind_min_metric])

knn_err_rate = 1 - accuracy_score(y_test, y_pred_knn)
print('1nn classifier error: ' + str(knn_err_rate))