nearest_neighbor.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. '''
  2. A nearest neighbor learning algorithm example using TensorFlow library.
  3. This example is using the MNIST database of handwritten digits
  4. (http://yann.lecun.com/exdb/mnist/)
  5. Author: Aymeric Damien
  6. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  7. '''
  8. import numpy as np
  9. import tensorflow as tf
  10. # Import MINST data
  11. from tensorflow.examples.tutorials.mnist import input_data
  12. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  13. # In this example, we limit mnist data
  14. Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
  15. Xte, Yte = mnist.test.next_batch(200) #200 for testing
  16. # tf Graph Input
  17. xtr = tf.placeholder("float", [None, 784])
  18. xte = tf.placeholder("float", [784])
  19. # Nearest Neighbor calculation using L1 Distance
  20. # Calculate L1 Distance
  21. distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.neg(xte))), reduction_indices=1)
  22. # Prediction: Get min distance index (Nearest neighbor)
  23. pred = tf.arg_min(distance, 0)
  24. accuracy = 0.
  25. # Initializing the variables
  26. init = tf.initialize_all_variables()
  27. # Launch the graph
  28. with tf.Session() as sess:
  29. sess.run(init)
  30. # loop over test data
  31. for i in range(len(Xte)):
  32. # Get nearest neighbor
  33. nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
  34. # Get nearest neighbor class label and compare it to its true label
  35. print "Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
  36. "True Class:", np.argmax(Yte[i])
  37. # Calculate accuracy
  38. if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
  39. accuracy += 1./len(Xte)
  40. print "Done!"
  41. print "Accuracy:", accuracy