TensorFlow 实现Softmax Regression 识别数字

本文介绍了使用TensorFlow进行MNIST手写数字识别的机器学习任务,详细阐述了从数据获取、特征理解,到模型定义、损失函数设定、优化器选择,以及训练过程和准确率评估的全过程。
摘要由CSDN通过智能技术生成

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实战》黄文坚

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值