5.保存和获取神经网络【两种方法】

'''
Author: 365JHWZGo
Description: 5.保存和获取神经网络【两种方法】
Date: 2021-10-23 12:26:12
FilePath: \pytorch\pytorch\day06-2.py
LastEditTime: 2021-10-23 17:36:48
LastEditors: 365JHWZGo
'''
#导包
import torch
import matplotlib.pyplot as plt
from torch.autograd import Variable

#创造数据
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=True), Variable(y, requires_grad=True) 
# x, y = Variable(x), Variable(y) 

def save():
    #创造神经层
    net1 = torch.nn.Sequential(
        torch.nn.Linear(1,10),
        torch.nn.ReLU(),
        torch.nn.Linear(10,1)
    )
    optimizer = torch.optim.SGD(net1.parameters(),lr = 0.5)
    loss_func = torch.nn.MSELoss()
    for i in range(100):
        prediction = net1(x)
        loss = loss_func(prediction,y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        
    
    plt.figure(1,figsize=(10,3))  
    plt.subplot(131)
    plt.title('net1',fontdict={'color':'red','fontsize':20})
    plt.scatter(x.data.numpy(),y.data.numpy())
    plt.plot(x.data.numpy(),prediction.data.numpy(),lw=5,c='red')    

    torch.save(net1,'net1.pkl')
    torch.save(net1.state_dict(),'net1_state_dict.pkl')

#方法一:保存整个神经网络
def restore_net():
    net2 = torch.load('net1.pkl')
    prediction = net2(x)
      
    plt.subplot(132)
    plt.title('net2',fontdict={'color':'red','fontsize':20})
    plt.scatter(x.data.numpy(),y.data.numpy())
    plt.plot(x.data.numpy(),prediction.data.numpy(),lw=5,c='red')    

#方法二:保存神经网络当中一些参数
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('net1_state_dict.pkl'))
    prediction = net3(x)
    plt.subplot(133)
    plt.title('net3',fontdict={'color':'red','fontsize':20})
    plt.scatter(x.data.numpy(),y.data.numpy())
    plt.plot(x.data.numpy(),prediction.data.numpy(),lw=5,c='red')
    plt.show()

save()
restore_net()
restore_params()



关于其中是否要写Variable的情况分析

什么都不写

在这里插入图片描述

x, y = Variable(x), Variable(y)

在这里插入图片描述

x, y = Variable(x, requires_grad=True), Variable(y, requires_grad=True)

在这里插入图片描述

x, y = Variable(x, requires_grad=False), Variable(y, requires_grad=False)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

365JHWZGo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值