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

相关推荐
掘金013 分钟前
Cursor Agent Prompt 拆解
人工智能·程序员·github
Dawson Zhu4 分钟前
大模型推理的三维本质:原理解析与工程实践
人工智能·语言模型·架构·aigc·agi
回眸&啤酒鸭4 分钟前
【回眸】低压电工实操考试
人工智能
RisunJan10 分钟前
【这就是AI】AI每日资讯简报 - 2026-09-29(周二)
人工智能
TechEdu20260610 分钟前
[人工智能]Python08:NumPy 检查与诊断
人工智能·numpy
Leo.yuan11 分钟前
Agent化分析加速成形:FineBI AI原生技术架构落地,推动AI+BI分析范式跃迁
大数据·人工智能
龙孚信息17 分钟前
内容转化的逆向解构:从商机落地回溯 B2B 内容营销的断点与重塑
人工智能
拉格朗日(Lagrange)23 分钟前
【第 1 章】WorkBuddy 从入门到高手
人工智能
猎头南楼24 分钟前
企业网络安全体系与AI安全检测实践:零信任、纵深防御与LLM安全
人工智能·安全·web安全
yi01125 分钟前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划