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

相关推荐
3DVisionary5 分钟前
捕捉亚毫米级裂纹演化!DIC技术为裂纹扩展与抗裂研究带来全新方案
人工智能·python·3d·应变测量·金属3d打印·dic精度检验方法·各向异性
GJGCY11 分钟前
2026制造业RPA技术落地指南:7大核心场景架构对比与跨系统集成实践
人工智能·ai·自动化·制造·rpa·制造业·智能体
Xi-Xu16 分钟前
在云服务器上安全运行 OpenClaw:从安装到加固的完整指南
运维·服务器·人工智能·安全
Dev7z17 分钟前
基于卷积神经网络和递归神经网络的PE恶意文件检测识别
人工智能·rnn·神经网络·cnn·pe恶意文件
chaors18 分钟前
从零学RAG0x05实战应用:企业智能知识库
人工智能·github·ai编程
V搜xhliang024619 分钟前
世界模型、强化学习PPOSAC
人工智能·深度学习·机器学习·语言模型·自然语言处理
EterNity_TiMe_20 分钟前
跨地域实时共创,使用白板协作不卡壳得最佳解决方案。
人工智能·web·cpolar
吴佳浩 Alben25 分钟前
OpenClaw 2026.3.2 — 2026.3.8 权限变更与安全加固
人工智能·安全·语言模型
xjf771128 分钟前
通义灵码Agent闭环工作流
人工智能·ai文档
AAwangzong31 分钟前
OpenClaw引爆工业AI革命:从跟风部署到系统进化的四重重构
人工智能