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

相关推荐
郝学胜-神的一滴几秒前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
火山引擎开发者社区9 分钟前
豆包工作,3 个月,800 万,20 亿
人工智能
Chuck.li18 分钟前
AI 长篇创作工具选型:工作流对照与自测清单
人工智能·大模型·ai写作·网文作者·ai网文·豆包写作
aleimu30 分钟前
Windows 11 右键打开 Cmder 2.0:从找不到菜单到默认使用 Cmder
前端·人工智能·后端
SwanArc技术笔记1 小时前
读技术文档,先用哪个 AI?模型指南筛选与 GPT-6.2 Astra 实操
人工智能
深海鱼在掘金1 小时前
深入浅出RAG——第21章:回顾与展望
人工智能
羲云网络1 小时前
GPT Image 2.6 GIF 交付排障:上线后为什么只剩第一帧?
图像处理·人工智能·前端开发·gif
安爹前沿AI1 小时前
Seedance 有个文档里没写的参数:开了码率涨 3.9 倍,费用一分没多
人工智能
深海鱼在掘金1 小时前
深入浅出RAG——第20章:端到端实战:企业级知识库问答系统
人工智能
黑十1 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能