nearest_neighbor.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. '''
  2. Nearest Neighbor classification on MNIST with TensorFlow
  3. '''
  4. import numpy as np
  5. import tensorflow as tf
  6. # Import MINST data
  7. import input_data
  8. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  9. #In this example, we limit mnist data
  10. Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
  11. Xte, Yte = mnist.test.next_batch(200) #200 for testing
  12. Xtr = np.reshape(Xtr, newshape=(-1, 28*28))
  13. Xte = np.reshape(Xte, newshape=(-1, 28*28))
  14. xtr = tf.placeholder("float", [None, 784])
  15. xte = tf.placeholder("float", [784])
  16. nn = tf.Variable(tf.zeros([10]))
  17. #Calculation of L1 Distance
  18. distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.neg(xte))), reduction_indices=1)
  19. #Predict: Get min distance index (Nearest neighbor)
  20. pred = tf.arg_min(distance, 0)
  21. accuracy = 0.
  22. init = tf.initialize_all_variables()
  23. with tf.Session() as sess:
  24. sess.run(init)
  25. for i in range(len(Xte)):
  26. nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i,:]})
  27. #Get nn class label and compare it to its true label
  28. print "Test", i, "Prediction:", np.argmax(Ytr[nn_index]), "True Class:", np.argmax(Yte[i])
  29. if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
  30. accuracy += 1./len(Xte)
  31. print "Done!"
  32. print "Accuracy:", accuracy