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

相关推荐
狒狒AI4 分钟前
DeepSeek Harness 插件生态拆解:31,259 个仓库与 93% 装不上的口径差
人工智能
AI前端工程狮5 分钟前
我把 MCP 长任务拆成三个工具,token 账单涨了 7 倍
javascript·人工智能·程序员
阿里云大数据AI技术7 分钟前
如何用 STAROps Elasticsearch 智能助手看穿“搜索变慢”
人工智能·agent
用户3214687511111 分钟前
不会编程也能考AI证书?应用型与技术型认证的门槛差在哪
人工智能
程序员cxuan20 分钟前
GPT-6.2 Astra 发布了,但口碑崩了。。。
人工智能·后端·程序员
SelectDB22 分钟前
让数据更易查、更好用:正泰集团基于 SelectDB 的 AI 应用实践
人工智能
字节跳动数据库35 分钟前
火山引擎缓存数据库:如何构建超大规模缓存集群的无感弹性能力
数据库·人工智能·后端
阿里云大数据AI技术36 分钟前
MaxAgent 实战课堂(二):从单作业诊断到作业定时巡检
人工智能
泯泷40 分钟前
给你一个免费的20人 AI 团队,你的胜算真的变大了吗?
人工智能·llm