使用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 小时前
AI Agent 开发踩坑记:口播功能非得用 APP 原生实现吗?
前端·人工智能·agent
蝎子莱莱爱打怪8 小时前
DSpark 讲透:DeepSeek 不换模型,硬把 V4 提速 85%,是怎么做到的?
人工智能·面试·程序员
巫山老妖10 小时前
置身AI内
人工智能
IT_陈寒11 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
vanuan13 小时前
两个AI智能体第一次对话-A2A双Agent协作实战
人工智能
kfaino14 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
雨落Re17 小时前
如何设计一个高质量Skill
人工智能
Token炼金师17 小时前
大模型权重文件全指南:从格式选择到优化实战
人工智能
阿牛哥_GX17 小时前
CDP 浏览器操控原理:让脚本接管你的浏览器
人工智能
ThreeS17 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python