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

相关推荐
Devil枫7 小时前
【腾讯位置服务开发者征文大赛】AI 赋能小程序地图开发:腾讯地图 Miniprogram Skill 实战记录
人工智能·小程序
blackorbird7 小时前
AI工作流自动化平台n8n正被大规模网络武器化
运维·网络·人工智能·自动化
阿杰学AI7 小时前
AI核心知识126—大语言模型之 CrewAI 和 AutoGen(简洁且通俗易懂版)
人工智能·语言模型·自然语言处理·agent·多智能体·智能体·多智能体协作框架
企业架构师老王7 小时前
2026年国内AI Agent选型指南:企业数字化转型中的非侵入式架构方案深度评测
人工智能·ai·架构
黎阳之光7 小时前
黎阳之光受邀出席上海口岸联合会2026智慧口岸研讨班 无感通关方案获盛赞
大数据·人工智能·算法·安全·数字孪生
hsg777 小时前
简述:地理深度学习全域训练PyTorch2.7+TorchGeo等基线
人工智能·深度学习
有梦想的牛牛7 小时前
GPT-6 能力畅想:当 AI 跨越“理解”走向“共生”
人工智能·gpt
米猴设计师7 小时前
PS电商详情页高效制作:Nano Banana一键生成电商高转化套图(附实操教程)
大数据·图像处理·人工智能·ai·aigc·startai·banana修图
落羽的落羽7 小时前
【Linux系统】深入线程:多线程的互斥与同步原理,封装实现两种生产者消费者模型
java·linux·运维·服务器·c++·人工智能·python