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

相关推荐
‿hhh14 小时前
Dify核心模块详解:从文本生成到智能体
人工智能·学习·microsoft·agent·上下文·记忆
大鱼>14 小时前
模型可解释性:特征重要性/SHAP/LIME
人工智能·python·机器学习·lstm
霖大侠14 小时前
Decoupled and Reusable Adaptation for Efficient Cross-Modal Transfer
人工智能·深度学习·算法·机器学习·transformer
武子康14 小时前
调查研究-216 Tesla Robotaxi 进了 Miami,但真正的考题才刚开始
人工智能·llm·自动驾驶
LaughingZhu14 小时前
Product Hunt 每日热榜 | 2026-07-05
人工智能·经验分享·深度学习·神经网络·产品运营
海兰14 小时前
【AI编程思考:第六篇】学习记忆与 Agent 状态:让 AI 真正“记得”你
人工智能·学习·ai编程
Dragon Wu15 小时前
ComfyUI ReActor需要下载检测模型的解决方案
人工智能·ai
雨辰AI15 小时前
【零基础实战】大模型入门面试 100 问:基础概念 + 环境实操(一问一答版,直接背诵)
人工智能·ai·面试·职场和发展·ai编程
龙萱坤诺15 小时前
Claude Fable 5 重新开放:最强模型回归
大数据·运维·人工智能