深度学习-第T1周——实现mnist手写数字识别

深度学习-第P1周——实现mnist手写数字识别

一、前言

二、我的环境

  • 电脑系统:Windows 10
  • 语言环境:Python 3.8.5
  • 编译器:colab在线编译
  • 深度学习环境:Pytorch

三、前期工作

1、导入依赖项并设置GPU

import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")

if gpus:
  gpu0 = gpus[0]
  tf.config.experimental.set_memory_growth(gpu0, True)
  tf.config.set_visible_device([gpu0], "GPU")

2、导入数据集

使用dataset下载MNIST数据集,并划分训练集和测试集

使用dataloader加载数据

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_lables), (test_images, test_lables) = datasets.mnist.load_data()

3、归一化

数据归一化作用

  • 使不同量纲的特征处于同一数值量级,减少方差大的特征的影响,使模型更准确
  • 加快学习算法的准确性
train_images, test_images = train_images / 255.0, test_images / 255.0

train_images.shape, test_images.shape, train_lables.shape, test_lables.shape

4、可视化图片

#进行图像大小为10宽10长的绘图
plt.figure(figsize = (10, 10))

for i in range(20):
    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_lables[i])

5、调整图片格式

train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))

四、构建简单的CNN网络

对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。

#二、构建简单的CNN网络
# 创建并设置卷积神经网络
# 卷积层:通过卷积操作对输入图像进行降维和特征抽取
# 池化层:是一种非线性形式的下采样。主要用于特征降维,压缩数据和参数的数量,减小过拟合,同时提高模型的鲁棒性。
# 全连接层:在经过几个卷积和池化层之后,神经网络中的高级推理通过全连接层来完成。
model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation = 'relu', input_shape= (28, 28, 1)),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation = 'relu'),
    layers.MaxPooling2D((2, 2)),

    layers.Flatten(),
    layers.Dense(64, activation = 'relu'),
    layers.Dense(10)

])

model.summary()
#以上为简单的tf八股模板,可以看B站的北大老师曹健的tensorflow笔记

在这里插入图片描述

五、编译并训练模型

1、设置超参数

#这里设置优化器,损失函数以及metrics
model.compile(
	#设置优化器为Adam优化器
    optimizer = 'adam',
    #设置损失函数为交叉熵损失函数
    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits = True),
    metrics = ['accuracy']
)

2、编写训练函数

history = model.fit(
    train_images,
    train_lables,
    epochs = 10,
    validation_data = (test_images, test_lables)
)

在这里插入图片描述

六、预测

plt.imshow(test_images[1])

pre = model.predict(test_images)
pre[1]

在这里插入图片描述

七、总结

提前看了一遍北大软微老师的tf笔记,对于tensorflow建模型的八股大致弄懂了

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值