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

相关推荐
用户0183493016920 分钟前
用Zustand管理AI多会话状态
人工智能
武子康3 小时前
调查研究-198 Agent 到底该记住什么?读懂《What Must Generalist Agents Remember?》
人工智能·openai·agent
aqi003 小时前
15天学会AI应用开发(九)利用Chroma持久化向量数据
人工智能·python·大模型·ai编程·ai应用
武子康5 小时前
调查研究-197 FAISS vs Elasticsearch 全面对比:从向量检索、全文搜索到 RAG 选型指南
人工智能·elasticsearch·agent
青禾网络5 小时前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
用户252736278145 小时前
【技术实战】用 Spring Boot + Vue3 + LM Studio 在本地跑通 RAG 知识库
人工智能
用户5191495848455 小时前
VBScript随机数生成器内部机制:从时间种子到密码令牌破解
人工智能·aigc
米小虾5 小时前
Context Engineering —— 知识与记忆的窗口
人工智能·agent
IT_陈寒6 小时前
Python里这个赋值坑,连老司机都能翻车
前端·人工智能·后端