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

相关推荐
碧海银沙音频科技研究院10 分钟前
BP寻呼机原理
人工智能·嵌入式硬件
万俟淋曦24 分钟前
[ROS 系列学习教程] 建模与仿真 - 使用 ros_control 控制六轴串联机械臂
人工智能·ai·机器人·ros·机械臂·robotics·具身智能
IT_陈寒32 分钟前
Vue开发者必知:5个让你效率翻倍的隐藏技巧
前端·人工智能·后端
深蓝AI4 小时前
12000 名工程师的高盛,只用四个月就收回了交易员的 AI 编程权限
人工智能·程序员
怕浪猫8 小时前
这个十几个agent 协作项目值得关注
人工智能·面试·github
starzy199010 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
深蓝AI10 小时前
为什么 agent 的 demo 都很惊艳,上了生产就不靠谱
人工智能·程序员
数字新视界11 小时前
信创动环监控在机房环境管理中的智能化应用与实践分析
大数据·人工智能·物联网·信息与通信·动环监控系统
岁月宁静11 小时前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
深蓝AI11 小时前
一个项目五个 AI 同时干活,Claude Code 怎么让它们不互相打架
人工智能·程序员