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

相关推荐
ms365copilot5 分钟前
Excel Copilot聊天历史|关闭文件后,还能找回之前的AI分析对话
人工智能·excel·copilot
知几蜗牛6 分钟前
GPT-6 Astra来了:AI开始从"聊天机器人"进化成数字员工了吗?
人工智能
月华路6 分钟前
《模型不玄学》第25章 双头模型:共享底座 + 两个分支
人工智能·深度学习·机器学习
一次旅行14 分钟前
2026‑09‑07 AI产业深度解读|GPT-6 Astra引爆AGI争议、自动化科研落地、对齐监控能力衰减
人工智能·gpt·agi
人工智能培训14 分钟前
AI智能体落地价值:从工具赋能到产业重构,解锁企业降本增效新逻辑
人工智能·重构
LPCK_2026062215 分钟前
生物检测、化工、化学企业的智能体落地:拆出三块共性基石
人工智能
sougeo_geo15 分钟前
基于RAG架构的AI品牌心智量化:中立监测平台的技术实现与多模型验证实践
人工智能·架构
盼小辉丶16 分钟前
PyTorch计算机视觉(9)——变分自编码器(VAE)详解与实现
人工智能·pytorch·深度学习·计算机视觉
狗哥哥18 分钟前
年度能力建设 · 长期主义工作手册
人工智能
AC赳赳老秦18 分钟前
环保监测公开数据应用:OpenClaw 抓取空气与水质公开监测数据,开展区域环境质量趋势分析
大数据·数据库·人工智能·python·php·deepseek·openclaw