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

相关推荐
SuniaWang3 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
IDZSY04304 小时前
AI社交平台进阶指南:如何用AI社交提升工作学习效率
人工智能·学习
七七powerful4 小时前
运维养龙虾--AI 驱动的架构图革命:draw.io MCP 让运维画图效率提升 10 倍,使用codebuddy实战
运维·人工智能·draw.io
水星梦月4 小时前
大白话讲解AI/LLM核心概念
人工智能
温九味闻醉5 小时前
关于腾讯广告算法大赛2025项目分析1 - dataset.py
人工智能·算法·机器学习
White-Legend5 小时前
第三波GPT5.4 日400刀
人工智能·ai编程
. . . . .5 小时前
Claude Code Hooks的原理、触发执行机制以及如何编写 Hooks
人工智能
w_t_y_y5 小时前
codex(一)下载安装&使用
人工智能
唐兴通个人5 小时前
唐兴通应邀为平安财产险北京分公司高层主讲《新媒体营销》专项培训,引领保险业AI时代内容营销变革
人工智能