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

相关推荐
冬奇Lab35 分钟前
烧了数千美金 Token,我用 AI Agent 打通了企业级 Bug 修复全流程
人工智能·debug
冬奇Lab1 小时前
一天一个开源项目(第85篇):TypeScript 巫师把自己的 Claude 配置推到了 GitHub,一夜全球第一
人工智能·开源·claude
爱艺江河1 小时前
智慧合规的HarmonyOS原生实践:与OpenClaw适配的项目方案浅析
人工智能·华为·harmonyos
xiaoduo AI1 小时前
客服机器人用知识图谱推理吗?Agent功能介绍+关联问答,跨品类问题能推导?
人工智能·机器人·知识图谱
Data-Miner1 小时前
数以轻舟聚焦Excel-Agent场景:当AI做表工具学会说人话
人工智能·excel
甲维斯1 小时前
完了!我要背弃Opus4.7叛逃到GPT5.5+Codex了
人工智能·ai编程
夏沫の梦1 小时前
生图新王GPT-image-2已用!附使用教程+生成案例
人工智能
AI木马人1 小时前
13.【多租户架构实战】如何让一个AI系统同时服务多个用户且数据完全隔离?(完整设计方案)
人工智能·架构
sjsjsbbsbsn1 小时前
大模型核心知识总结
java·人工智能·后端
qq_411262422 小时前
四博 AI 双目智能音箱方案:把“会说话的音箱”升级成“会表达、会感知、会控制”的 AI 终端
人工智能·智能音箱