加载指定层的预训练模型代码

import torch
import os
import torchvision.models as models
import torch.nn as nn

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("using {} device".format(device))


class Net(nn.Module):
    def __init__(self, model):
        super(Net, self).__init__()
        self.resnet50 = nn.Sequential(*list(model.children())[:-1])
        self.fc = nn.Linear(2048, 2)

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


# 先加载在创建net
model = models.resnet50(pretrained=True)
model_weight_path = "./resnet50.pth"
# 等价于if not,条件为假时执行
assert os.path.exists(model_weight_path), "file {} does not exist.".format(model_weight_path)

model.load_state_dict(torch.load(model_weight_path, map_location=device))
net = Net(model)
print(net)

参考:
https://blog.csdn.net/whut_ldz/article/details/78845947
https://blog.csdn.net/xys430381_1/article/details/107038723

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值