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

相关推荐
sunneo2 分钟前
每周精选GitCode开源项目
人工智能
sinovoip4 分钟前
香蕉派BPI-M7S开源单板计算机采用瑞芯微RK3588s芯片设计,与树莓派产品尺寸一样
人工智能·开源·业界资讯
数据百晓通9 分钟前
2026 智能体重构数据治理:全链路 AI、云生态、场景嵌入赛道解析
大数据·运维·人工智能
特立独行的猫a12 分钟前
小鸿 AI新玩法:面向 AI Agent 的通用语音交互硬件技术方案
人工智能·atomgit·小鸿ai·贾维斯
Elivs27 分钟前
RMSNorm函数
人工智能·算法·机器学习
2401_8322981029 分钟前
AI安全与全球治理:构建可控可信的智能发展新秩序
人工智能
Akir.weiwen31 分钟前
跨层禁止:机器如何拦截非法语义绑定
人工智能·设计规范·语义
xiakq38 分钟前
2026 年八大 LLM API 横评:DeepSeek V4 vs GPT-4o vs Claude vs Gemini
人工智能·gpt·ai·claude
u01030552741 分钟前
Java图像处理实战指南
人工智能·1024程序员节
铃木之影1 小时前
Java 版本 RAG 示例(Spring AI + Milvus)
java·人工智能·spring