当前位置: 首页 > news >正文

T1-实现mnist手写数字识别

● 🍨 本文为🔗365天深度学习训练营中的学习记录博客
● 🍖 原作者:K同学啊

一、前期准备

1.设置GPU

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") print(gpus)

2.导入数据

一种方法是可以直接下载

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()

如果无法连接下载数据可以先下载好数据集在本地加载

import os import gzip import numpy as np def load_mnist_local(path): files = [ 'train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz' ] with gzip.open(os.path.join(path, files[0]), 'rb') as f: x_train = np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1,28,28) with gzip.open(os.path.join(path, files[1]), 'rb') as f: y_train = np.frombuffer(f.read(), np.uint8, offset=8) with gzip.open(os.path.join(path, files[2]), 'rb') as f: x_test = np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1,28,28) with gzip.open(os.path.join(path, files[3]), 'rb') as f: y_test = np.frombuffer(f.read(), np.uint8, offset=8) return (x_train, y_train), (x_test, y_test) # 这里改成数据集所在位置 data_path = r"C:\Users\asus\Desktop\T1\data\MNIST\raw" (train_images, train_labels), (test_images, test_labels) = load_mnist_local(data_path)

3.归一化

# 将像素的值标准化至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

4.数据可视化

# 将数据集前20个图片数据可视化显示 # 进行图像大小为20宽、10长的绘图(单位为英寸inch) plt.figure(figsize=(20,10)) # 遍历MNIST数据集下标数值0~49 for i in range(20): # 将整个figure分成2行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()

5.调整图片格式

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

二、训练模型

1.构建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()

2.编译模型

model.compile( optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

3.模型训练

history = model.fit( train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))

import matplotlib.pyplot as plt #隐藏警告 import warnings warnings.filterwarnings("ignore") plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.rcParams['figure.dpi'] = 100 from datetime import datetime current_time = datetime.now() epochs_range = range(10) plt.figure(figsize=(12, 3)) plt.subplot(1, 2, 1) plt.plot(epochs_range, train_acc, label='Training Accuracy') plt.plot(epochs_range, test_acc, label='Test Accuracy') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.xlabel(current_time) plt.subplot(1, 2, 2) plt.plot(epochs_range, train_loss, label='Training Loss') plt.plot(epochs_range, test_loss, label='Test Loss') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.show()

三、模型预测

plt.imshow(test_images[1])

pre = model.predict(test_images) # 对所有测试图片进行预测 pre[1] # 输出第一张图片的预测结果

第三项为29.019821,说明预测结果为2,和图片一致。

个人总结:安装tensorflow2的GPU版本时,一定要注意各个库的版本协调,我因为在学深度学习之前就已经安装了python3.12,anaconda和CUDA12.6,python和CUDA的版本都过高无法适配tensorflow2,所以在anaconda里建立了一个pyhon3.9的虚拟环境,在该环境内下载了CUDA11.2和cudnn8.1,最后安装tensorflow2.10。本周使用tensorflow实现mnist手写数字识别,使用的是最简单的CNN模型 LeNet-5,由输入层、卷积层1,池化层1,卷积层2,池化层2,flatten层,全连接层,输出层按序构成。这里的tensorflow2(Keras)是高阶API的写法,能够快速搭建出CNN模型。

http://www.jsqmd.com/news/1305960/

相关文章:

  • HMC998A,DC~22GHz 2W 超宽带功率放大器
  • PID控制器在循迹小车中的原理、调试与应用实战
  • Python爬虫IP封禁解决方案与代理池实战
  • 2026 年 8 月桂林非急救医疗转运行业发展解析及合规企业服务实录 - 平台推荐官
  • 单仁牛商玄琨GEO:AI搜索获客系统实战落地的技术指南 - 汇聚至此
  • 5分钟快速上手:猫抓浏览器扩展终极使用指南
  • 2026年豆包GEO优化服务商推荐:自研监测技术赋能AI品牌曝光
  • AI做视频模板卖钱:从0到1搭建自动化印钞机的5个致命细节,90%新手踩坑在第3步?
  • AI大模型面试高频考点:Transformer、RLHF与LoRA解析
  • P4098 ALO 题解
  • AI项目管理如何避免“只会问答”?建立可执行工作流的5个步骤
  • 桌面多功能交互终端:硬件调试与多协议配置实践指南
  • 如何构建终极英雄联盟自动化工具:5个核心技术模块深度解析
  • 嵌入式开发必备:FatFS文件系统移植与实战应用详解
  • 终极Wand-Enhancer实战指南:5步掌握WeMod专业版功能解锁与远程控制
  • 倒计时一天!智源/TileRT/腾讯/华为/智元创新多方集结,共探 AI 编译的多层级协同优化
  • 2026年7月北京苹果手机维修服务指南|iPhone全系进水、屏幕、电池、主板原装检修 - 苹果手机品牌电脑维修
  • DLP4500 EVM实战指南:从硬件连接到光学投影的常见问题与解决方案
  • 英雄联盟Akari助手:3分钟快速上手的游戏自动化工具
  • 编程用哪个AI大模型好?实测GPT-5.6和Claude的真实体验
  • Slurm作业调度实战:从sbatch到sacct的完整生命周期管理
  • 2026年2月28日周六时间管理全攻略
  • 2026年 上海小件行李搬运配送团队推荐榜单:同城/跨城速运,专业打包与安心守护优选 - 优企名品
  • 如何用MZmine3免费开源质谱数据分析软件加速你的科研发现
  • 天猫店群自动化管理系统:综合代码架构自愈,异常自动恢复不中断
  • 手机卡托又薄又小还高光,嘉腾闪测仪把多参数检测做到秒级批量完
  • 含金量高财务岗位证书有哪些?2026年财务人考证与职业升级指南
  • PrimeTime静态时序分析:get_cells命令深度解析与应用实战
  • 三维设计云桌面方案
  • 大麦抢票脚本完整指南:告别手动抢票的终极解决方案