# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import os
from six.moves import urllib

DOWNLOAD_ROOT = "https://raw.githubusercontent.com/kscanne/1070/master/lab07/"
TRAIN_URL = DOWNLOAD_ROOT + "train.csv"
TEST_URL = DOWNLOAD_ROOT + "test.csv"
DATASET_PATH = "/Users/goople/slu-workspace/ml/handson-ml"

def fetch_data(train_url=TRAIN_URL, test_url=TEST_URL, dataset_path=DATASET_PATH):
    if not os.path.isdir(dataset_path):
        os.makedirs(dataset_path)
    train_path = os.path.join(dataset_path, "train.csv")
    test_path = os.path.join(dataset_path, "test.csv")
    urllib.request.urlretrieve(train_url, train_path)
    urllib.request.urlretrieve(test_url, test_path)



# -

fetch_data()

# +
import numpy as np

def load_data(dataset_path=DATASET_PATH):
    csv_train_path = os.path.join(dataset_path, "train.csv")
    csv_test_path = os.path.join(dataset_path, "test.csv")
    return np.genfromtxt(csv_train_path, delimiter=','), np.genfromtxt(csv_test_path, delimiter=',')



# -

train_data, test_data = load_data()

print(train_data)

y_train = train_data[:,0]
X_train = train_data[:,1:]
y_test = test_data[:,0]
X_test = test_data[:,1:]


y_train

X_train

# +
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)

def show_digit(some_digit):
    some_digit_image = some_digit.reshape(28, 28)
    plt.imshow(some_digit_image, cmap = mpl.cm.binary,
           interpolation="nearest")
    plt.axis("off")
    plt.show()


# -

show_digit(X_train[2500])

y_train[2500]


def binary_classifier(example, digit, K):
    S = []
    for x, y in zip(X_train, y_train):
        diff = np.sum((np.absolute(example-x)))
        S.append((diff, y))
    S.sort(key=lambda x: x[0])
    y = 0
    for k in range(K):
        if S[k][1] == digit:
            y += 1
        else:
            y -= 1
    return np.sign(y)


def multiclass_classifier(example, K):
    digit = 0
    while binary_classifier(example, digit, K) < 1 and digit < 10:
        digit += 1
    return digit


multiclass_classifier(X_train[2500], 100)


def accuracy():
    TP = 0
    for x,y in zip(X_test, y_test):
        if multiclass_classifier(x, 10) == y:
            TP += 1
    return TP/100


accuracy()



StarcoderdataJupyterScriptsDedupFiltered