Skip to content

Instantly share code, notes, and snippets.

@Azadehkhojandi
Created November 20, 2017 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Azadehkhojandi/14f1e1c6aece8e3e83507c66c773face to your computer and use it in GitHub Desktop.
Save Azadehkhojandi/14f1e1c6aece8e3e83507c66c773face to your computer and use it in GitHub Desktop.
K-Nearest Neighbors with the MNIST Dataset
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.image as mp_image
import matplotlib.pyplot as mp_pyplot
mnist = input_data.read_data_sets("minst_data/", one_hot=True)
training_digits, training_lables = mnist.train.next_batch(5000)
test_digits, test_lables = mnist.train.next_batch(10)
training_digits_pl = tf.placeholder("float", [None, 784])
test_digit_pl = tf.placeholder("float", [784])
l1_distance = tf.abs(tf.add(training_digits_pl, tf.negative(test_digit_pl)))
distance = tf.reduce_sum(l1_distance, axis=1)
pred = tf.arg_min(distance, 0)
accuracy = 0
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(len(test_digits)):
pixels = test_digits[i].reshape((28, 28))
mp_pyplot.imshow(pixels, cmap='gray')
mp_pyplot.show()
nn_index = sess.run(pred, feed_dict={
training_digits_pl: training_digits,
test_digit_pl: test_digits[i, :]
})
match = True
if np.argmax(training_lables[nn_index]) != np.argmax(test_lables[i]):
match = False
print("match:", match,"\t", "prediction:", np.argmax(
training_lables[nn_index]), "true lable", np.argmax(test_lables[i]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment