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

相关推荐
2601_9654490813 小时前
AI视频制作:做系列历史地图视频想固定音色,AI 音色克隆的流程实测
人工智能·音视频
2601_9620710013 小时前
从OpenRouter到Crazyrouter:Claude Code三处改动
人工智能·ai
阿里云大数据AI技术13 小时前
云栖实录|从代码上下文到千亿级文档:Qoder × 阿里云 Elasticsearch 落地生产级Agent向量检索
人工智能·elasticsearch
汤姆宝库13 小时前
具身智能深拆:VLA、世界模型与数据飞轮
开发语言·人工智能·php
鲜于言悠90513 小时前
Jev爆火:不生成文字,直接输出概率的决策模型
人工智能
美团技术团队13 小时前
如何在“不能出错”的系统里使用 AI Coding?分布式存储实践与边界
人工智能
枫叶丹414 小时前
AI 提出科学假设之后:从数据筛选到实验验证
人工智能·chatgpt·开源·agent·codex
kaixin_啊啊14 小时前
【零基础学AI】第 19 章——用分类模型识别类别
人工智能·分类·数据挖掘
郝学胜-神的一滴14 小时前
AI 编程智能体 17:四步搞定专属AI智能体
大数据·人工智能·python·神经网络·算法·langchain·强化学习
vx1530278236214 小时前
CDGA|AI时代,数据治理的位置下沉了吗?
大数据·人工智能·cdga·数据治理