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

相关推荐
xiangjiaodalishi13 小时前
主流 AI 爬虫 User-Agent 清单大全:分组、配置与持续维护(2026 版)
人工智能·爬虫·python
昇腾CANN13 小时前
10月26日直播丨DeepSeek推理性能跃迁4.5倍,ACL Graph技术解密
人工智能·昇腾·cann·cann开源
普贤莲花13 小时前
先学Workbuddy还是“人工智能训练师”,或者python基础课?
开发语言·人工智能·python
数聚天成DeepSData13 小时前
第三方地图工具导出的 Landsat 影像,使用条件和 USGS 官方下载的一样吗
人工智能·深度学习·机器学习·数据集·deepsdata
VIP_CQCRE13 小时前
AI 工具入口不等于独立 SaaS:Studio 分站的配置模型与边界
人工智能·saas·ai工具·技术架构·acedatacloud
长不大的杨瑞杰13 小时前
OpenCode v2 团队治理实战:多仓库 Policy、灰度发布与故障回滚
运维·人工智能·安全·软件工程·devops
AIyy86613 小时前
用AI辅助做PPT的一些实践体会
人工智能
loulanyue_13 小时前
当AI学会自主攻击与渗透破壁:Agent行为链失控与Mythos级攻防颠覆下的安全范式重构——读CNCC2026第六届网络生态治理论坛实录
网络·人工智能·安全
李航198313 小时前
虚拟盖房子,在游戏中学习房子的建造过程
人工智能·学习·游戏·计算机视觉·ai编程