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

相关推荐
一切皆是因缘际会4 分钟前
存算一体芯片软件双模式:单字符驱动网络(普通CPU也能跑)
人工智能·物联网·ai·系统架构·架构设计·发布订阅·存算一体
字节逆旅15 分钟前
Claude Code Router 接入过程的爬坑记录
人工智能·claude
江畔柳前堤22 分钟前
github实战指南01-账号配置与 SSH 密钥
运维·人工智能·深度学习·ssh·github·pyqt·信号处理
workflower1 小时前
使用大语言模型处理用户需求
大数据·人工智能·设计模式·重构·动态规划
CodePlayer竟然被占用了2 小时前
没有生态的大模型不算前沿
人工智能
米小虾2 小时前
AI Agent 开发实战:2026年主流框架与MCP协议深度解析
人工智能·agent
米小虾2 小时前
2026年AI大模型半年报:从"参数军备"到"生态为王",谁在领跑下半场?
人工智能
m0_571186602 小时前
第五十周周报
人工智能
寰宇视讯2 小时前
解码AI未来 2026世界制造业大会人工智能与机器人展9月启幕
人工智能·机器人