nearest_neighbor

from __future__ import print_function

import numpy as np
import tensorflow as tf

# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

# In this example, we limit mnist data
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing

# tf Graph Input
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder("float", [784])

# Nearest Neighbor calculation using L1 Distance
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)

accuracy = 0.

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()

# Start training
with tf.Session() as sess:

    # Run the initializer
    sess.run(init)

    # loop over test data
    for i in range(len(Xte)):
        # Get nearest neighbor
        nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
        # Get nearest neighbor class label and compare it to its true label
        print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
            "True Class:", np.argmax(Yte[i]))
        # Calculate accuracy
        if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
            accuracy += 1./len(Xte)
    print("Done!")
    print("Accuracy:", accuracy)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 01.外婆的帽子 寒假剛回家,我就迫不及待地打開(kāi)了我的行李箱,因?yàn)榈谝淮螐男陆鲞h(yuǎn)門(mén)到青島上大學(xué),我一直在心里記得...
    北芊閱讀 410評(píng)論 6 5
  • Given an array of integers and an integer k, you need to ...
    cocalrush閱讀 205評(píng)論 0 0
  • 窗簾上透著光 睜開(kāi)眼睛,8點(diǎn)40 起來(lái)洗漱洗頭,倒騰倒騰出門(mén) 坐著六號(hào)線,到了漢陽(yáng),看著裝修的房子這幾天毫無(wú)進(jìn)展 ...
    11淺淺11閱讀 332評(píng)論 0 0
  • 2016年3月24日星期四 20點(diǎn)37分 地鐵線二號(hào)倒到四號(hào)線,我根據(jù)附小朱老師的提醒,從北大東門(mén)地鐵口出來(lái)。 一...
    悅者閱讀 1,570評(píng)論 2 11

友情鏈接更多精彩內(nèi)容