使用pytorch搭建ResNet并基于迁移学习训练

这里的迁移学习方法是载入预训练权重的方法

python 复制代码
    net = resnet34()
    # load pretrain weights
    # download url: https://download.pytorch.org/models/resnet34-333f7ec4.pth
    model_weight_path = "./resnet34-pre.pth"
    assert os.path.exists(model_weight_path), "file {} does not exist.".format(model_weight_path)
    net.load_state_dict(torch.load(model_weight_path, map_location='cpu'))
    # for param in net.parameters():
    #     param.requires_grad = False

    # change fc layer structure
    in_channel = net.fc.in_features
    net.fc = nn.Linear(in_channel, 5)

这里的迁移学习方法是载入预训练权重的方法net = resnet34():注意这里没有传入参数num_classes 因为后面才载入所有的参数,会覆盖我们设定的classes

change fc layer structure

in_channel = net.fc.in_features # fc 为全连接层 in_features为特征矩阵的深度

net.fc = nn.Linear(in_channel, 5)

如果不想使用迁移学习的方法,则注释阴影部分,在net = resnet34()中传入num_classes参数

相关推荐
qq_4523962334 分钟前
第二篇:《安装、配置与 psql 高效使用》
人工智能
方方洛40 分钟前
ray教程-11-可观测性与调试
人工智能·分布式·机器学习
我是李工啊43 分钟前
PRD 总和代码对不上?让 AI 从代码生成状态图和权限矩阵
人工智能·产品经理
ComputerInBook1 小时前
泛函分析概观
人工智能·算法·机器学习·泛函分析
burg_xun1 小时前
【生命科学 Agent】推理平台(二)
人工智能·程序人生·系统架构
zh路西法1 小时前
【模型式强化学习】(二)PETS——从概率动力学模型到模型预测控制(MPC)
pytorch·python·强化学习·pe·mpc·ces·pets
IT_陈寒1 小时前
Vue的这个响应式陷阱我居然现在才发现
前端·人工智能·后端
lanxiaoqing021 小时前
演讲训练的第一步:先敢说,再会说
人工智能·学习·学习方法·口才
巫山老妖1 小时前
REA 工程解析:让 AI Agent 拿着证据做逆向
人工智能
梦想的颜色1 小时前
【AI速览】Codex 系列模型选型指南:效率、成本、任务匹配全维度决策
人工智能·chatgpt·codex·luna·astra·sol·大模型选型