Tensorflow入门之MNIST手写数字识别实战教程

学习一门编程语言时,入门的第一件事几乎都是打印“Hello World”。MNIST手写数字识别就像是机器学习领域里的Hello World。通过Tensorflow实现MNIST手写数字识别将让我们快速地入门机器学习以及了解Tensorflow的使用。



数据集介绍

MNIST数据集主要由一些手写数字的图片和相应的标签组成,图片一共有10类,分别对应从0~9,共10个阿拉伯数字,如下图所示。

在这里插入图片描述
原始的MNIST数据库包含4个文件,见下表。

文件名大小用途
train-images-idx3-ubyte.gz≈9.45MB训练图像数据
train-labels-idx 1-ubyte.gz≈0.03MB训练图像的标签
t10-images-idx3-ubyte.gz≈1.75MB测试图像数据
t10k-labels-idxl-ubyte.gz≈4.4KB测试图像的标签

在MNIST数据集中有两类图像:一类是训练图像,另一类是测试图像。训练图像一共有60000张,测试图像有10000张。在Tensorflow中不需要去单独下载MNIST数据集,它为我们提供了方便的封装,可以直接加载MNIST数据。


开始训练模型

导入包和数据集

导入Tensorflow和MNIST数据集

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 读取MNIST数据集,如果不存在会实现下载
mnist = input_data.read_data_sets("/tmp/MNIST_data/", False, one_hot=True)

定义占位符和变量

# 创建x,x是占位符,代表待识别的图片。
x = tf.placeholder("float", [None, 784])

# 在这里,我们都用全为零的张量来初始化W和b。因为我们要学习W和b的值,它们的初值可以随意设置。
# 权重:W的维度是[784,10],因为我们想要用784维的图片向量乘以它以得到一个10维的证据值向量,每一位对应不同数字类。
W = tf.Variable(tf.zeros([784, 10]))

# 偏置值:b的形状是[10],所以我们可以直接把它加到输出上面。
b = tf.Variable(tf.zeros([10]))

# y表示模型的输出,softmax模型可以用来给不同的对象分配概率。即使在之后,我们训练更加精细的模型时,最后一步也需要用softmax来分配概率。
y = tf.nn.softmax(tf.matmul(x, W) + b)

# y_是实际的图像标签,同样以占位符表示,是以独热表示的。
y_ = tf.placeholder("float", [None, 10])

tf.placeholder(dtype, shape=None, name=None) 占位符

tf.Variable() 变量

tf.nn.softmax(logits, name=None) Softmax回归

构造损失和梯度下降

构造完损失并使用梯度下降法优化损失

# 根据y和y_构造交叉熵损失
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))

# 有了损失就可以用梯度下降法针对模型的参数(W和b)进行优化
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

tf.reduce_sum(input_tensor, reduction_indices=None, keep_dims=False, name=None) 计算输入tensor元素的和
tf.train.GradientDescentOptimizer(learning_rate) 基于一定的学习率进行梯度优化训练

创建Session,初始化变量

创建一个session。只有在session中才能运行优化步骤train_step

# 添加一个操作来初始化创建的变量
init = tf.initialize_all_variables()
# 创建一个session。只有在session中才能运行优化步骤train_step
sess = tf.Session()
sess.run(init)

init = tf.initialize_all_variables() 用于初始化变量,需要session来启动
tf.Session() 创建一个会话,当上下文管理器退出时会话关闭和资源释放自动完成

开始训练

这里我们让模型循环训练1000次。该循环的每个步骤中,我们都会随机抓取训练数据中的100个批处理数据点,然后我们用这些数据点作为参数替换之前的占位符来运行train_step。

for i in range(1000):
    # batch_xs和batch_ys对应这占位符x和y_
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

feed_dict 给使用placeholder创建出来的tensor赋值

准确率验证

训练完成后,就可以对模型的准确率进行验证。

# 正确的预测结果
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# 计算预测准确值,它们都是Tensor
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
# 这里是获取最终模型的准确率
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

tf.argmax(input, dimension, name=None) 返回input最大值的索引index

tf.equal(x, y, name=None) 逐个对比两个矩阵或向量的元素,相同返回True,不相同返回False

tf.cast(x, dtype, name=None) 将x或者x.values转换为dtype

tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None) 求tensor中平均值

最终的预测结果是:0.9173
在这里插入图片描述

上面所使用的Softmax回归是一个比较简单的模型,预测的准确率不高,在下面将使用卷积神经网络将预测的准确率提升到99%。


使用卷积神经网络训练模型

导入包和数据集

依旧是导入Tensorflow和MNIST数据集

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

创建占位符

# x为训练图像的占位符,y_为训练图像标签的占位符。
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])

定义神经网络

# 第一层神经网络

# 函数weight_variable可以返回一个给定形状的变量并自动以截断正态分布初始化
def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

# 函数bias_variable同样可以返回一个给定形状的变量,初始化时所有值是0.1
def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')
                        
# [5, 5, 1, 32]代表卷积核尺寸为5×5,一个颜色通道,32个不同的卷积核。
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

