CNN训练推理手写数字

George

25-05-14

25-05-14

| 浏览量:👀  |  返回 <实验课>

简介和数据集

简介

卷积神经网络(Convolutional Neural Network, CNN)是一种深度学习模型,广泛应用于计算机视觉任务中,尤其是在图像分类和物体识别方面。与传统的全连接神经网络相比,CNN通过引入局部连接、权重共享和池化层等机制,能够有效捕捉图像中的空间特征,从而提升模型的性能和计算效率。

本实验旨在利用卷积神经网络构建一个图像分类模型,以识别手写数字数据集 MNIST(Modified National Institute of Standards and Technology)。MNIST 数据集包含 70,000 张 28x28 像素的灰度手写数字图像,涵盖从 0 到 9 的十个类别。由于其规模适中且相对简单,MNIST 数据集成为深度学习研究和教学中常用的基准数据集。

原文链接:【卷积神经网络】MINST数据集识别 | 手写数字识别

数据集

使用 PyTorch 框架时,数据集通常放在 data/MNIST/raw 目录下。

比如,训练和推理用代码放在 /root/ailab 目录下,则数据集放在 /root/ailab/data/MNIST/raw 目录中。

可从网上自行下载,或从如下链接下载。共 4 个 .gz 文件,下载后放入上述数据集目录中。

t10k-images-idx3-ubyte.gz
t10k-labels-idx1-ubyte.gz
train-images-idx3-ubyte.gz
train-labels-idx1-ubyte.gz

训练和推理

源代码

可以咨询大模型获得源代码框架。比如:输出基于 PyTorch 框架的 Python 完整代码,用于训练 mnist 和推理,需要详细注释。

也可从如下链接下载,共参考。

train_mnist_ascend_250513.py
infer_mnist_ascend_250513.py

运行和调测

train_mnist_ascend_250513.py 运行结果如下(以训练 5 个 epoch 为例)


