pytorch 三种模型保存方式


# train.py

import torch
from torch import nn
from torchvision.models import resnet18
from collections import OrderedDict

class Flatten(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self,x):
        return torch.flatten(x,1)

class Model(nn.Module):
    def __init__(self,num_classes,device):
        super().__init__()
        _m = resnet18(False).to(device)
        self.backbone = nn.Sequential(
            OrderedDict([("stem", nn.Sequential(_m.conv1, _m.bn1, _m.relu, _m.maxpool)),
                         ('layer1',_m.layer1),
                         ('layer2',_m.layer2),
                         ('layer3',_m.layer3),
                         ('layer4',_m.layer4),
                         ]))
        self.fc = nn.Sequential(
            nn.AdaptiveAvgPool2d((1, 1)),
            Flatten(),
            nn.Linear(_m.inplanes, num_classes)
        )

    def forward(self,x):
        x = self.backbone(x)
        x = self.fc(x)
        return x

if __name__ == "__main__":
    device = "cuda"
    x = torch.randn([1,3,64,64]).to(device)
    model = Model(10,device).to(device)
    print(model)
    pred = model(x)
    print(pred.shape)

1、save weight

# save weight
torch.save(model.state_dict(),'weight.pth')

# load
from train import Model,Flatten
x = torch.randn([1,3,64,64]).to('cuda')
model = Model(10,'cuda').to('cuda')
model.load_state_dict(torch.load('weight.pth',map_location='cuda'))
print(model(x).shape)

2、save model + weight

# save model + weight
torch.save(model,'model.pth')

# load
class Flatten(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self,x):
        return torch.flatten(x,1)

class Model(nn.Module):
    pass

x = torch.randn([1,3,64,64]).to('cuda')
model = torch.load("model.pth",map_location='cuda')
print(model)

# model(x) 报错
out = model.backbone(x)
out = model.fc(out)
print(out.shape)

3、save model + weight (use jit)

# save model + weight (use jit)
# torch.jit.save(model,'model_jit.pth') # 报错
x = torch.randn([1,3,64,64]).to('cuda')
traced_script_module = torch.jit.trace(model, x)
# 保存模型
traced_script_module.save("model_jit.pth")

# load
x = torch.randn([1,3,64,64]).to('cuda')
model = torch.jit.load('model_jit.pth',map_location='cuda')
print(model)
print(model(x).shape)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值