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

相关推荐
程序猿追2 小时前
HarmonyOS 7 多标签草稿,关掉当前页之后该留下谁
pytorch·深度学习·harmonyos
用户96098457922402 小时前
本机 AGY 环境备份、跨平台改造与新机一键初始化实战
人工智能
前进的李工2 小时前
Agent 学习笔记 29:多 Agent 协作的六种失败模式
人工智能·乐观锁·ai agent·harness·理解债与认知缺陷·拜占庭故障·循环失控
用户96098457922402 小时前
多会话并行控 Chrome 不打架:标签归属隔离、桌面输入互斥与第六色状态灯实战
人工智能
用户96098457922402 小时前
项目级 .agent/ 隔离、双协议 Hooks 与只读 DB/Redis 插件实战
人工智能
用户96098457922402 小时前
MCP 懒加载代理与 Chrome 会话标签组:按需拉起浏览器、容器与标签归组实战
人工智能
云票2 小时前
湖南废止施工组织设计智能评审:2分规则取消
大数据·人工智能
王亚博_Abel2 小时前
127 加 1 为什么是 -128?手拆补码四个实验实测
人工智能
Techblog of HaoWANG2 小时前
具身智能机器人专题(7)大模型 / 语音 / RAG 的容器化架构与系统开发
人工智能·算法·大模型·边缘计算·具身智能
RPA机器人就用八爪鱼3 小时前
电商重复流程自动化:用 AI 搭建和维护,用 RPA 按规则执行
人工智能·自动化·rpa