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

相关推荐
秦先生在广东11 分钟前
Headroom 深度解析:本地化 LLM 代理下的 Token 压缩艺术
人工智能
罗西的思考16 分钟前
【Agentic RL】Dressage Staleness 控制深度分析
人工智能·算法·机器学习
秦先生在广东22 分钟前
深度解析 XERJ:为 AI Agent 打造的 Rust 本地搜索引擎
人工智能
天天代码码天天43 分钟前
录下自己的声音,让电脑替你讲故事:我做了一个 C# 离线配音工具
人工智能
Rocky Ding*1 小时前
深入解析GPT-6 Astra提示词工程:从Skills、AGENTS.md到可验证的Agent交付
论文阅读·人工智能·深度学习·机器学习·aigc·ai-native·提示词工程
志尊宝1 小时前
AI原生前端开发(009):AI辅助性能分析与优化建议
人工智能·react.js·ai-native
KeyAction66661 小时前
第二届中国国际人工智能+行动大会看点:智能体专场、算力账本与产品发布
人工智能·ai
johnsong1 小时前
AI前沿日报 2026-10-19:硅基心智觉醒
人工智能
紧跟先前的步伐2 小时前
Go AI Agent 实战 03|Token、上下文窗口与模型调用成本
java·人工智能·golang
老金带你玩AI2 小时前
Taste Skill V2来了,AI做的网站还会一眼认出来吗?
人工智能