nearest_neighbor.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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.negative(xte))), reduction_indices=1)
  23. # Prediction: Get min distance index (Nearest neighbor)
  24. pred = tf.arg_min(distance, 0)
  25. accuracy = 0.
  26. # Initialize the variables (i.e. assign their default value)
  27. init = tf.global_variables_initializer()
  28. # Start training
  29. with tf.Session() as sess:
  30. # Run the initializer
  31. sess.run(init)
  32. # loop over test data
  33. for i in range(len(Xte)):
  34. # Get nearest neighbor
  35. nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
  36. # Get nearest neighbor class label and compare it to its true label
  37. print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
  38. "True Class:", np.argmax(Yte[i]))
  39. # Calculate accuracy
  40. if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
  41. accuracy += 1./len(Xte)
  42. print("Done!")
  43. print("Accuracy:", accuracy)