第T1周:使用TensorFlow实现mnist手写数字识别

  1. 跑通程序
  2. 了解深度学习是什么

我的环境:
● 语言环境:Python3.6.5
● 编译器:jupyter notebook
● 深度学习环境:TensorFlow2

一、前期工作

  1. 设置GPU(如果使用的是CPU可以忽略这步)
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")

if gpus:
    gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPU
    tf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用
    tf.config.set_visible_devices([gpu0],"GPU")
  1. 导入数据
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

# 导入mnist数据,依次分别为训练集图片、训练集标签、测试集图片、测试集标签
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
  1. 归一化

数据归一化作用

● 使不同量纲的特征处于同一数值量级,减少方差大的特征的影响,使模型更准确。
● 加快学习算法的收敛速度。

# 将像素的值标准化至0到1的区间内。(对于灰度图片来说,每个像素最大值是255,每个像素最小值是0,也就是直接除以255就可以完成归一化。)
train_images, test_images = train_images / 255.0, test_images / 255.0
# 查看数据维数信息
train_images.shape,test_images.shape,train_labels.shape,test_labels.shape
"""
输出:((60000, 28, 28), (10000, 28, 28), (60000,), (10000,))
"""
  1. 可视化图片
# 将数据集前20个图片数据可视化显示
# 进行图像大小为20宽、10长的绘图(单位为英寸inch)
plt.figure(figsize=(20,10))
# 遍历MNIST数据集下标数值0~49
for i in range(20):
    # 将整个figure分成5行10列,绘制第i+1个子图。
    plt.subplot(2,10,i+1)
    # 设置不显示x轴刻度
    plt.xticks([])
    # 设置不显示y轴刻度
    plt.yticks([])
    # 设置不显示子图网格线
    plt.grid(False)
    # 图像展示,cmap为颜色图谱,"plt.cm.binary"为matplotlib.cm中的色表
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    # 设置x轴标签显示为图片对应的数字
    plt.xlabel(train_labels[i])
# 显示图片
#plt.show()
  1. 调整图片格式
#调整数据到我们需要的格式
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))

train_images.shape,test_images.shape,train_labels.shape,test_labels.shape
"""
输出:((60000, 28, 28, 1), (10000, 28, 28, 1), (60000,), (10000,))
"""

二、构建CNN网络模型

# 创建并设置卷积神经网络
# 卷积层:通过卷积操作对输入图像进行降维和特征抽取
# 池化层:是一种非线性形式的下采样。主要用于特征降维,压缩数据和参数的数量,减小过拟合,同时提高模型的鲁棒性。
# 全连接层:在经过几个卷积和池化层之后,神经网络中的高级推理通过全连接层来完成。
model = models.Sequential([
    # 设置二维卷积层1,设置32个3*3卷积核,activation参数将激活函数设置为ReLu函数,input_shape参数将图层的输入形状设置为(28, 28, 1)
    # ReLu函数作为激活励函数可以增强判定函数和整个神经网络的非线性特性,而本身并不会改变卷积层
    # 相比其它函数来说,ReLU函数更受青睐,这是因为它可以将神经网络的训练速度提升数倍,而并不会对模型的泛化准确度造成显著影响。
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    #池化层1,2*2采样
    layers.MaxPooling2D((2, 2)),                   
    # 设置二维卷积层2,设置64个3*3卷积核,activation参数将激活函数设置为ReLu函数
    layers.Conv2D(64, (3, 3), activation='relu'),  
    #池化层2,2*2采样
    layers.MaxPooling2D((2, 2)),                   
    
    layers.Flatten(),                    #Flatten层,连接卷积层与全连接层
    layers.Dense(64, activation='relu'), #全连接层,特征进一步提取,64为输出空间的维数,activation参数将激活函数设置为ReLu函数
    layers.Dense(10)                     #输出层,输出预期结果,10为输出空间的维数
])
# 打印网络结构
model.summary()