(base) root@davinci-mini:~/ailab# python3 train_mnist_ascend_250513.py
[警告] torch_npu模块未找到,将回退到CPU训练
当前训练设备: cpu
/usr/local/miniconda3/lib/python3.9/site-packages/torch/utils/data/dataloader.py:626: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 3, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.
  warnings.warn(
===== MNIST训练开始 =====
使用设备: cpu
训练样本数: 60000
批量大小: 64
总迭代次数: 938次/epoch
/usr/local/miniconda3/lib/python3.9/site-packages/torch/utils/data/dataloader.py:665: UserWarning: 'pin_memory' argument is set as true but no accelerator is found, then device pinned memory won't be used.
  warnings.warn(warn_msg)
/usr/local/miniconda3/lib/python3.9/site-packages/torch/nn/functional.py:1538: UserWarning: dropout2d: Received a 2-D input to dropout2d, which is deprecated and will result in an error in a future release. To retain the behavior and silence this warning, please use dropout instead. Note that dropout2d exists to provide channel-wise dropout on inputs with 2 spatial dimensions, a channel dimension, and an optional batch dimension (i.e. 3D or 4D inputs).
  warnings.warn(warn_msg)
Epoch:  1 [     0/60000 (0%)]  Loss: 2.306371 elapsed_time: 0.7181 secs
Epoch:  1 [   640/60000 (1%)]  Loss: 1.105067 elapsed_time: 4.5227 secs
Epoch:  1 [  1280/60000 (2%)]  Loss: 0.960787 elapsed_time: 8.2586 secs
Epoch:  1 [  1920/60000 (3%)]  Loss: 0.525667 elapsed_time: 11.9629 secs
...
Epoch:  2 [ 58880/60000 (98%)]  Loss: 0.151442 elapsed_time: 335.6310 secs
Epoch:  2 [ 59520/60000 (99%)]  Loss: 0.055742 elapsed_time: 339.3682 secs
total_elapsed_time: 690.2588 秒
...
Epoch:  3 [ 58880/60000 (98%)]  Loss: 0.033503 elapsed_time: 335.6799 secs
Epoch:  3 [ 59520/60000 (99%)]  Loss: 0.015223 elapsed_time: 339.1351 secs
total_elapsed_time: 1031.5982 秒
...
Epoch:  4 [ 58880/60000 (98%)]  Loss: 0.035570 elapsed_time: 333.4938 secs
Epoch:  4 [ 59520/60000 (99%)]  Loss: 0.121509 elapsed_time: 337.1759 secs
total_elapsed_time: 1371.1106 秒
...
Epoch:  5 [ 58880/60000 (98%)]  Loss: 0.004134 elapsed_time: 340.5883 secs
Epoch:  5 [ 59520/60000 (99%)]  Loss: 0.042905 elapsed_time: 344.2381 secs
total_elapsed_time: 1717.5507 秒

            

            

说明
1、对于手写代码,或从大模型获取的代码,建议增加打印信息,确保训练按预期进行。
2、观察训练耗时,以便设置合理的 epoch。
3、升级开发板的 torch、torchvision、torchaudio,可缩短训练耗时。以上述样例代码为例,升级前完成 1个epoch约耗时 16 分钟,升级后只需要 6 分钟。
4、还可安装昇腾提供的 torch_npu(待验证)。


infer_mnist_ascend_250513.py 执行结果如下。可手写0-9,拍照,处理为 28 * 28 像素的图片,然后上传到开发板上做推理验证;或用其他方法生成。


(base) root@davinci-mini:~/ailab# python3 infer_mnist_ascend_250513.py
[警告] torch_npu模块未找到,将使用CPU推理
当前推理设备: cpu
模型已从 mnist_model_e5.pth 加载

正在预处理图像...
正在进行推理...
/usr/local/miniconda3/lib/python3.9/site-packages/torch/nn/functional.py:1538: UserWarning: dropout2d: Received a 2-D input to dropout2d, which is deprecated and will result in an error in a future release. To retain the behavior and silence this warning, please use dropout instead. Note that dropout2d exists to provide channel-wise dropout on inputs with 2 spatial dimensions, a channel dimension, and an optional batch dimension (i.e. 3D or 4D inputs).
  warnings.warn(warn_msg)

===== 识别结果 =====
预测数字: 8

ASCII表示:
 _ 
|_|
|_|

附录

升级 PyTorch

如需要升级开发板的 PyTorch / torchvision / torchaudio,可参考如下步骤。

1、用 root 账号登录开发板,然后执行 pip3 list | grep torch,查看 PyTorch 相关版本信息。


(base) root@davinci-mini:~# pip3 list | grep torch
torch                    1.13.0
torchaudio               0.13.0
torchvision              0.14.0

2、联系老师获得已下载的升级包,并复制到本地电脑。然后用相关工具或 scp 命令上传到开发板上。

# 在本地电脑上,切换到某个目录,该目录下 的 torch250515 子目录,存放了升级包。
# 执行如下命令,将本地电脑上的 torch250515 子目录(连带子目录中的文件),复制到开发板的目录中(假定复制到 /root/ailab 目录)
scp -r torch250515 root@192.168.137.100:/root/ailab

3、在开发板上,切换到升级包所在目录,比如 /root/ailab/torch250515,执行 pip3 install xxx.whl

# 按此顺序依次执行
pip3 install fsspec-2025.3.2-py3-none-any.whl
pip3 install typing_extensions-4.13.2-py3-none-any.whl
pip3 install sympy-1.14.0-py3-none-any.whl
pip3 install filelock-3.18.0-py3-none-any.whl
pip3 install torch-2.7.0-cp39-cp39-manylinux_2_28_aarch64.whl
pip3 install torchvision-0.22.0-cp39-cp39-manylinux_2_28_aarch64.whl

4、重复第1步,确认下升级了。