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

相关推荐
AI日报派送佬4 小时前
2026年10月14日AI行业日报|Gemini 4 Argon正式发布;小模型跨设备传播风险引发安全热议
网络·人工智能·openai·谷歌·deepseek·anthropic·ai日报
镜象科技6 小时前
职业院校AI心理健康解决方案怎么选?三个特殊场景与三类路线
人工智能
Leo.yuan6 小时前
企业Data Agent架构选型:帆软Dora基于NL2BI的现有BI体系复用方案
大数据·人工智能
朱涛的自习室6 小时前
70 美金的 Beyond Compare,我让 Gemini 4 和 DeepSeek 造个开源免费版(Day 2)
android·前端·人工智能
米小虾6 小时前
上下文:Agent 的眼睛里到底装着什么
人工智能·agent
米小虾6 小时前
Agent = 大脑 + 眼睛 + 手脚:一篇看懂现代 AI Agent 的骨架
人工智能
小小测试开发6 小时前
安全评测得分 0.9556 掉到 0.3257,只改了 top_k 和 prompt_style 之外的题面比例
人工智能·安全·prompt
slacker-kian7 小时前
[实践]-用LLM对文本结构化:把多段文本描述变成规范的 JSON 知识库
人工智能·llm·prompt·结构化·pydantic·one-shot 提示
品牌常新7 小时前
景区巡逻机器人怎么选?派宝S5全地形守护解析
运维·人工智能·机器人