session = tf.Session()

x = tf.placeholder(tf.float32,shape=[28*28])

allx = tf.placeholder(tf.float32,shape=[None,28**2])

testimage = mnist.test.images[0]

"""
Explanation: 定義 Input 及 Output 暫存變數
Input 為 28x28 的點陣圖素
Output 為 10 個 Label Array ，分別代表著 0~9 的預測值
End of explanation
"""


dist = tf.reduce_sum(tf.abs(tf.sub(x,allx)), reduction_indices=1)

l2dist = session.run(tf.reduce_sum(tf.sub(x,allx),1),feed_dict={x:testimage,allx:mnist.train.images})

"""
Explanation: 使用 reduce sum 來計算測試圖片與所有的 Training 圖片的的距離
reduce sum 請參考 : https://www.tensorflow.org/versions/r0.11/api_docs/python/math_ops.html#reduce_sum
End of explanation
"""


predict = tf.arg_min(dist,0)
predictl2 = tf.arg_min(l2dist,0)


def dopredict(testimage):
    return (session.run(predict,feed_dict={x:testimage,allx:mnist.train.images}),
            session.run(predict,feed_dict={x:testimage,allx:mnist.train.images}))

def draw(img):
    tmp = img
    tmp2 = tmp.reshape((28,28))

    plt.imshow(tmp2, cmap = cm.Greys)
    plt.show()


import random
for img in  list(map(lambda _: random.choice(mnist.test.images), range(1))): #mnist.train.images[50:55]:
    draw(img)
    
    p,p2 = dopredict(img)
#     print p,p2
    print(numpy.argmax(mnist.train.labels[p]))
    print(numpy.argmax(mnist.train.labels[p2]))

"""
Explanation: 距離最近的那張圖片及為預測結果
End of explanation
"""


