nearest_neighbor.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. from __future__ import print_function
  9. import numpy as np
  10. import tensorflow as tf
  11. # Import MNIST data
  12. from tensorflow.examples.tutorials.mnist import input_data
  13. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  14. # In this example, we limit mnist data
  15. Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
  16. Xte, Yte = mnist.test.next_batch(200) #200 for testing
  17. # tf Graph Input
  18. xtr = tf.placeholder("float", [None, 784])
  19. xte = tf.placeholder("float", [784])
  20. # Nearest Neighbor calculation using L1 Distance
  21. # Calculate L1 Distance
  22. distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.neg(xte))), reduction_indices=1)
  23. # Prediction: Get min distance index (Nearest neighbor)
  24. pred = tf.arg_min(distance, 0)
  25. accuracy = 0.
  26. # Initializing the variables
  27. init = tf.global_variables_initializer()
  28. # Launch the graph
  29. with tf.Session() as sess:
  30. sess.run(init)
  31. # loop over test data
  32. for i in range(len(Xte)):
  33. # Get nearest neighbor
  34. nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
  35. # Get nearest neighbor class label and compare it to its true label
  36. print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
  37. "True Class:", np.argmax(Yte[i]))
  38. # Calculate accuracy
  39. if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
  40. accuracy += 1./len(Xte)
  41. print("Done!")
  42. print("Accuracy:", accuracy)