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

相关推荐
AI 编程助手GPT2 分钟前
ChatGPT 新手入门与实战操作指南
开发语言·人工智能·git·python·chatgpt
小陈phd4 分钟前
多模态大模型学习笔记(四十四)——图像计数(Image Counting):多目标密集场景下的精确统计
人工智能
Elastic 中国社区官方博客5 分钟前
使用 Jina CLIP v2 和 Elasticsearch 实现多语言图片搜索
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·jina
刘一说6 分钟前
AI科技热点日报 | 2026年06月02日
人工智能·科技
任我坤6 分钟前
Github Copilot 智能编程助手深度评测
人工智能·github·copilot
Agent手记7 分钟前
电信装维如何智能派单?AI 工程师匹配原理与智能体架构拆解
人工智能·ai·架构
动物园猫9 分钟前
停车场空车位检测数据集分享(适用于YOLO系列深度学习检测任务)
人工智能·深度学习·yolo
山科智能信息处理实验室12 分钟前
(AAAI-2026)KnowLP:GraphRAG 诱导双知识结构图,实现个性化学习路径推荐
人工智能·深度学习·大语言模型
zhangfeng113312 分钟前
DeepSeek V4 适配华为昇腾950 难度及开源情况
人工智能·pytorch·python·机器学习·华为·开源
searchforAI13 分钟前
Ai好记 vs Get笔记:AI音视频笔记工具深度测评对比
人工智能·笔记·学习·ai·音视频·语音识别