深度学习04 -模型管理

访问模型参数

import torch
from torch.utils import data
from torch import nn

net = nn.Sequential(nn.Linear(2, 4), nn.ReLU(), nn.Linear(4, 1))

print((net[0].state_dict()))
print(net[0].bias)
print(net[0].bias.data)
rderedDict([('weight', tensor([[ 0.2167, -0.4856],
        [-0.6567, -0.4602],
        [ 0.1185,  0.1153],
        [-0.0756, -0.6647]])), ('bias', tensor([0.4804, 0.4804, 0.3834, 0.7041]))])
Parameter containing:
tensor([0.4804, 0.4804, 0.3834, 0.7041], requires_grad=True)
tensor([0.4804, 0.4804, 0.3834, 0.7041])

保存Tensor数据

>>> x = torch.arange(4)
>>> torch.save(x, 'x-file')
>>> x2 = torch.load('x-file')
>>> x2
tensor([0, 1, 2, 3])

保存模型参数

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(1, 2)
        self.output = nn.Linear(2, 2)

    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))

net = MLP()

torch.save(net.state_dict(), 'mlp.params')

clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
clone.eval() # 从train模式调整为test模式,不再进行训练更改梯度

net.state_dict() , clone.state_dict()

(OrderedDict([('hidden.weight', tensor([[-0.6865],
                       [-0.2476]])),
              ('hidden.bias', tensor([ 0.3468, -0.3090])),
              ('output.weight', tensor([[ 0.1645, -0.1768],
                       [ 0.7000, -0.6238]])),
              ('output.bias', tensor([-0.0137, -0.4359]))]),
 OrderedDict([('hidden.weight', tensor([[-0.6865],
                       [-0.2476]])),
              ('hidden.bias', tensor([ 0.3468, -0.3090])),
              ('output.weight', tensor([[ 0.1645, -0.1768],
                       [ 0.7000, -0.6238]])),
              ('output.bias', tensor([-0.0137, -0.4359]))]))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值