TensorFlow 实现Softmax Regression 识别数字

TensorFlow机器学习hello world任务MNIST手写数字识别

MNIST是个机器视觉数据集,包含大量28像素*28像素的手写数字图片,且带有数字标签对应每张图片的数字。
获取数据的代码如下:
这里写图片描述
数据特征如下:
这里写图片描述

代码及详细分析

import tensorflow as tf
#获取数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("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)

sess = tf.InteractiveSession() #创建一个新的InteractiveSession
x = tf.placeholder(tf.float32,[None,784]) #数据尺寸none代表不限制数量,784表示每天输入是一个784维的向量

W = tf.Variable(tf.zeros([784,10]))#初始为0,[784,10]784是特征的维数,10代表有10类
b = tf.Variable(tf.zeros([10]))
#y=softmax(Wx+b)改写成�� tf.nn包括大量神经网络组件 tf.matmul是tensorflow的矩阵乘法函数
y = tf.nn.softmax(tf.matmul(x,W)+b)
y_ = tf.placeholder(tf.float32,[None,10])
#cross_entropy通常用于表示loss
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
#使用梯度下降的方法减小loss
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#变量初始化
tf.global_variables_initializer().run()
#训练1000次
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    train_step.run({x:batch_xs, y_:batch_ys})
    #print(batch_xs, 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}))

使用TensorFlow的整个流程

1.定义算法公式,即神经网络forward时的计算。
2.定义loss,选定优化器,并指定优化器优化loss。
3.迭代的对数据进行训练。
4.在训练集或验证集上对准确率进行评测。

参考

《TensorFlow实战》黄文坚

猜你喜欢

转载自blog.csdn.net/qq_33374476/article/details/76691000
今日推荐