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

相关推荐
老兵发新帖9 分钟前
关于ONNX和pytorch,我们应该怎么做?结合训练和推理
人工智能
方安乐12 分钟前
杂记:对齐研究(AI alignment)
人工智能
方见华Richard39 分钟前
世毫九《认知几何学修订版:从离散概念网络到认知拓扑动力学》
人工智能·经验分享·交互·原型模式·空间计算
人工智能培训1 小时前
基于Transformer的人工智能模型搭建与fine-tuning
人工智能·深度学习·机器学习·transformer·知识图谱·数字孪生·大模型幻觉
emma羊羊1 小时前
【AI技术安全】
网络·人工智能·安全
玄同7651 小时前
告别 AgentExecutor:LangChain v1.0+ Agent 模块深度迁移指南与实战全解析
人工智能·语言模型·自然语言处理·langchain·nlp·agent·智能体
永恒的溪流1 小时前
环境出问题,再修改
pytorch·python·深度学习
Fxrain1 小时前
[Reading Paper]FFA-Net
图像处理·人工智能·计算机视觉
GISer_Jing1 小时前
Memory、Rules、Skills、MCP如何重塑AI编程
前端·人工智能·aigc·ai编程
DS随心转APP1 小时前
ChatGPT和Gemini回答怎么导出
人工智能·ai·chatgpt·deepseek·ds随心转