使用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参数

相关推荐
阳光是sunny8 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
冬奇Lab8 小时前
每日一个开源项目(第148篇):obsidian-skills - Obsidian CEO 亲写的 AI Agent 格式规范,让 Agent 不再破坏你的 Vault
人工智能·开源·资讯
ethantan8 小时前
AI Agent 组成:像人一样思考的智能体
人工智能·程序员·架构
冬奇Lab8 小时前
Workflow 系列(05):评测体系——三层测试结构与 Trace 追踪
人工智能·工作流引擎
ethantan9 小时前
一篇讲解AI Agent 组成:像人一样思考的智能体
人工智能·后端·程序员
Cosolar11 小时前
vLLM 生产级部署完全指南
人工智能·后端·架构
CodePlayer竟然被占用了11 小时前
被美国政府封杀18天,Claude Fable 5 回来了——但代价是什么?
人工智能
IT_陈寒12 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
smartpi12 小时前
SmartPi GPIO 脉冲与回复语执行时序指南
人工智能
阿里云大数据AI技术13 小时前
PAI支持一键部署GLM-5.2,Coding能力比肩Claude Opus 4.8
人工智能