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

相关推荐
济南凡维7 分钟前
CODESOFT中如何将标签保存为PDF文件
网络·人工智能·打印机·codesoft
weixin_4692738110 分钟前
Image Translate AI:利用 AI实现图片翻译
人工智能
ysu_031411 分钟前
边界条件的硬约束与软约束——从试函数构造到谱分析诊断
人工智能·pytorch·深度学习·物理信息神经网络·pinns·边界条件·ntk
会飞锦鲤12 分钟前
基于 Mask R-CNN 的药片缺陷检测系统
人工智能·pytorch·python·神经网络·resnet-50
kyriewen17 分钟前
GPT-6 拿下模型众测第一:我拆完 30 个主题的实时榜单,「最强 AI」得看你问哪个场景
人工智能·程序员·ai编程
jimmyleeee19 分钟前
大模型安全之十六:AI Security Posture Management
人工智能·安全
人工智能AI技术28 分钟前
2026老后端转AI Agent:技术体检+完整复习路线
人工智能
七牛云行业应用34 分钟前
2026 年 9 月 Coding Agent Harness 选型完整指南:30 个工具、SDK 与运行时
人工智能·agent·ai编程
梧桐凰37 分钟前
AI 时代测试工程师的武器库:实战工具指南
人工智能·功能测试·测试用例
武子康37 分钟前
小智服务端怎样组织 ASR、LLM、TTS?先追本次连接实际使用的对象
人工智能·llm·agent