# 将单张图片从784维向量重新还原为28×28的矩阵图片,-1代表样本数量不固定,1代表颜色通道。
x_image = tf.reshape(x, [-1,28,28,1])

# 进行卷积计算,卷积计算后用ReLu作为激活函数
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

# 调用函数max_pool_2x2进行一次池化操作
h_pool1 = max_pool_2x2(h_conv1)
# 第二层神经网络
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

全连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# 使用Dropout(防止神经网络过度拟合),keep_prob是一个占位符,训练时为5,测试时为1
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
全连接层,把1024量闺岱句量转换成 10维,对应 10 个向量 
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None) 从截断的正态分布中输出随机值

tf.constant(value, dtype=None, shape=None, name=‘Const’, verify_shape=False) 常量

tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None) 卷积函数:在给定的4D input与 filter下计算2D卷积,输入shape为 [batch, height, width, in_channels]

tf.nn.max_pool(value, ksize, strides, padding, data_format=’NHWC’, name=None) 最大值方法池化

tf.reshape(tensor, shape, name=None) 改变tensor的形状

tf.nn.relu(features, name=None) 激活函数

tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None) 计算dropout,keep_prob为keep概率
noise_shape为噪声的shape

构造损失和梯度下降

定义损失函数为cross_entropy,优化器使用Adam,学习率为1e-4

cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

tf.train.AdamOptimizer : 使用Adam 算法的Optimizer

定义测试的准确率

correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

创建Session,初始化变量

sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())

开始训练

设置训练时候Dropout的keep_prob的比率为0.5,mini-batch为50,共进行20000次训练迭代。

for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
    print ("step %d, training accuracy %g" % (i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print ("test accuracy %g" % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

训练结束打印准确率

print ("test accuracy %g" % accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

最终这个CNN模型得到的准确率约为99%
99%


全部代码

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 读取MNIST数据集,如果不存在会实现下载
mnist = input_data.read_data_sets("MNIST_data/", False, one_hot=True)

# 第一个维度数字用来索引图片,第二个维度数字用来索引每张图片中的像素点。
# 创建x,x是占位符,代表待识别的图片。
x = tf.placeholder(tf.float32, [None, 784])

# 在这里,我们都用全为零的张量来初始化W和b。因为我们要学习W和b的值,它们的初值可以随意设置。
# W是Softmax模型的参数,将一个784维的输入转化为一个10维的输出
W = tf.Variable(tf.zeros([784, 10]))

# b是有一个softmax模型的参数,一般叫“偏置值”
b = tf.Variable(tf.zeros([10]))

#  y表示模型的输出,softmax模型可以用来给不同的对象分配概率。即使在之后,我们训练更加精细的模型时,最后一步也需要用softmax来分配概率。
y = tf.nn.softmax(tf.matmul(x, W) + b)

# y_是实际的图像标签,同样以占位符表示,是以独热表示的。
y_ = tf.placeholder("float", [None, 10])

# 根据y和y_构造交叉熵损失
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))

# 有了损失就可以用梯度下降法针对模型的参数(W和b)进行优化,学习率0.01
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

# 添加一个操作来初始化创建的变量
init = tf.initialize_all_variables()

# 在一个Session里面启动模型,并且初始化变量
# 创建一个session。只有在session中才能运行优化步骤train_step
sess = tf.Session()
sess.run(init)

# 开始训练模型,这里我们让模型循环训练1000次
# 该循环的每个步骤中,我们都会随机抓取训练数据中的100个批处理数据点,然后我们用这些数据点作为参数替换之前的占位符来运行train_step。
# batch_xs的形状为(100,784)的图像数据,batch_ys是形如(100,10)的实际标签。 batch_xs和batch_ys对应这占位符x和y_。
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
# 在session中运行train_step,运行是要传入占位符的值
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

# 下述y的值是在上述训练最后一步已经计算获得,所以能够与原始标签y_进行比较
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# 计算预测准确值,它们都是Tensor
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
# 这里是获取最终模型的准确率
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

使用CNN训练模型代码

# 导入Tensorflow,加载MNIST数据
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# 创建Session
sess = tf.InteractiveSession()

# x为训练图像的占位符,y_为训练图像标签的占位符。
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])

# 函数weight_variable可以返回一个给定形状的变量并自动以截断正态分布初始化
def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

# 函数bias_variable同样可以返回一个给定形状的变量,初始化时所有值是0.1
def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')
# 第一层卷积层
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])

# 进行卷积计算,卷积计算后用ReLu作为激活函数
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

# 调用函数max_pool_2x2进行一次池化操作
h_pool1 = max_pool_2x2(h_conv1)


# 第二层卷积层
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

# 全连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# Dropout层,减轻过度拟合
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# 输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# 定义损失函数,使用Adam优化器,学习率为1e-4
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 定义测试的准确率
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# 初始化变量
sess.run(tf.initialize_all_variables())

