TensorFlow入门-MNIST & softmax regression

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/muyiyushan/article/details/60955392

环境:win7 64位 Anaconda(python3.5)-TensorFlow

安装好TensorFlow后,参考TenforFlow官方教程开始学习。此文为使用MNIST数字集训练softmax regression,实现数字识别。

1. MNIST简介

MNIST放在Yann LeCun的网站上。

每张图像是28*28,将图像拉伸成一维的,就是有28*28=784的数字的向量。将图像拉伸成一维的,会损失2维结构信息。

训练图像55,000张,所以mnist.train.images是个[55000,784]的矩阵。
验证图像有5,000张,所以mnist.validation.images是[5000,784]。
测试图像10,000张。每个像素值在0-1之间。

因为数字在0-9之间,共有10类。图像的标签采用one-hot方式。比如3对应[0,0,1,0,0,0,0,0,0,0]。
训练图像对应的labels,mnist.train.labels就是[55,000,10]的矩阵。

2.代码解读

1.下载读取MNIST数据

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

数据下载到了C:\Users\Administrator\MNIST_data中。

2.导入TensorFlow

import tensorflow as tf

3.创建模型

softmax regression中计算预测值的公式是y=softmax(W*x+b),所以要定义W,x,b和y。

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b

x是一个placeholder(占位符),当我们要求TensorFlow运行一个计算时
会输入它。tf.float32是数据类型,[None,784]指数据维度,因为图像数量可任意选择,所以用None。

W,b定义为Variable,初始为0。

计算y时,为了让维度对应,将x,W调换顺序。

4.定义损失函数和优化策略

labels对应的y_

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

损失函数使用交叉熵(cross-entropy)用了内置的计算cross-entropy的函数。
这里写图片描述

cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))

optimizer用Gradient Densent, learning rate设置为0.5。

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

5.训练

先用个session对象初始化变量

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

每个batch为100的SGD

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

6. 模型评估

用tf.argmax(y,1)函数返回预测结果中沿着一个轴(axis)的最大值的索引(index),即预测的类别。用tf.equal检查预测值与真实值是否相等。

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

correct_prediction是一个布尔值列表,类似于 [True, False, True, True] ,将其转化为[1,0,1,1],即可计算准确度accuracy。

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

精度是91%。

猜你喜欢

转载自blog.csdn.net/muyiyushan/article/details/60955392