The paddlepaddle deep learning framework trains the LeNet5 model (1)

Table of contents

1.paddle installation

2.paddle implements LeNet5 model and training


The most complete and detailed Anaconda installation tutorial in history

Basic methods for creating, activating and using anaconda virtual environment

The more mainstream deep learning frameworks now

1.paddle installation

Click on the official website to view the downloaded version . Generally, it is not easy to install a version that is too high, because certain problems will occur if the version is too high. Try to install a lower version.

Tip: After selecting the version, copy the "installation command" to the activated anaconda environment for installation (IDEA can choose Pycharm).

2.paddle implements LeNet5 model and training

Tip: Most people should be very familiar with the LeNet5 model in deep learning , a network used for handwritten digit recognition. But below we will use LeNet5, which has been implemented in the paddle library , for model training and handwriting prediction (this is just to start learning paddle ).

"""
@Author : Keep_Trying_Go
@Major  : Computer Science and Technology
@Hobby  : Computer Vision
@Time   : 2023/7/20 22:17
"""

import paddle
import numpy as np
import matplotlib.pyplot as plt
from paddle.vision.transforms import Normalize


def loadDataset():
    #由于手写体图像是单通道的,所以进行归一化的时候列表中只对一个通道的值进行归一化
    transform = Normalize(
        mean=[127.5],
        std=[127.5],
        data_format='CHW'
    )

    train_dataset = paddle.vision.datasets.MNIST(
        mode='train',
        transform=transform,
        download=True
    )
    test_dataset = paddle.vision.datasets.MNIST(
        mode='test',
        transform=transform,
        download=True
    )

    return train_dataset,test_dataset

def train():

    train_dataset,test_dataset = loadDataset()

    #初始化网络模型
    lenet5 = paddle.vision.models.LeNet(num_classes=10)
    model = paddle.Model(lenet5)

    #网络模型训练配置,准备损失函数,优化器和评价指标
    model.prepare(
        paddle.optimizer.Adam(parameters=model.parameters(),learning_rate=0.001),
        paddle.nn.CrossEntropyLoss(),
        paddle.metric.Accuracy()
    )
    
    #模型的训练
    model.fit(
        train_dataset,
        epochs=10,
        batch_size=16,
        verbose=1
    )
    
    #模型的评估
    model.evaluate(
        test_dataset,
        batch_size=16,
        verbose=1
    )
    
    #保存模型
    model.save('runs/mnist')

    return train_dataset,test_dataset

Tip: When saving the model, the parameters of the optimizer and network model will be saved together, as follows:

def predict():
    #加载模型
    model = paddle.vision.models.LeNet(num_classes=10)
    model = paddle.Model(model)
    #将训练保存的模型参数加载到网络模型中
    model.load('runs/mnist.pdparams')
    
    #加载数据集
    _,test_dataset = loadDataset()
    
    #只取第一张图像
    img,label = test_dataset[0]
    # 将图片shape从1*28*28变为1*1*28*28,增加一个batch维度,以匹配模型输入格式要求
    img_batch = np.expand_dims(img.astype('float32'),axis=0)
    
    #得到预测的结果
    out = model.predict_batch(img_batch)[0]
    #得到预测最大类别概率的索引
    pred_label = out.argmax()

    print('true label: {}  pred label: {}'.format(label[0],pred_label))

    plt.imshow(img[0])
    plt.show()

if __name__ == '__main__':
    # train()
    predict()

 

 Tip: Readers can also go to the official website to learn. Here are some supplements and summaries, such as how to load the trained and saved model when loading the model.

Guess you like

Origin blog.csdn.net/Keep_Trying_Go/article/details/131860456