深度学习——神经网络参数的保存和提取

代码与详细注释:

Talk is cheap. Show you the code!

import torch
import matplotlib.pyplot as plt


# 造数据
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)  # x data (tensor), shape=(100, 1)
y = x.pow(2) + 0.2*torch.rand(x.size())  # noisy y data (tensor), shape=(100, 1)


# 保存net1
def save():
    # 使用Sequential快速搭建神经网络
    net1 = torch.nn.Sequential(
        torch.nn.Linear(1, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 1)
    )
    # 优化器设置为SGD
    optimizer = torch.optim.SGD(net1.parameters(), lr=0.5)
    # 损失函数设置为MSELoss
    loss_func = torch.nn.MSELoss()

    # 训练100步
    for t in range(100):
        # 计算预测值
        prediction = net1(x)
        # 计算预测值和真实值之间的误差
        loss = loss_func(prediction, y)
        # 将梯度设置为0
        optimizer.zero_grad()
        # 误差反向传播
        loss.backward()
        # 优化器逐步优化
        optimizer.step()

    # 绘制第一张子图
    plt.figure(1, figsize=(10, 3))
    plt.subplot(131)
    plt.title('Net1')
    # 绘制原数据的散点图
    plt.scatter(x.data.numpy(), y.data.numpy())
    # 绘制回归曲线
    plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)

    # 方法一:保存整个网络
    torch.save(net1, 'net.pkl')
    # 方法二:只保存网络参数
    torch.save(net1.state_dict(), 'net_params.pkl')


# 提取
def restore_net():
    # 方法一:提取整个网络
    net2 = torch.load('net.pkl')
    # 使用net2进行预测
    prediction = net2(x)

    # 绘制第二张子图
    plt.subplot(132)
    # 设置子图标题
    plt.title('Net2')
    plt.scatter(x.data.numpy(), y.data.numpy())
    plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)


def restore_params():
    # 使用Sequential快速搭建一个和net1结构一致的网络net3
    net3 = torch.nn.Sequential(
        torch.nn.Linear(1, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 1)
    )

    # 方法二:加载net1的参数,提取,然后赋给net3的参数
    net3.load_state_dict(torch.load('net_params.pkl'))
    prediction = net3(x)

    # 绘制子图3
    plt.subplot(133)
    plt.title('Net3')
    plt.scatter(x.data.numpy(), y.data.numpy())
    plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
    plt.show()


# net1进行预测,并且用两种方法进行保存模型
save()

# 提取整个网络到net2进行预测并绘图
restore_net()

# 提取net1的网络参数,然后赋给net3预测并绘图
restore_params()

运行结果:

在这里插入图片描述

因为网络结构和网络参数是一样的,所以训练出来的效果也是一致的!

猜你喜欢

转载自blog.csdn.net/Elon15/article/details/131645021