output

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 conv2d (Conv2D)             (None, 26, 26, 32)        320       
                                                                 
 max_pooling2d (MaxPooling2  (None, 13, 13, 32)        0         
 D)                                                              
                                                                 
 conv2d_1 (Conv2D)           (None, 11, 11, 64)        18496     
                                                                 
 max_pooling2d_1 (MaxPoolin  (None, 5, 5, 64)          0         
 g2D)                                                            
                                                                 
 flatten (Flatten)           (None, 1600)              0         
                                                                 
 dense (Dense)               (None, 64)                102464    
                                                                 
 dense_1 (Dense)             (None, 10)                650       
                                                                 
=================================================================
Total params: 121930 (476.29 KB)
Trainable params: 121930 (476.29 KB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________

三、编译模型

"""
这里设置优化器、损失函数以及metrics
这三者具体介绍可参考我的博客:
https://blog.csdn.net/qq_38251616/category_10258234.html
"""
# model.compile()方法用于在配置训练方法时,告知训练时用的优化器、损失函数和准确率评测标准
model.compile(
	# 设置优化器为Adam优化器
    optimizer='adam',
	# 设置损失函数为交叉熵损失函数(tf.keras.losses.SparseCategoricalCrossentropy())
    # from_logits为True时,会将y_pred转化为概率(用softmax),否则不进行转换,通常情况下用True结果更稳定
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    # 设置性能指标列表,将在模型训练时监控列表中的指标
    metrics=['accuracy'])

四、训练模型

"""
这里设置输入训练数据集(图片及标签)、验证数据集(图片及标签)以及迭代次数epochs
关于model.fit()函数的具体介绍可参考我的博客:
https://blog.csdn.net/qq_38251616/category_10258234.html
"""
history = model.fit(
    # 输入训练集图片
	train_images, 
	# 输入训练集标签
	train_labels, 
	# 设置10个epoch,每一个epoch都将会把所有的数据输入模型完成一次训练。
	epochs=10, 
	# 设置验证集
    validation_data=(test_images, test_labels))

output

Epoch 1/10
1875/1875 [==============================] - 13s 5ms/step - loss: 0.1419 - accuracy: 0.9572 - val_loss: 0.0470 - val_accuracy: 0.9849
Epoch 2/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0469 - accuracy: 0.9857 - val_loss: 0.0565 - val_accuracy: 0.9811
Epoch 3/10
1875/1875 [==============================] - 8s 4ms/step - loss: 0.0318 - accuracy: 0.9904 - val_loss: 0.0340 - val_accuracy: 0.9894
Epoch 4/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0240 - accuracy: 0.9922 - val_loss: 0.0326 - val_accuracy: 0.9896
Epoch 5/10
1875/1875 [==============================] - 8s 4ms/step - loss: 0.0173 - accuracy: 0.9945 - val_loss: 0.0273 - val_accuracy: 0.9917
Epoch 6/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0141 - accuracy: 0.9954 - val_loss: 0.0368 - val_accuracy: 0.9892
Epoch 7/10
1875/1875 [==============================] - 8s 4ms/step - loss: 0.0120 - accuracy: 0.9962 - val_loss: 0.0380 - val_accuracy: 0.9899
Epoch 8/10
1875/1875 [==============================] - 8s 4ms/step - loss: 0.0093 - accuracy: 0.9967 - val_loss: 0.0288 - val_accuracy: 0.9920
Epoch 9/10
1875/1875 [==============================] - 8s 4ms/step - loss: 0.0077 - accuracy: 0.9972 - val_loss: 0.0351 - val_accuracy: 0.9909
Epoch 10/10
1875/1875 [==============================] - 9s 5ms/step - loss: 0.0067 - accuracy: 0.9979 - val_loss: 0.0370 - val_accuracy: 0.9901

五、预测

pre = model.predict(test_images) # 对所有测试图片进行预测
pre[0]

output

array([-12.295295  ,  -6.8074613 ,  -7.0550156 ,  -0.22500038,
        -6.9359474 , -10.427808  , -22.984123  ,  19.57409   ,
        -4.20898   ,   1.4158278 ], dtype=float32)

因此最后的结果是预测为7,与事实相符。

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值