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

相关推荐
思绪无限1 天前
YOLOv5至YOLOv12升级:木材表面缺陷检测系统的设计与实现(完整代码+界面+数据集项目)
人工智能·深度学习·目标检测·计算机视觉·木材表面缺陷检测
kishu_iOS&AI1 天前
深度学习 —— 损失函数
人工智能·pytorch·python·深度学习·线性回归
好运的阿财1 天前
OpenClaw工具拆解之canvas+message
人工智能·python·ai编程·openclaw·openclaw工具
TechubNews1 天前
新火集团首席经济学家付鹏演讲——2026 年是 Crypto 加入到 FICC 资产配置框架元年
大数据·人工智能
蒸汽求职1 天前
跨越 CRUD 内卷:半导体产业链与算力基建下的软件工程新生态
人工智能·科技·面试·职场和发展·软件工程·制造
DeepModel1 天前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
聊点儿技术1 天前
LLM数据采集如何突破AI反爬?——用IP数据接口实现进阶
人工智能·数据分析·产品运营·ip·电商·ip地址查询·ip数据接口
小兵张健1 天前
一场大概率没拿到 offer 的面试,让我更坚定去做喜欢的事
人工智能·面试·程序员
2501_940041741 天前
AI创建小游戏指令词
人工智能·游戏·prompt
AC赳赳老秦1 天前
OpenClaw二次开发实战:编写专属办公自动化技能,适配个性化需求
linux·javascript·人工智能·python·django·测试用例·openclaw