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

相关推荐
TechEdu2026063 分钟前
[人工智能]豆包(Doubao):模型能力、应用架构与工程实践
人工智能·ai
IT_陈寒4 分钟前
Vue的嵌套组件竟然吃掉了我的事件?
前端·人工智能·后端
Henry-SAP13 分钟前
SAP独立需求与相关需求的区别解析
人工智能·云原生·sap·erp
沫儿笙21 分钟前
弧焊机器人智能节气阀
人工智能·机器人
小新科研测评35 分钟前
2026 年 3 种 PDF 文献翻译方案横评:公式/表格/双栏排版保真度实测
人工智能·ai·pdf·自动翻译
xierui12312336 分钟前
OpenAI 拟停止向 Cursor供模:如何设计不绑供应商的AIAgent架构
人工智能·系统架构·软件工程
workflower37 分钟前
人形机器人灵巧手产业链
人工智能·设计模式·机器人·云计算·无人机
deepdata_cn1 小时前
Qubit如何改变世界?密码、医药、AI 三大落地场景
人工智能·量子计算
亚远景aspice1 小时前
亚远景-ASPICE 与工具的结合:AI 原生工具链如何破解 ASPICE4.0 落地的效率困局
人工智能·aspice·过程管理