# coding:utf-8
'''
最近邻域分类器
'''
import numpy as np
import tensorflow as tf
import os
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('D:/Develop/DL/deeplearning-notes/datas/mnist',one_hot=True)
X_train,Y_train = mnist.train.next_batch(10000)
X_test,Y_test = mnist.test.next_batch(2000)
xtrain = tf.placeholder(tf.float32,[None,784])
xtest = tf.placeholder(tf.float32,[784])
# 使用L1计算
distance = tf.reduce_sum(tf.abs(tf.add(xtrain,tf.negative(xtest))),axis=1)
# 预测
pred = tf.argmin(distance,0)
accuracy = 0.0
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
num_test = len(X_test)
for i in range(num_test):
nn_index = sess.run(pred,feed_dict={xtrain:X_train,xtest:X_test[i,:]})
pred_class_label = np.argmax(Y_train[nn_index])
true_class_label = np.argmax(Y_test[i])
print('test:',i,'predicted class label:',pred_class_label,'true class label',true_class_label)
if pred_class_label == true_class_label:
accuracy += 1
print('Done')
accuracy /= num_test
print('Accuracy:',accuracy)