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

相关推荐
阿里云大数据AI技术15 分钟前
DataWorks Data Agent 实战课堂(一):解锁你的7×24h全能“数据搭子”DataWorks AI助理!
大数据·人工智能·agent
得一录23 分钟前
大模型中Temperature的解释
人工智能
Database_Cool_26 分钟前
阿里云RDS主从延迟解决方案_只读实例半同步复制最佳实践
数据库·人工智能
XMan_Liu32 分钟前
AI聊天机器人架构学习
人工智能·架构·机器人
喝拿铁写前端32 分钟前
AI 时代,ESLint 应该怎么做得更好
前端·人工智能·代码规范
派叔35 分钟前
老字号数字化转型的困境与路径:一个系统架构视角下的观察
大数据·人工智能·系统架构·产品运营·流量运营
阿里-于怀38 分钟前
阿里云刚发布的 AgentLoop 是什么?
人工智能·阿里云·云计算
2601_9563198844 分钟前
最新AI量化提效,先做可验证的小流程
人工智能·python
朴马丁1 小时前
从制造到智造:国产PLM如何赋能化工新材料企业研发创新
大数据·人工智能·制造·流程行业plm·化工新材料行业
AI棒棒牛1 小时前
YOLO26 全网独家改进创新:ECCV2026 PriorEye 主干网络改进,引入视觉-空间先验门控 Backbone,复杂场景涨点新思路!
人工智能·神经网络·目标检测·yolo26