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

相关推荐
wangqiaowq几秒前
AI-Native(AI 原生) 指从产品、架构、交互到组织流程,从第一天起就以 AI 为核心来设计,而不是在传统软件上后加一个 AI 功能。
人工智能
AI深栈2 分钟前
第 14 章 · LangGraph4j 入门:AI Agent 什么时候该上状态图
java·人工智能
学电子她就能回来吗3 分钟前
把自然语言变成可制造 CAD:开源 SolidWorks Automation Skill 的工程化实践
人工智能·python·自动化·solidworks·mcp
广西生活网5 分钟前
启元机器人接入腾讯 WorkBuddy 具身智能打通虚实服务新链路
人工智能
花花鱼8 分钟前
SpringBoot + Vue3 解决HTML反转义导致JSON解析失败的方案
人工智能·ai
H0311169859 分钟前
QuestMobile之外的数据分析平台信息整理:月狐数据、友盟+、GrowingIO
人工智能
桃西西呀11 分钟前
Agent说做完了,其实什么都没改:静默失败原因拆解
人工智能·llm·agent
骑士雄师15 分钟前
鉴权遗留问题
人工智能
政企项目老覃16 分钟前
大模型 Agent 自主任务编排:电商客服地址解析从 12% 失败率到 2.1% 的落地复盘
人工智能·程序人生·算法