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

相关推荐
AI科技星几秒前
超复数全域经济周期场与信息谱场——金融与密码学底层理论重构《0·1·∞三元一体全域超复数统一场论》系列全集(六一字不漏完整合订终版)
人工智能·算法·金融·密码学·拓扑学·乖乖数学·全域数学
开发者如是说13 分钟前
Vibe Code 了产品却无人下载?我写了个工具来帮你
人工智能·程序员·产品
AI科技星18 分钟前
《01无穷全域信息场论:算子G与宇宙本体高维完备公理大典》
人工智能·python·算法·金融·乖乖数学·全域数学
战场小包24 分钟前
AI 写代码越来越快,慢下来的那个人变成了我
人工智能·agent
sunywz1 小时前
【AI RAG知识库】05.【导入】【节点5】node_item_name_recognition
人工智能
彩云回1 小时前
长文档处理(Long Document Processing)策略
人工智能
AIGS0011 小时前
企业AI落地:从RAG到AgentRAG的技术跃迁
java·人工智能·人工智能ai大模型应用
程序员cxuan1 小时前
Claude Code 焚诀(一):Claude Code 六种心智模型
人工智能·后端
FlagOS智算系统软件栈1 小时前
FlagOS技术工作坊:当AI开始“自己部署自己”,大模型基础设施进入“无人驾驶”时代
人工智能
一楼的猫1 小时前
AI写作检测机制技术深度解析:200+维度检测、叙事指纹与网文AI辅助怎么过审
人工智能·学习·安全·chatgpt·ai写作