Skip to content

Instantly share code, notes, and snippets.

@codeboy101
Created March 16, 2017 07:16
Show Gist options
  • Select an option

  • Save codeboy101/7d2f802fd76ff29bf3ae3a9cdb74efa9 to your computer and use it in GitHub Desktop.

Select an option

Save codeboy101/7d2f802fd76ff29bf3ae3a9cdb74efa9 to your computer and use it in GitHub Desktop.
import numpy as np
import loader
train_features, train_labels, test_features, test_labels = loader.load_images('TrainImages')
train_features = np.reshape(train_features,(500, 4000))
train_labels = np.reshape(train_labels, (500, 2))
test_features = np.reshape(test_features, (550, 4000))
test_labels = np.reshape(test_labels, (550, 2))
train_data = zip(train_features, train_labels)
test_data = zip(test_features, test_labels)
def get_index(labels):
if labels[0] == 1: return 0
else: return 1
def l1_distance(img1, img2):
return np.sum(np.abs(img1.ravel() - img2.ravel()))
def nearest_neighbor(img):
all_dists = {l1_distance(img, each[0]):get_index(each[1]) for each in train_data}
return min(all_dists), all_dists[min(all_dists)] # ValueErro: min(arg), arg is an empty sequence error
def run_model(test):
classification = []
for entry in test:
label = nearest_neighbor(entry[0])
classification.append((label[1], entry[1]))
return sum(i == j for i, j in classification)
result = run_model(test_data)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment