Pytorch学习(七)---- 保存提取

莫烦python视频学习笔记 视频链接https://www.bilibili.com/video/BV1Vx411j7kT?from=search&seid=3065687802317837578

import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# import os 这里是为了防止报错加的

torch.manual_seed(1)         # reproducible

# fake data
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = x.pow(2) + 0.2*torch.rand(x.size())
x, y = Variable(x, requires_grad=False), Variable(y, requires_grad=False)

# 神经网络的保存
def save():
    # save net1
    net1 = torch.nn.Sequential(              # Sequential的功能在这个括号里逐层搭建神经层
        torch.nn.Linear(1, 10),
        torch.nn.ReLU(),                     # 激励函数
        torch.nn.Linear(10, 1)
    )
    optimizer = torch.optim.SGD(net1.parameters(), lr=0.25)  # 传入参数,lr是学习效率
    loss_func = torch.nn.MSELoss()

    for t in range(100):
        prediction = net1(x)
        loss = loss_func(prediction, y)  # 预测值与真实值对比
        optimizer.zero_grad()  # 将梯度降为零
        loss.backward()
        optimizer.step()  # 以学习效率0.5优化梯度

    # plot result
    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')  # entire all
    torch.save(net1.state_dict(), 'net_params.pkl')  # 保存参数


# 神经网络的提取
# method 1
def restore_net():
    net2 = torch.load('net.pkl')
    prediction = net2(x)
    # plot result
    plt.figure(1, figsize=(10, 3))
    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)


# method 2
def restore_params():
    net3 = torch.nn.Sequential(
        torch.nn.Linear(1, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 1)
    )
    net3.load_state_dict(torch.load('net_params.pkl'))
    prediction = net3(x)
    # plot result
    plt.figure(1, figsize=(10, 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()

# save net1
save()
# restore entire net
restore_net()
# restore params
restore_params()

一开始将训练的学习效率设置为0.5,即:

 optimizer = torch.optim.SGD(net1.parameters(), lr=0.5)  # 传入参数,lr是学习效率

结果图像如下,很明显学习效果是失败的。

Pytorch学习(七)---- 保存提取_第1张图片
重新设置学习效率,发现在0.25~0.3学习效果最好
Pytorch学习(七)---- 保存提取_第2张图片

你可能感兴趣的:(神经网络,python)