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

相关推荐
匠测AI说1 分钟前
AI for Testing 提效实战·测试设计(四):我拿一个真实需求,让 AI 陪我走完了整个测试设计(全程复盘)
人工智能·测试
Omics Pro3 分钟前
研究证实AI虚拟细胞可用于药物靶点发现
数据库·人工智能·算法·机器学习·自然语言处理
柏慧通云报餐7 分钟前
智慧食堂食材溯源数字化方案|采购 - 入库 - 餐桌全链路记录体系落地实践
大数据·运维·人工智能
柯南46687 分钟前
【AI工程师精讲】涌现能力:能力在连续提升,还是尺子在骗人
人工智能·ai编程
在所不辞兄7 分钟前
常微分方程详解与应用
人工智能·神经网络·算法·机器学习
小鹿的周先生8 分钟前
第16章-RAG
java·人工智能·ai编程
不加辣椒8 分钟前
第 12 章 推理型 Sensors 深入
人工智能
用户1917291270838 分钟前
企业级 AI Agent 编排层架构:从华为、谷歌的同周动作看 2026 拐点
人工智能
电子科技圈11 分钟前
芯科科技扩展 AI 开发者平台,简化物联网开发并拓展边缘智能
人工智能·科技·物联网
袖清暮雨12 分钟前
机器学习之随机森林
人工智能·随机森林·机器学习