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

相关推荐
米小虾38 分钟前
Agent Skill 规范与 Skill-Creator 核心思想
人工智能·agent
ZhengEnCi1 小时前
09e-斯坦福CS336作业四:大规模语言模型训练数据收集与处理
人工智能
oil欧哟1 小时前
Codex 最佳实践(超级长文):先搞懂 AI,再用好 AI
前端·人工智能·后端
甲维斯1 小时前
日本发布比肩Fable5的模型?Fugu Ultra初探!
人工智能·ai编程
雪隐1 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地FLUX.2 Klein 的 AI 图片生成
人工智能·后端
腾讯云开发者2 小时前
腾讯云TVP走进香港数码港,解码AI出海新范式
人工智能
用户47949283569152 小时前
又当又立: Anthropic 这篇安全白皮书,为什么让人恶心
人工智能
Darling噜啦啦2 小时前
AI Loop 自迭代循环实战:让 AI 自动写文案直到完美——从 Prompt 工程到 Loop 工程
人工智能
vanuan2 小时前
MCP协议实战(Python版):让AI直接查你的数据库
人工智能
Vuhao2 小时前
为什么同样的问题,别人的AI回答质量高40%?
人工智能