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

相关推荐
kaixin_啊啊4 小时前
【零基础学AI】第 25 章课后练习与答案
人工智能
水如烟5 小时前
孤能子视角:逆溯法与传统方法比较
人工智能
jimmyleeee5 小时前
大模型安全之五十一:OWASP LLM Top 10 全景解读
人工智能·安全
飞哥数智坊6 小时前
DeepSeek-V4.1-Flash-1017 官方许愿案例太吸睛,我也复刻了一个
人工智能
深蓝AI6 小时前
自报提效 12 倍,模型进步加速 1.9 倍:METR 报告到底量了什么
人工智能·程序员
怕浪猫7 小时前
从工具到代理:一张图看懂 2026–2030 年 AI 如何重构 11 个行业
人工智能·程序员·产品
云和数据.ChenGuang7 小时前
LangGraph 异步 Node 的设计与写法实践
开发语言·人工智能·python·机器学习·php
会飞锦鲤8 小时前
工业AI视觉检测项目完整实施方案
人工智能·深度学习·视觉检测·缺陷检测·模型训练·ai项目·工业应用
优秘智能8 小时前
优秘智能增长智脑视角下的AI试点与验收
人工智能·知识管理·企业应用
天诰8 小时前
SA-K-11 检索会消失吗与四个未解问题
java·服务器·人工智能·python·机器学习·ai编程