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

相关推荐
stereohomology几秒前
Kimi K3编程实力远超GLM5.2:一个Trae复赛证据
人工智能·大模型·对比·why不coding
qizayaoshuap7 分钟前
# 倒计时器 — HarmonyOS TextInput与计时任务管理深入实践
pytorch·深度学习·华为·harmonyos
阳光是sunny12 分钟前
LangGraph实战教程:状态管理与`graph.invoke`入参深度解析
前端·人工智能·后端
老猿AI洞察15 分钟前
7月25日热点:马斯克说中国AI有望成为全球领导者,这次不是客套话
大数据·人工智能
AI_小站20 分钟前
Loop Engineering又是啥?一文讲清企业Agent落地的四层工程进化论
java·人工智能·架构·prompt·大模型开发·智能体·大模型应用
BEOL贝尔科技20 分钟前
还在担心样本的安全吗?如何制定有效的温湿度异常应急预案?
人工智能·安全
科技之门27 分钟前
百公里管网漏损分级定位实战方案2026
前端·人工智能·算法
火山引擎开发者社区27 分钟前
LLM Space 开源!任意组装 loop、tools、skills,顺手无痛“蒸馏” Kimi-K3
人工智能
zhishidi30 分钟前
深度学习中的优化器
人工智能·深度学习