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

相关推荐
IT_陈寒8 小时前
Vite的静态资源打包让我熬夜到三点,这坑千万别跳
前端·人工智能·后端
玩转AI不是事9 小时前
用IndexedDB做AI对话离线缓存实战
人工智能
Asize10 小时前
多模态生图:从 Vite 工程化到前端调用 Qwen Image
javascript·人工智能·后端
MobotStone10 小时前
AI项目越多,为什么越容易失控
人工智能·aigc
十有八七10 小时前
AI时代的置身X内
前端·人工智能
Lkstar10 小时前
A2A协议深度解析|Agent2Agent通信标准,智能体互联网的"HTTP"
人工智能·llm
百度Geek说10 小时前
当代码越来越便宜,什么在变贵?
人工智能
橘子星10 小时前
LLM 无状态架构实践:从原理到代码落地
前端·javascript·人工智能
召钱熏11 小时前
裸聊可用 ≠ 工作流可用:Gemma4 12B 接入 Claude Code 的真实踩坑复盘
人工智能
黄敬峰11 小时前
从 Token 到向量:手把手带你通过代码读懂大模型(LLM)的“黑盒”原理
人工智能