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

相关推荐
fthux1 小时前
招聘季实测:我用 TraeWork 搭了一套 AI 简历初筛系统
人工智能·ai编程·trae
SLD_Allen1 小时前
NVIDIA KAI Scheduler深度解析——Kubernetes原生AI调度器的架构、原理与实践
人工智能·架构·kubernetes
小玮看世界1 小时前
从“画图”到“Mermaid”:AI语义理解与架构绘制的演进之路
人工智能·深度学习·计算机视觉
小岐AI观2 小时前
智赋岐黄适合养生馆吗?
大数据·人工智能·物联网
YOLO数据集集合2 小时前
煤炭物料检测数据集:基于YOLO26的矿山传送带智能“哨兵”
人工智能·yolo·数据挖掘·煤炭·煤炭检测·矿山传送带·传送带异物
深小乐2 小时前
DeepSeek Harness 强是真的强,普通用户可以再等等
人工智能
蜡台3 小时前
大模型算力下放客户端:浏览器/本地设备全落地方案解析
人工智能·ai