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

相关推荐
长桥夜波1 分钟前
机器学习日报21
人工智能·机器学习
rchmin11 分钟前
Prompt Engineering 从入门到精通的系统学习路径
人工智能·学习·prompt
ACE198517 分钟前
AI Agent 设计模式深度解析:提示链(Prompt Chaining)模式
人工智能·设计模式·prompt
AndrewHZ18 分钟前
【图像处理基石】如何使用大模型进行图像处理工作?
图像处理·人工智能·深度学习·算法·llm·stablediffusion·可控性
AndrewHZ22 分钟前
【图像处理基石】图像处理的基础理论体系介绍
图像处理·人工智能·算法·计算机视觉·cv·理论体系
人邮异步社区34 分钟前
如何有效地利用AI辅助编程,提高编程效率?
人工智能·深度学习·ai编程
许泽宇的技术分享1 小时前
当AI Agent遇上.NET:微软Agent Framework的架构奥秘与实战启示
人工智能·microsoft·.net
爱笑的眼睛111 小时前
PyTorch Lightning:重新定义深度学习工程实践
java·人工智能·python·ai
做cv的小昊1 小时前
VLM经典论文阅读:【综述】An Introduction to Vision-Language Modeling
论文阅读·人工智能·计算机视觉·语言模型·自然语言处理·bert·transformer