python代码
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/data/', one_hot=True)
xtrain, ytrain = mnist.train.next_batch(2000) # 用5000个样本做容器对象
xtest, ytest = mnist.test.next_batch(200) # 200个测试样本
xi = tf.placeholder(tf.float32, [None, 784]) # 数值可变的变量都要声明成Variable
yi = tf.placeholder(tf.float32,784)
distance = tf.reduce_sum(tf.abs(tf.add(xi, tf.negative(yi) )), reduction_indices=1 )
pred = tf.argmin(distance, 0) # 最短的距离
init = tf.global_variables_initializer()
acc = 0.0
with tf.Session() as sess:
sess.run(init)
for i in range(len(xtest)):
sample = xtest[i,:]
pres_index = sess.run(pred, feed_dict={xi:xtrain, yi:sample })
pred_label = np.argmax(ytrain[pres_index])
target = np.argmax(ytest[i])
print('sample:{} | pred:{} | target:{}'.format(i, pred_label, target))
if pred_label == target:
acc += 1/len(xtest)
print('finished, final accuracy is:{}'.format(acc))
总结
- tensorflow可以只进行前向计算,比如本例,相当于就是numpy
最后
以上就是安静百合最近收集整理的关于tensorflow100天—第5天:最近邻算法python代码总结的全部内容,更多相关tensorflow100天—第5天内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复