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

相关推荐
零基础1232 分钟前
Agent 的 Memory 怎么做科研:以中医诊断场景为例
人工智能·经验分享·python·语言模型
归秋1425 分钟前
人声节奏对齐软件推荐:从专业DAW到AI人声制作工具怎么选
人工智能
海天一色y1 小时前
模型部署的「通用语」:ONNX 转换
pytorch·onnx
2601_962966641 小时前
数学与应用数学专业想进管理咨询,2027届秋招需要补哪些商业知识和技能?
人工智能
ss2731 小时前
AI全栈实战 | 3.2-01 Python 基础:四大数据容器怎么选,推导式为什么是 Pythonic 的灵魂
开发语言·人工智能·python
Sweet锦1 小时前
不调 Python,不装向量库:我用纯 Java 写了一套以图搜图引擎
java·人工智能·开源·图搜索
fpcc2 小时前
AI和大模型—JEV模型
人工智能
weixin_446260852 小时前
面向演进式企业AI智能体技能的持续流程级评估
人工智能
量子-Alex2 小时前
【大模型后训练SFT】Finetuning with Sampling: SFT Learns Better Than You Think
人工智能·深度学习·机器学习
ForDreamMusk2 小时前
Transformer Encoder Block
人工智能·深度学习·transformer