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

相关推荐
WiSirius几秒前
LLM:基于 AgentScope + Streamlit 的 AI Agent脑暴室
人工智能·深度学习·自然语言处理·大模型·llama
跨境猫小妹3 分钟前
采购交期拉长如何把补货策略从经验改为预测
大数据·人工智能·产品运营·跨境电商·营销策略
console.log('npc')6 分钟前
Cursor,Trae,Claude Code如何协作生产出一套前后台app?
前端·人工智能·react.js·设计模式·ai·langchain·ai编程
AI视觉网奇9 分钟前
动作迁移算法笔记 2026
人工智能·笔记
@TsUnAmI~17 分钟前
当翻译不只是翻译:我做了一个AI桌面翻译助手
人工智能
码农垦荒笔记19 分钟前
OpenClaw实战 #07:从 0 写一个自定义 Skill——让 AI 自动同步 Notion 待办到飞书(完整代码)
人工智能·飞书·notion
进击ing小白20 分钟前
OpenCv之图像的仿射和透视变化
人工智能·opencv·机器学习
lpfasd12322 分钟前
2026创业风向:做一款“AI陪伴成长”App,是风口还是雷区?
人工智能
ECT-OS-JiuHuaShan24 分钟前
朱梁万有递归元定理,解构西方文明中心论幻觉
开发语言·人工智能·php