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

相关推荐
Kel6 分钟前
深入剖析 openai-node 源码:一个工业级 TypeScript SDK 的架构之美
javascript·人工智能·架构
岛雨QA16 分钟前
Skill学习指南🧑‍💻
人工智能·agent·ai编程
波动几何21 分钟前
从人性到无名:一条向内的觉悟之路
人工智能
EllenLiu32 分钟前
架构演进与性能压榨:在金融 RAG 中引入条款森林 (FoC)
人工智能·架构
IT_陈寒1 小时前
深入理解JavaScript:核心原理与最佳实践
前端·人工智能·后端
Presto1 小时前
AI 时代 .env 文件不再安全——我试图找到替代方案,然后撞上了一堵墙
人工智能
IT WorryFree1 小时前
OpenClaw-Medical-Skills 仓库介绍
人工智能·skill·openclaw
多年小白1 小时前
今日AI科技简报 | 2026年3月19日
人工智能·科技·ai编程
逄逄不是胖胖1 小时前
《动手学深度学习》-69预训练bert数据集实现
人工智能·深度学习·bert
IT_陈寒1 小时前
Python开发者的效率革命:这5个技巧让你的代码提速50%!
前端·人工智能·后端