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

相关推荐
Learn Beyond Limits6 分钟前
TensorFlow Implementation of Content-Based Filtering|基于内容过滤的TensorFlow实现
人工智能·python·深度学习·机器学习·ai·tensorflow·吴恩达
是Yu欸10 分钟前
【AI视频】从单模型,到AI Agent工作流
人工智能·ai·ai作画·aigc·音视频·实时音视频
AI人工智能+21 分钟前
发票识别技术:结合OCR与AI技术,实现纸质票据高效数字化,推动企业智能化转型
人工智能·nlp·ocr·发票识别
用户51914958484527 分钟前
Aniyomi扩展开发指南与Google Drive集成方案
人工智能·aigc
ezl1fe30 分钟前
第零篇:把 Agent 跑起来的最小闭环
人工智能·后端·agent
说私域33 分钟前
开源链动2+1模式AI智能名片S2B2C商城小程序在竞争激烈的中低端面膜服装行业中的应用与策略
大数据·人工智能·小程序
佛喜酱的AI实践35 分钟前
Claude Code配置魔法:从单人编程到专属AI团队协作
人工智能·claude
文心快码BaiduComate37 分钟前
文心快码Comate3.5S更新,用多智能体协同做个健康管理应用
前端·人工智能·后端
叶楊38 分钟前
PEFT适配器加载
人工智能·深度学习·机器学习
Tezign_space1 小时前
AI用户洞察新纪元:atypica.AI如何重塑商业决策逻辑
人工智能·ai智能体·atypica