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

相关推荐
泯泷6 分钟前
像项目经理一样指挥 AI 团队:管理者模式
人工智能·llm·agent
京东云开发者16 分钟前
双11囤Token火了:京东搜索量暴涨7倍,AI生产力成新刚需
人工智能
ahccqw33 分钟前
OpenCV 车辆数量统计
人工智能·opencv·计算机视觉
人工智能AI技术1 小时前
LangGraph 本地 build 频频翻车,最终在服务器跑通流式对话
人工智能
Flynn Liang1 小时前
同一需求三套写法:用 Spring AI、LangChain4j、AgentScope Java 各实现一个带工具调用的 RAG 助手(实战对比)
java·人工智能·大模型·架构设计·spring ai·langchain4j·agentscope
汤姆宝库1 小时前
构建一个能用的RAG系统:切块、嵌入、混合检索与融合排序
人工智能
Dawson Zhu1 小时前
【LLM推理与Serving⑪】MoE推理与MLA:DeepSeek-V3架构下的显存与通信权衡
人工智能·语言模型·架构·aigc·agi
github_is_geeksKai2 小时前
50 个 AI 与开源工具怎么选:从实际用途到实现边界
人工智能
IT_陈寒2 小时前
Vite的HMR把我整不会了:一个生产环境的热更新坑
前端·人工智能·后端
github_is_geeksKai2 小时前
浏览器 AI 小工具怎么选?40 个项目与 5 类商业任务的参考指南
人工智能