Torch之模型的保存与加载

从一个小demo讲解

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())

# 变为Variable
x, y = Variable(x), Variable(y)

# 定义网络
net = torch.nn.Sequential(
    torch.nn.Linear(1, 10),
    torch.nn.ReLU(),
    torch.nn.Linear(10, 1)
)

print(net)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Sequential (
  (0): Linear (1 -> 10)
  (1): ReLU ()
  (2): Linear (10 -> 1)
)
1
2
3
4
5
# 选择优化方法
optimizer = torch.optim.SGD(net.parameters(), lr = 0.5)

# 选择损失函数
loss_func = torch.nn.MSELoss()

# 训练网络
for i in xrange(1000):
    # 对x进行预测
    prediction = net(x)
    # 计算损失
    loss = loss_func(prediction, y)
    # 每次迭代清空上一次的梯度
    optimizer.zero_grad()
    # 反向传播
    loss.backward()
    # 更新梯度
    optimizer.step()

plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw = 5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 10, 'color':  'red'})
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
第一种方式,保存整个模型

# 保存训练的模型

# 保存整个网络和参数
torch.save(net, 'net.pkl')

# 重新加载模型
net = torch.load('net.pkl')

# 用新加载的模型进行预测
prediction = net(x)
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw = 5)
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
第二种方式,只保存模型参数

# 只保存网络的参数, 官方推荐的方式
torch.save(net.state_dict(), 'net_params.pkl')

# 定义网络
net = torch.nn.Sequential(
    torch.nn.Linear(1, 10),
    torch.nn.ReLU(),
    torch.nn.Linear(10, 1)
)

# 加载网络参数
net.load_state_dict(torch.load('net_params.pkl'))

# 用新加载的参数进行预测
prediction = net(x)
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw = 5)
plt.show()

--------------------- 
作者:Never-Giveup 
来源:CSDN 
原文:https://blog.csdn.net/qq_36653505/article/details/84728395 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值