tensorflow入门1 基本用法和最近邻算法

#tensorflow入门例子
import tensorflow as tf
hello = tf.constant('Hello, Tensorflow!')
sess = tf.Session()
print sess.run(hello)
print "--------------"
##################################################
#basic Operations
a = tf.constant(2)
b = tf.constant(3)
with tf.Session() as sess:
    print sess.run(a+b)
    print sess.run(a*b)
print "--------------"
###################################################
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
add = tf.add(a,b)
mul = tf.mul(a,b)
with tf.Session() as sess:
    print sess.run(add,feed_dict={a:2,b:3})
    print sess.run(mul,feed_dict={a:2,b:3})
print "--------------"
####################################################
matrix1 = tf.constant([[3.,3.]])#1*2矩阵
matrix2 = tf.constant([[2.],[2.]])#2*1
product = tf.matmul(matrix1,matrix2)
with tf.Session() as sess:
    result = sess.run(product)
    print result
print "--------------"
#################################################
#最近邻算法
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./MNIST_data/",one_hot=True)#one_hot是对标签进行one-hot

Xtr,Ytr = mnist.train.next_batch(5000)
Xte,Yte = mnist.test.next_batch(200)

xtr = tf.placeholder("float",[None,784])
xte = tf.placeholder("float",[784])
#计算L1距离,两点各个维度做差,取绝对值后求和
#tf.neg()取负
#tf.reduce_sum()按照reduction_indices指定的轴进行求和1代表对行求和
distance = tf.reduce_sum(tf.abs(xtr-xte),reduction_indices=1)
#换成欧氏距离,结果没有影响
#distance = tf.reduce_sum(tf.square(xtr-xte),reduction_indices=1)
#arg_min函数得到distance中值最小的下标
pred = tf.arg_min(distance,0)
accuracy = 0.
init = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init)
    for i in range(len(Xte)):
        nn_index = sess.run(pred,feed_dict={xtr:Xtr,xte:Xte[i,:]})
        print i,np.argmax(Ytr[nn_index]),np.argmax(Yte[i])
        if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
            accuracy += 1./len(Xte)
    print accuracy
结果准确率92%









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值