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

相关推荐
杨杨杨大侠5 小时前
RAG、记忆、上下文,这几个东西到底怎么串起来?
人工智能·agent
system_error_x6 小时前
MCP协议开发实战:从零搭建AI Agent工具链
人工智能
Sayai6 小时前
ComfyUI+混元视频实战:12G 显存跑 13G 模型,5 分钟出片(国产开源,附模型与工作流)
人工智能·aigc·音视频·comfyui·hunyuanvideo·混元视频
燧机科技SuiJi7 小时前
山体坍塌落石滑坡泥石流监测系统 落石泥石流监控摄像机
大数据·人工智能·深度学习·yolo
国科安芯7 小时前
立方星与微纳卫星综合电子微型化趋势下的抗辐射MCU选型综述
人工智能·单片机·嵌入式硬件·mcu·risc-v·抗辐射
诸神缄默不语7 小时前
小春学习日刊 2026年第4期:2026.10.16
人工智能
draracle7 小时前
为什么 AI 无法胜任系统架构
人工智能·系统架构
未来和明天8 小时前
iLeadE-3403边缘计算网关10.4 TOPS数据采集、视频接入与外设扩展等多元化应用需求
人工智能·边缘计算
youngfengying8 小时前
集成学习及置信度
人工智能·机器学习