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

相关推荐
kfaino2 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
雨落Re4 小时前
如何设计一个高质量Skill
人工智能
Token炼金师4 小时前
大模型权重文件全指南:从格式选择到优化实战
人工智能
阿牛哥_GX4 小时前
CDP 浏览器操控原理:让脚本接管你的浏览器
人工智能
ThreeS4 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
米小虾5 小时前
Loop Engineering —— 循环的设计与自主执行
人工智能·agent
米小虾5 小时前
Harness Engineering —— 系统的安全护栏
人工智能·agent
火山引擎开发者社区6 小时前
积分当钱花,火山引擎开发者激励计划首月消费双倍回馈
人工智能
aqi006 小时前
15天学会AI应用开发(十)把文本嵌入模型换成国产模型
人工智能·python·ai编程