# 开始训练模型,让模型循环训练20000次,每100步报告一次在验证集上的准确率
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print ("step %d, training accuracy %g" % (i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
  
# 训练结束后报告在测试集上的准确率,准确率约为99.2%
print ("test accuracy %g" % accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

项目代码

GitHub地址:https://github.com/WellTung666/Tensorflow/tree/master/MNIST

参考资料

http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 基于TensorFlowMNIST手写数字识别是一种机器学习技术,它可以通过训练模型来识别手写数字。MNIST是一个常用的数据集,包含了大量的手写数字图像和对应的标签。TensorFlow是一个流行的深度学习框架,可以用来构建和训练神经网络模型。通过使用TensorFlow,我们可以构建一个卷积神经网络模型,对MNIST数据集进行训练和测试,从而实现手写数字识别的功能。 ### 回答2: 随着机器学习技术的不断发展,MNIST手写数字识别已成为一个基础、常见的图像分类问题。TensorFlow是目前最流行的深度学习框架之一,广泛应用于图像处理、自然语言处理等领域,所以在TensorFlow上实现MNIST手写数字识别任务是非常具有代表性的。 MNIST手写数字识别是指从给定的手写数字图像中识别出数字的任务。MNIST数据集是一个由数万张手写数字图片和相应标签组成的数据集,图片都是28*28像素的灰度图像。每一张图片对应着一个标签,表示图片中所代表的数字。通过对已经标记好的图片和标签进行训练,我们将构建一个模型来预测测试集中未知图片的标签。 在TensorFlow中实现MNIST手写数字识别任务,可以通过以下步骤完成: 1. 导入MNIST数据集:TensorFlow中的tf.keras.datasets模块内置了MNIST数据集,可以通过如下代码导入:(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() 2. 数据预处理:对数据进行标准化处理,即将灰度值范围从[0,255]缩放到[0,1]之间。同时将标签值进行独热编码,将每个数字的标签由一个整数转换为一个稀疏向量。采用以下代码完成数据预处理:train_images = train_images / 255.0 test_images = test_images / 255.0 train_labels = tf.keras.utils.to_categorical(train_labels, 10) test_labels = tf.keras.utils.to_categorical(test_labels, 10) 3. 构建模型:采用卷积神经网络(CNN)进行建模,包括卷积层、池化层、Dropout层和全连接层。建议采用可重复使用的模型方法tf.keras.Sequential()。具体代码实现为:model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu',input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.5)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) 4. 编译模型:指定优化器、损失函数和评估指标。可采用Adam优化器,交叉熵损失函数和准确率评估指标。具体实现代码如下:model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 5. 训练模型:采用train()函数进行模型训练,完成代码如下:model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels)) 6. 评估模型:计算测试准确率,完成代码如下:test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) 以上就是基于TensorFlowMNIST手写数字识别的简要实现过程。其实实现过程还可以更加复杂,比如调节神经元数量,添加卷积层数量等。总之采用TensorFlow框架实现MNIST手写数字识别是一个可行的任务,未来机器学习发展趋势将越来越向深度学习方向前进。 ### 回答3: MNIST手写数字识别是计算机视觉领域中最基础的问题,使用TensorFlow实现这一问题可以帮助深入理解神经网络的原理和实现,并为其他计算机视觉任务打下基础。 首先,MNIST手写数字数据集由28x28像素的灰度图像组成,包含了数字0到9共10个类别。通过导入TensorFlow及相关库,我们可以很容易地加载MNIST数据集并可视化: ``` import tensorflow as tf import matplotlib.pyplot as plt (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() print("Training images:", train_images.shape) print("Training labels:", train_labels.shape) print("Test images:", test_images.shape) print("Test labels:", test_labels.shape) plt.imshow(train_images[0]) plt.show() ``` 在实现MNIST手写数字识别的神经网络模型中,最常用的是卷积神经网络(Convolutional Neural Networks,CNN),主要由卷积层、激活层、池化层和全连接层等组成。卷积层主要用于提取局部特征,激活层用于引入非线性性质,池化层则用于加速处理并减少过拟合,全连接层则进行最终的分类。 以下为使用TensorFlow搭建CNN实现MNIST手写数字识别的代码: ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D(pool_size=(2,2)), tf.keras.layers.Conv2D(64, kernel_size=(3,3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(10, activation='softmax') ]) model.summary() model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) train_images = train_images.reshape((60000, 28, 28, 1)) train_images = train_images / 255.0 test_images = test_images.reshape((10000, 28, 28, 1)) test_images = test_images / 255.0 model.fit(train_images, train_labels, epochs=5, batch_size=64) test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print("Test accuracy:", test_acc) ``` 这段代码中使用了两个卷积层分别提取32和64个特征,池化层进行特征加速和降维,全连接层作为最终分类器输出预测结果。在模型训练时,使用Adam优化器和交叉熵损失函数进行训练,经过5个epoch后可以得到约99%的测试准确率。 总之,通过使用TensorFlow实现MNIST手写数字识别的经历,可以深切认识到深度学习在计算机视觉领域中的应用,以及如何通过搭建和训练神经网络模型来解决实际问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值