TensorFlow 学习笔记(1)

来源:互联网 发布:手机淘宝注册会员名 编辑:程序博客网 时间:2024/05/17 12:52

TensorFlow 的Softmax Regression 手写识别数字简单实现

使用包:tensorflow
使用数据集:MINST

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data

生成全局session

#设定session(任务)且注册为默认sessionsess = tf.InteractiveSession()

建立输入训练数据x的Placeholder,存储输入数据,大小为输入个数乘以维度(784)的矩阵.
建立w权值,b偏置。并全部设初始值为0

#设定10维的b(偏置),748*10的权重b = tf.Variable(tf.zeros([10]))w = tf.Variable(tf.random_uniform([784,10],-1,1))#输入xx = tf.placeholder(tf.float32,[None,784])

使用cross-entropy作为loss function。进行y值计算,做前向传导。
并且建立标签集y的Placeholder。

#预测出的yy = tf.nn.softmax(tf.matmul(x,w)+b)#输入的标签yy_ = tf.placeholder(tf.float32,[None,10])#代价函数coss_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))

选择一个优化器,对代价函数进行优化,取得最优解。
并设置运行session

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(coss_entropy)tf.global_variables_initializer().run()

设置每次100张图片为一组的batch。执行1000次。

for step in range(1000):    batch_xs , batch_ys = mnist.train.next_batch(100)    train_step.run({x:batch_xs,y_:batch_ys})

统计正确率:

correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))

执行后的正确率大约在92%左右,并不是很高。通过学习简单的体验了tensoflow的使用。执行了最简单的例子。

原创粉丝点击