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

相关推荐
薛定谔的猫-菜鸟程序员2 分钟前
端侧免费大模型实测:MiniCPM5-2B-Q4_K_M 架构拆解与 4GB 显卡实测
人工智能·大模型·agent·hermes·minicpm5-2b
小海豚儿2 分钟前
没有反馈的 Loop,只是更贵的重试
人工智能·ai编程
用户302822530685 分钟前
Agent Skill工程:如何把一次成功运行提炼成可测试的方法
人工智能
ellenwan20265 分钟前
看到“最新 AI 量化学习”时,先让表达变清楚
人工智能·python
IvorySQL7 分钟前
打造下一代 AI Agent 的统一多模智能数据底座——PostgreSQL 与 AI 的融合演进
数据库·人工智能·postgresql
面朝大海,春不暖,花不开14 分钟前
Buat New Trenches, Kalian Bisa Baca Panduan Meta Ini
人工智能·机器学习
派大_星20 分钟前
基于 PyTorch 的 CNN 图片分类学习
pytorch·分类·cnn
RAOY的AI笔记20 分钟前
从ChatGPT注册场景理解Web身份认证:Session、Cookie、Token与MFA基础原理
人工智能·chatgpt
vibecoding7721 分钟前
AI 大模型广场选型完整指南:七大平台模型矩阵、接口兼容与定价横向对比(2026 年)
人工智能·大模型·ai编程
知几蜗牛23 分钟前
语音AI最大的误区,是默认每个人都在安静房间里说话
人工智能