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

相关推荐
一点一木8 分钟前
🚀 2026 年 8 月 GitHub 十大热门项目排行榜 🔥
人工智能·github
ssshooter13 分钟前
现在网页都能提供 MCP 了?!
前端·人工智能·程序员
京东云开发者20 分钟前
Claude Code vs Codex 记忆体系深度对比
人工智能
不加辣椒1 小时前
第 4 章 什么是 Harness Engineering
人工智能
桃西西呀1 小时前
上下文窗口都卷到 100 万了,大模型为什么还在为"位置"发愁?
人工智能·llm·ai编程
阿拉斯攀登1 小时前
SpringBoot整合MQTT:后端订阅设备数据、解析传感器报文
人工智能
然我2 小时前
模型不是 Agent:从零实现一个最小 Agent Loop
前端·人工智能·agent
黄油面包2 小时前
Codex 额度三天见底后,我重新做了一周预算
前端·人工智能
AI效率君2 小时前
Deer‑Flow 2.0 + Go‑MCP‑Server(add加法工具)保姆级完整教程
人工智能·agent
阿拉斯攀登2 小时前
SpringCloud微服务MQTT架构:设备消息统一接入、业务分发设计
人工智能