博客摘抄于:TensorFlow实战之Softmax Regression识别手写数字
1.使用的数据集
MNIST(Mixed National Institute of Standards and Technology database)是一个非常庞大的手写数字数据库,包含几万张 28*28像素的手写数字组成,这些图片只包含灰度信息,空白部分为0,笔记部分根据颜色颜色的深浅有0-1之间的取值。
2.目的
对这些手写数字图片进分类,转化为0-9共10类。
3.MNIST手写数字图片示例图
4 算法结构特点
- 使用softmax Regression 分类模型进行分类
- 只有输入层和输出层,没有隐藏层
5 TensorFlow 实现简单机器学习算法的步骤
- 定义算法公式,也就是神经网络forward时的计算
- 定义loss,选定优化器,并制定优化器优化loss
- 迭代地对数据进行训练
- 在测试集或者验证集上对准确率进行评测
6 图解
Softmax 函数
计算过程可视化如下:
7 代码实现
from tensorflow.examples.tutorials.mnist import input_data
#使用本地下载好的数据库
mnist = input_data.read_data_sets("E:/SoftMaxRegression/MNIST_data", one_hot=True)
# 展示训练集、测试集、验证集样本
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)
# 图像展示
import numpy as np
import matplotlib.pyplot as plt
# imshow data
imgTol = mnist.train.images
img = np.reshape(imgTol[5, :], [28, 28])
plt.imshow(img)
plt.show()
import tensorflow as tf
sess = tf.InteractiveSession() # 将本session注册成为默认的session
x = tf.placeholder(tf.float32,[None,784]) # 输入数据的地方,用于得到传递进来的真实的训练样本
# 第一个参数是数据类型,第二个参数是数据尺寸
# None代表不限条数的输入,784代表每条输入是一个784维的向量
w = tf.Variable(tf.zeros([784,10])) #参数初始化,主要在于一些可训练变量
b = tf.Variable(tf.zeros([10]))
# 1 实现Softmax Regression算法,求出预测值y
y = tf.nn.softmax(tf.matmul(x,w)+b)
# tf.nn包含了大量神经网络的组件
# tf.matmul是tensorflow中的矩阵乘法函数
# 2.1 对于多分类问题,通常使用cross-entropy作为loss function
y_ = tf.placeholder(tf.float32,[None,10]) # 输入是真实的label值,用来计算cross_entropy
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
# tf.reduce_mean(input_tensor,axis=None,keep_dims=False,name=None,reduction_indices=None)
# 第一个参数input_tensor: 输入的待降维的tensor;
# 第二个参数axis: 指定的轴,如果不指定,则计算所有元素的均值;
# 第三个参数keep_dims:是否降维度
#设置为True,输出的结果保持输入tensor的形状,设置为False,输出结果会降低维度;
# 第四个参数name: 操作的名称;
# 第五个参数 reduction_indices:在以前版本中用来指定轴,已弃用;
#reduction_indices=[1]时,操作横轴;reduction_indices=[0]时,操作纵轴;
# 默认值None,将把input_tensor降到0维,也就是一个数
# 2.2 定义优化算法,使用梯度下降算法更新参数
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 设置学习速率0.5,优化目标设定为cross_entropy
tf.global_variables_initializer().run()
#tf.global_variables_initializer()添加节点用于初始化所有的变量
# 3 迭代地对数据进行训练
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
#从训练集里提取100张图片数据,batch_xs存储像素信息,batch_ys存储标签信息
train_step.run({x:batch_xs,y_:batch_ys})
# 4 在测试集或验证集上对准确率进行评测
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
#tf.argmax(vector, 1):返回的是vector中的最大值的索引号
# tf.argmax(y,1)是求各预测值,数字中概率最大的一个
# tf.argmax(y_,1)是求样本中真实数字的类别
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) # 统计全部样本的预测
# tf.cast 是将之前的correct_prediction输出的bool值转换为float32.再求平均值。
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))
# eval() 其实就是tf.Tensor的Session.run() 的另外一种写法
结果:
(55000, 784) (55000, 10)
(10000, 784) (10000, 10)
(5000, 784) (5000, 10)
0.9165