Python Paddlepaddle使用mnist数据集训练图片识别并且验证

环境准备

python3.7
paddlepaddle

训练代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import paddle
from paddle.vision.transforms import Compose, Normalize
from paddle.metric import Accuracy



# 使用transform对数据集做归一化
transform = Compose([Normalize(mean=[127.5], std=[127.5], data_format='CHW')])
# 使用MNIST数据集,第一次使用,会从网络下载,地址为国外服务器,速度可能较慢
train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)
test_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)



model = paddle.Model(paddle.vision.models.LeNet()) # 使用内置的LeNet网络创建模型

optim = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())

# 配置模型
model.prepare(
optim,
paddle.nn.CrossEntropyLoss(),
Accuracy()
)


# 训练模型
model.fit(train_dataset,
epochs=10,
batch_size=64,
verbose=1
)
# 若想保存训练模型中的过程量则可以新增save_dir参数,
# model.fit(train_dataset,
# epochs=10,
# batch_size=64,
# save_dir='./testfive/mnist_checkpoint',
# verbose=1
# )
# 保存模型 ./testfive/mnist_checkpoint/为保存模型的路径 test为保存模型的名称
# 若只使用model.save('test', training=False) 则模型保存在当前运行目录下
model.save('./testfive/mnist_checkpoint/test', training=False)

输出结果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
The loss value printed in the log is the current step, and the metric is the average value of previous steps.
Epoch 1/10
step 938/938 [==============================] - loss: 0.0400 - acc: 0.9339 - 21ms/step
Epoch 2/10
step 938/938 [==============================] - loss: 0.0216 - acc: 0.9748 - 21ms/step
Epoch 3/10
step 938/938 [==============================] - loss: 0.0129 - acc: 0.9785 - 21ms/step
Epoch 4/10
step 938/938 [==============================] - loss: 0.0056 - acc: 0.9819 - 21ms/step
Epoch 5/10
step 938/938 [==============================] - loss: 0.0246 - acc: 0.9833 - 21ms/step
Epoch 6/10
step 938/938 [==============================] - loss: 0.0951 - acc: 0.9849 - 21ms/step
Epoch 7/10
step 938/938 [==============================] - loss: 0.0317 - acc: 0.9861 - 21ms/step
Epoch 8/10
step 938/938 [==============================] - loss: 6.0844e-04 - acc: 0.9878 - 22ms/step
Epoch 9/10
step 938/938 [==============================] - loss: 0.0028 - acc: 0.9881 - 21ms/step
Epoch 10/10
step 938/938 [==============================] - loss: 0.0107 - acc: 0.9893 - 21ms/step
D:\MyWorkProgram\anaconda3\envs\paddle\lib\site-packages\paddle\hapi\model.py:2199: UserWarning: 'inputs' was not specified when Model initialization, so the input shape
to be saved will be the shape derived from the user's actual inputs. The input shape to be saved is [[64, 1, 28, 28]]. For saving correct input shapes, please provide 'inputs' for Model initialization.
% self._input_info[0]

最后输出的结果可能仅仅为警告,忽略即可,不影响结果

获得最终的模型文件

1
2
3
D:\vsCodeWorkspace\pythonpaddleNumber\testfive\mnist_checkpoint\test.pdmodel
D:\vsCodeWorkspace\pythonpaddleNumber\testfive\mnist_checkpoint\test.pdiparams.info
D:\vsCodeWorkspace\pythonpaddleNumber\testfive\mnist_checkpoint\test.pdiparams

验证模型

从数据集的测试集中随机获取一张图片,进行预测,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

import paddle
from paddle.vision.transforms import Compose, Normalize
from paddle.metric import Accuracy
import numpy as np

m = paddle.jit.load("./testfive/mnist_checkpoint/test")
m.eval() # 设置为预测模型

# 使用transform对数据集做归一化
transform = Compose([Normalize(mean=[127.5], std=[127.5], data_format='CHW')])
test_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)
# train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)

img1,label1 = test_dataset[1];


pre = m(np.array([img1])) # 预测结果
print("预测数字:", np.argmax(pre)) # 输出预测数字

print("真实数字:", label1) # 输出真实数字

输出结果如下

1
2
预测数字: 2  
真实数字: [2]

一辈子很短,努力的做好两件事就好;
第一件事是热爱生活,好好的去爱身边的人;
第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱;

继开 wechat
欢迎加我的微信,共同交流技术