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

相关推荐
阿里云大数据AI技术9 分钟前
在 EMR Serverless Spark 中访问 Fluss
人工智能·spark
Dawson Zhu11 分钟前
《Agentic Design Patterns》第 21 章导读:探索与发现
人工智能·语言模型·架构·aigc·agi
龙腾AI白云11 分钟前
数字孪生、具身智能、世界模型三者交叉
数据库·人工智能·机器学习·flask·pygame
JAVA_AI人工智能项目实战13 分钟前
大模型结构演进.学习笔记
大数据·人工智能·语言模型·架构
商业数据派15 分钟前
京东11.11:首日下单用户数同比双位数增长、超百项服务首次全景亮相
人工智能
W***259219 分钟前
2026企业AI办公工具选型指南:从需求匹配到平台评估
人工智能
石狮松松21 分钟前
第04 章 机器学习、深度学习、大模型到底什么关系
人工智能
有月牙23 分钟前
Work Agent深度解读:AI长程任务的执行机制与落地边界
人工智能
Pingred23 分钟前
我把一个私有化 RAG 系统真正跑通了:LocalRAG v0.1.0 发布
人工智能·python
miofly25 分钟前
Google Gemini 4 Argon:用一个模型完成机器人训练全流程
人工智能