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

相关推荐
ShallWeL1 分钟前
【机器学习】(16)—— 数值数据
人工智能·python·算法·机器学习·数据分析
赤龙ERP2 分钟前
赤龙一周观察 · 2026年7月第1周(07-06 ~ 07-12)
人工智能·创业创新·erp
console.log('npc')13 分钟前
AI Agent 前端流式渲染核心技术文档(SSE \+ WebSocket \+ 打字机渲染)
前端·人工智能·websocket
泠不丁14 分钟前
Next.js AI 应用路由设计:页面轻一点,边界清楚一点
人工智能
法外狂徒123 分钟前
将 Pi Agent 接入 HagiCode 的实践之路
服务器·前端·人工智能
CoderIsArt24 分钟前
使用深度学习方法进行纺织品和颜色缺陷检测
人工智能·深度学习
木木学AI24 分钟前
2026年云呼叫中心PoC验证:通信底座、高并发、工单集成三维评估方法
人工智能
hongyucai26 分钟前
详解rlinf强化学习四步曲
人工智能·python·算法·架构
c_lb728826 分钟前
2026年下半年AI量化工具,阶段不同重点也不同
人工智能·python