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

相关推荐
Flynn Liang12 分钟前
大模型成本优化:基于 Redis 的可验证语义缓存架构
人工智能·redis·缓存·架构·ai agent·智能体
锋行天下20 分钟前
langgraph全栈项目(一)
前端·人工智能·后端
程序员cxuan29 分钟前
不得了,Google 造反了,Opus 5.5 又被干了
人工智能·后端·程序员
数字新视界1 小时前
能耗管理系统提升企业能源效率的实践与展望
大数据·人工智能·数据中心·机房管理·模块化机房
郝学胜-神的一滴1 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
Frag0ut2 小时前
Chrome 2026浏览器AI助手全攻略:智能问答与内容创作实战进阶指南
人工智能·chrome·ai助手·本地大模型·浏览器ai·网页智能总结·侧边栏ai
如夏倾城3 小时前
入侵检测系统(IDS)原理、部署模式与 IPS/防火墙对比
大数据·网络·人工智能·网络安全·云原生·架构·kubernetes
Dawson Zhu3 小时前
【模型量化⑤】Weight-Only INT4:AWQ与GPTQ两大算法深度解析
人工智能·语言模型·架构·aigc·agi
水如烟3 小时前
孤能子视角:通用智能 vs 分工协同智能群系统–––集中结晶 vs 分布式结晶
人工智能