tensorflow100天—第5天:最近邻算法

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))

总结

  1. tensorflow可以只进行前向计算,比如本例,相当于就是numpy
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值