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

相关推荐
fpcc19 分钟前
AI和大模型——扩展模型
人工智能
xixingzhe26 小时前
AI 自然语言转SQL
人工智能
love530love6 小时前
【笔记】AutoClaw NSIS 安装器卡死、进程杀不掉、目录删不了?我是这么解决的
人工智能·windows·笔记·agent
Mandy的名字被占用了6 小时前
晨风AI+知识付费系统|学练考全闭环,重构教育变现新模式
人工智能·后端
步步为营DotNet6 小时前
Avalonia 11.3 本地离线AI图像识别绑定Minimal API AI推理网关
人工智能
满怀冰雪6 小时前
06-自动微分入门:用 Paddle 计算梯度
人工智能·python·深度学习·paddle
架构源启6 小时前
文档接入与智能解析:基于 Spring AI 1.1.x 的多格式解析、版面理解与结构化抽取
java·人工智能·spring
李昊哲小课7 小时前
GLM 多技术栈集成完整教程
人工智能·智能体
浩哥学JavaAI8 小时前
2026年最新AI agent面试(10)_通信与行业动态
人工智能·面试·职场和发展
新知图书8 小时前
7.4 测试与发布(一键生成PPT智能体开发)
人工智能·agent·ai agent·智能体·扣子