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

相关推荐
imDwAaY43 分钟前
机器学习入门:从感知机到逻辑回归,理解线性分类器与Softmax CS188 Note20 学习笔记
人工智能·笔记·python·学习·机器学习·逻辑回归
无负今日_tq1 小时前
【无标题】
人工智能·深度学习·条纹
郑洁文1 小时前
基于CNN的异常流量监测系统的设计与实现
人工智能·神经网络·网络安全·cnn
爱吃肉的鹏1 小时前
基于深度学习的电缆异常检测
人工智能·深度学习
钓了猫的鱼儿1 小时前
基于深度学习+AI的茶叶病害目标检测与预警系统(Python源码+数据集+UI可视化界面+YOLOv11训练结果)
人工智能·深度学习·目标检测
codefan※1 小时前
干掉幻觉实战:如何构建企业级知识图谱增强 RAG
人工智能·大模型·llm·知识图谱·neo4j·rag·graphrag
码农大坚果1 小时前
智能体开发实战02|Harness工程入门
人工智能·agent
知识领航员1 小时前
30个AI音乐提示词|直接复制可用,覆盖6大风格
人工智能·adobe·chatgpt·prompt·aigc·音视频
ECT-OS-JiuHuaShan1 小时前
辩证函数,渡劫代谢:时势造英雄,英雄发神经
数据库·人工智能·机器学习
YOLO数据集集合1 小时前
YOLOv11+DeepSeek多技术融合电网缺陷巡检平台|绝缘子破损瓷瓶故障AI识别、前后端一体化电力运维管理系统落地开发
运维·人工智能·yolo