KNN在Mnist数据集上的实现,用的是L1距离(各像素差的绝对值的和),tf实现,十分简单的算法在MNIST上效果不错,测试正确率能大概在0.96
import numpy
import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
x = tf.placeholder("float", [None, 784])
test = tf.placeholder("float", [784])
distance = tf.reduce_sum(tf.abs(tf.add(x, tf.negative(test))),axis=1)
index = tf.arg_min(distance, 0)
init = tf.global_variables_initializer()
train_sample, train_label = mnist.train.next_batch(10000)
test_sample, test_label = mnist.test.next_batch(500)
sess = tf.Session()
sess.run(init)
accury=0
for i in range(len(test_sample)):
answer_index = sess.run(index, feed_dict={x: train_sample, test: test_sample[i]})
print('test:', i, "answer_index:", answer_index, "预测类别:",numpy.argmax(train_label[answer_index]), "真实类别:", numpy.argmax(test_label[i]),)
if numpy.argmax(train_label[answer_index])==numpy.argmax(test_label[i]):
accury=accury+1
print(accury/len(test_sample))