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

相关推荐
冬奇Lab8 小时前
RAG 系列(十三):查询优化——让问题问得更好
人工智能·llm
上海云盾第一敬业销售8 小时前
大模型驱动的网络攻击:AI对抗AI,智能WAF的进化之路
人工智能
冬奇Lab8 小时前
企业引入 AI 之后,为什么提效不明显?
人工智能·aigc
冬奇Lab8 小时前
一天一个开源项目(第98篇):UI-TARS-Desktop - 字节跳动开源的多模态 GUI 代理栈
人工智能·开源·资讯
青岛前景互联信息技术有限公司8 小时前
OpenClaw 重构智慧消防:AI时代的平台融合实践
大数据·人工智能
梦梦代码精9 小时前
BuildingAI 上部署自定义工作流智能体:5 个实用技巧
大数据·人工智能·算法·开源软件
极客老王说Agent9 小时前
2026智造前瞻:实在Agent生产排期智能助理核心功能与使用方法详解
大数据·人工智能·ai·chatgpt
Mr_pyx9 小时前
Spring AI 入门教程:Java开发者的AI应用捷径
java·人工智能·spring
巫山老妖9 小时前
鹅厂十年:三段式技术成长复盘
android·人工智能·程序员