tensorflow程序-最简单softmax模型

#-*- coding=utf-8 -*-
import numpy
import tensorflow as tf
import input_data
#读取手写字体数据源 [None,28*28]
mnist = input_data.read_data_sets("/home/tensorflow/tensorflow_workspace/data/", one_hot=True)
x = tf.placeholder("float",[None,28*28]);  #定义输入变量的大小[None,28*28]
W = tf.Variable(tf.zeros([28*28,10]));  #tf类型的一个变量。 W矩阵的大小为[28*28,10]
b = tf.Variable(tf.zeros([10]));        #tf类型的一个变量。 偏执的大小为[10]
pre_y = tf.nn.softmax( tf.matmul(x,W) + b ); # pre_y:  存放预测的概率分布,大小为[None,10]
rel_y = tf.placeholder("float",[None,10]);   # rel_y: 存放实际的分布
cross_entropy = -tf.reduce_sum( rel_y * tf.log(pre_y) );  #交叉熵作为损失函数
learn_rate = 0.01
train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(cross_entropy);

with tf.Session() as sess:
	sess.run( tf.initialize_all_variables() ); #以上的variables只有在该行后生效
	
	#训练
	for i in range(2000): #训练2000次 
		batch_x, batch_y = mnist.train.next_batch(100); #每次从样本中随机选择100个样本训练
		sess.run( train_step, feed_dict = {x:batch_x, rel_y:batch_y} ); #训练模型

	#评估
	correct_prediction = tf.equal( tf.argmax(pre_y,1), tf.argmax(rel_y,1) );
	accuracy =  tf.reduce_mean( tf.cast(correct_prediction,"float") );
	print sess.run(accuracy, feed_dict = {x:mnist.test.images, rel_y:mnist.test.labels});

函数:tf.argmax(pre_y,1)

表示将预测的结果集pre_y(形如:[[0,1],[1,0],[1,0],......])转换成最大值的id (形如:[1,0,0,......])

函数:tf.equal(tfvariable_a,tfvariable_b)

表示 判断tfvariable_a和tfvariable_b两个向量有哪些位置是相等的,最后返回:[True,False,False,......]

函数:tf.cast(correct_prediction,"float")

表示将:形如[False,False,True,......]的向量转换成float型向量如:[0,0,1,......]

最终返回测试正确率为:0.914

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值