TensorFlow学习(二)

Tensorflow 学习笔记(二)_MNIST手写数字识别

下载数据集

1
2
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

里面包含有55,000 数据点作为训练集 (mnist.train), 10,000 数据点作为测试集 (mnist.test), 并有 5,000 数据作验证 (mnist.validation).
每一张图片包含有28*28个像素点,被读取后,在代码展开成一个长度为784的数组

softmax回归模型实现

导入tensorflow初始化一个输入

1
2
import tensorflow as tf
x = tf.placeholder(tf.float32,[None,784])

placeholder()生成指定大小的占位符,即它里面的内容是什么不重要,目的是为了能够将读入的数据以合适的大小填入占位符。

初始化权重和偏置

1
2
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

W和b也可以用placeholder()来初始化,但由于它们是变量,在后面的图计算过程中不断迭代更新,所以tensorflow有更好用的表示方法Variable(),它表示一张可修改的张量。
注意,W的维度是[784,10],因为我们想要用784维的图片向量乘以它以得到一个10维的证据值向量,每一位对应不同数字类。b的形状是[10],所以我们可以直接把它加到输出上面。

构建模型

1
y = tf.nn.softmax(tf.matmul(x,W)+b)

训练模型
定义评价指标(损失函数)

y 是我们预测的概率分布, y’ 是实际的分布

初始化占位符读入,图片真实结果

1
y_ = tf.placeholder(tf.float32,[None,10])

计算损失函数

1
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

利用tensorflow训练模型,采用tensorflow提供的学习方法最小化损失函数
这里采用了梯度下降的方法进行学习,后面可以学到更多优化参数的方法

1
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

创建会话 开始学习

1
2
3
4
5
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for i in range(1000):
batch_xs,batch_ys = mnist.train.next_batch(100)
sess.run(train_step,feed_dict={x:batch_xs,y_:batch_ys})

模型评估

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

评估预测值与真实值的差距,采用两个向量的距离平均值作为结果
注意:评估采用的是整体的平均值即所有图片的平均值,而不是一张对一张的方式,这样有更好的全局结果

参考

http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html
https://www.tensorflow.org/get_started/mnist/beginners

Donate comment here