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

相关推荐
roman_日积跬步-终至千里3 小时前
AI 能让一个人成为团队吗?从数据中台到 OPC,重新理解软件工程能力
大数据·人工智能·软件工程
在所不辞兄4 小时前
为什么神经网络在训练集损失已接近零后继续训练,测试性能仍可能继续提升,而不是单纯地越来越过拟合?
人工智能·深度学习·神经网络·机器学习·智能仿真
AI砖家4 小时前
ChatGPT Images 2.6 正式支持 GIF 生成:一张图片也能动起来,AI 动图创作时代来了!
人工智能·chatgpt
希和20274 小时前
免费AI视频生成工具汇总(国内优先,适合做漫剧、短视频,Obsidian笔记版)
人工智能·笔记·音视频
水如烟5 小时前
孤能子视角:逆溯法(存稿)——从终点参照解往回拆必经关卡
人工智能
用户2991422196805 小时前
GitHub 热榜项目:周榜(2026-11-08)
人工智能·开源·github
天天被压力5 小时前
【A股分钟级高频数据完全手册 #07】北交所历史分钟K线接口:京市Pro版分时批量
java·人工智能·python
用户2991422196805 小时前
AI 日报(2026年11月8日)
人工智能
天天被压力5 小时前
【A股分钟级高频数据完全手册 #08】股票日、分时数据接口对比:普通分时与Pro版差异实测
java·人工智能·python
miofly5 小时前
NVIDIA 开源 Cosmos 3 四款模型,用于交互式世界模拟与自动驾驶场景生成
人工智能