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

相关推荐
甲维斯21 分钟前
Claude Code中文界面版更一波!又改了5000+行!
人工智能·ai编程
腾讯云开发者25 分钟前
从前沿洞见到落地实践:腾讯云TVP布道澳门,燃动AI Agent新思潮
人工智能
雪隐36 分钟前
个人电脑玩AI-02让5060 Ti给你打工——Whisper语音识别篇(下)
人工智能·后端
HIT_Weston37 分钟前
110、【Agent】【OpenCode】todowrite 工具提示词(示例)(四)
人工智能·agent·opencode
ECT-OS-JiuHuaShan43 分钟前
什么是对和错?——“有针对性定义域的逻辑值的真伪”:认识论终极追问的公理化裁决
数据库·人工智能·算法·机器学习·数学建模
澹锦汐1 小时前
从 0 到 1 构建 AI 创意工具:独立开发者的 LLM 应用实战
人工智能
道友可好1 小时前
Superpowers vs OpenSpec vs Spec Kit:该选哪个?
前端·人工智能·后端
xixingzhe21 小时前
AI运维注意点
运维·人工智能
morning_judger1 小时前
Agent开发系列(十一)-知识库建设(知识地图)
人工智能