from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

mnist = read_data_sets('data/', one_hot=True)

train_pixels, train_list_values = mnist.train.next_batch(100)

test_pixels, test_list_values = mnist.train.next_batch(10)

train_pixel_tensor = tf.placeholder(dtype=tf.float32, shape=[None, 784])
test_pixels_tensor = tf.placeholder(dtype=tf.float32, shape=[784])

distance = tf.reduce_sum(
	tf.abs(
		tf.add(
			train_pixel_tensor,
			tf.negative(test_pixels_tensor)
		)
	),
	reduction_indices=1
)

pred = tf.arg_min(distance, 0)

accuracy = 0

init = tf.global_variables_initializer()

with tf.Session() as session:
	session.run(init)
	
	for i in range(len(test_list_values)):
		
		print(test_pixels)
		
		nn_index = session.run(
			pred,
			feed_dict={
				train_pixel_tensor: train_pixels,
				test_pixels_tensor: test_pixels[i, :]
			}
		)
		
		trained_value = train_list_values[nn_index]
		true_value = train_list_values[i]
		
		trained_value_number = np.argmax(trained_value)
		true_value_number = np.argmax(true_value)
		print('test N %s Predicted Class: %s, True Class: %s, %s'
			  % (i,
				 trained_value_number,
				 true_value_number,
				 trained_value_number == true_value_number
				 )
			  )
		
		if trained_value_number == true_value_number:
			accuracy += 1.0 / len(test_pixels)
			
			image = np.reshape(train_pixels[nn_index], [28, 28])
			plt.imshow(image)
			plt.show()
		
	print('Accuracy = %s' % accuracy)
