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

相关推荐
Sailing14 小时前
🤔🤔Dify 不必推倒重来,把重逻辑下沉到 LangGraph
人工智能·langchain·agent
oak隔壁找我15 小时前
AI从大语言模型发展至今的核心术语演进表
人工智能
电科_银尘15 小时前
【大模型算法与工程 37】语言模型强化学习基础:策略、奖励与优势
人工智能·算法·语言模型
衡石科技15 小时前
看板发出去之后:评论、订阅与受控发布的工程链路
大数据·运维·人工智能·数据可视化
挖掘狂人15 小时前
AI 会写代码之后,程序员该学什么?
人工智能·程序员·ai编程
艺杯羹15 小时前
11月23日AI前沿复盘:安全双警报、模型降价潮与工程防线
人工智能·网络安全·系统架构·大模型·ai agent
东坡肘子16 小时前
大众的 macOS,还是开发者的 macOS? -- 肘子的 Swift 周报 #163
人工智能·swiftui·swift
xsd202411181 天前
Eye-in-Hand 还是 Eye-to-Hand?
人工智能
邂逅and回眸1 天前
自进化的 Agent 是通往 AGI 的路吗
人工智能·agi