mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #下载并加载mnist数据
train_X, train_Y = mnist.train.next_batch(5000) # 5000 for training (nn candidates)
test_X, test_Y = mnist.test.next_batch(100) # 200 for testing
tra_X = tf.placeholder("float", [None, 784])
te_X = tf.placeholder("float", [784])
# Nearest Neighbor calculation using L1 Distance
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(tra_X, tf.negative(te_X))), reduction_indices=1)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)
accuracy = 0.
# Initializing the variables
init = tf.initialize_all_variables()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# loop over test data
for i in range(len(test_X)):
nn_index = sess.run(pred, feed_dict={tra_X: train_X, te_X: test_X[i, :]}) # Get nearest neighbor
print("Test", i, "Prediction:", np.argmax(train_Y[nn_index]), "True Class:", np.argmax(test_Y[i])) # Get nearest neighbor class label and compare it to its true label
if np.argmax(train_Y[nn_index]) == np.argmax(test_Y[i]): # Calculate accuracy
accuracy += 1./len(test_X)
print("Done!")
print("Accuracy:", accuracy)
tf 实现 KNN
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1.背景 今后博主会每周定时更新机器学习算法及其python的简单实现。今天学习的算法是KNN近邻算法。KNN算法...