python tf学习(二) 手动实现KNN算法手写数字识别
import tensorflow as tf
from tensorflow.examples.tutorials.mnist.input_data import read_data_sets
from pandas import Series
digits = read_data_sets('./')
X_train, y_train = digits.train.next_batch(5000)
X_test, y_test = digits.test.next_batch(200)
X = tf.placeholder(dtype=tf.float64, shape=784)
k = tf.placeholder(dtype=tf.float64)
l1 = tf.reduce_sum(tf.abs(X_train - X), axis=1)
min_distance_index = tf.argsort(l1)
with tf.Session() as sess:
acc = 0
for x, y in zip(X_test, y_test):
dis_index = sess.run(min_distance_index, feed_dict={X: x})
k_index = dis_index[:8]
y_k = y_train[k_index]
s = Series(y_k)
y_ = s.value_counts().idxmax()
print('预测结果', y_k)
print('真实结果', y)
print('最终预测结果:', y_)
if y_ == y:
acc += 1/200
print('准确率:', acc)
