• 感谢大家访问本站,希望本站的内容可以帮助到大家!

  • 问题反馈可发送邮件到stubbornhuang@qq.com

  • 本站由于前段时间遭受到大量临时和国外邮箱注册,所以对可注册的邮箱类型进行了限制!

  • 如果觉得本站的内容有帮助,可以考虑打赏博主哦!

  • 计算机图形学与计算几何经典必备书单整理,下载链接可参考:https://www.stubbornhuang.com/1256/

  • 工资「喂饱肚子」,副业「养活灵魂」!

  • 本站会放置Google广告用于维持域名以及网站服务器费用。

  • 在本站开通年度VIP,无限制下载本站资源和阅读本站文章

  • 欢迎大家交换友链,可在https://www.stubbornhuang.com/申请友情链接进行友链交换申请!

Pytorch – 模型微调时删除原有模型中的某一层的方法

Pytorch 发布于2022-08-08 阅读 10,597次 0次评论 0次点赞 本文共1310个字,阅读需要4分钟。

本文以去除Pytorch预置的ResNet18网络中最后一层全连接分类层为例,说明模型微调时如何去除模型中某一层的方法。

我们想要在模型中去掉某一层实际上就等效于在该层不进行任何操作,直接将上一层的值直接返回即可,下面提供了3种方法进行选择。

1 使用自定义nn.Module替换指定层

在本方法中,自定义了一个Identity类继承自nn.Module,并在forward方法中不进行如何操作直接返回原值,达到去除某一层的效果。

# -*- coding: utf-8 -*-

import torch
import torch.nn as nn
import torchvision.models

class Identity(nn.Module):
    def __init__(self):
        super(Identity, self).__init__()

    def forward(self, x):
        return x

if __name__ == '__main__':
    resnet18_modify = torchvision.models.resnet18(pretrained=True)
    resnet18_modify.fc = Identity()

    tensor = torch.rand([1,3,244,244])

    out = resnet18_modify(tensor)

    print(out.shape)

2 将需删除的层指定为空的nn.Sequential

这种方法更加简单,直接将想要删除的层设置为空的nn.Sequential,同样是不进行任何操作返回原值。

# -*- coding: utf-8 -*-

import torch
import torch.nn as nn
import torchvision.models

if __name__ == '__main__':
    resnet18_modify = torchvision.models.resnet18(pretrained=True)
    resnet18_modify.fc = nn.Sequential()

    tensor = torch.rand([1,3,244,244])

    out = resnet18_modify(tensor)

    print(out.shape)

3 先将已有模型中的子模块放到list中,然后在list中去掉某一层,然后再重组网络

# -*- coding: utf-8 -*-

import torch
import torch.nn as nn
import torchvision.models

if __name__ == '__main__':
    resnet18_modify = torchvision.models.resnet18(pretrained=True)
    print(resnet18_modify)

    modules = list(resnet18_modify.children())[:-1]
    resnet18_modify = nn.Sequential(*modules)

    print(resnet18_modify)

    tensor = torch.rand([1,3,244,244])

    out = resnet18_modify(tensor)

    print(out.shape)

欢迎扫码关注我的微信公众号,及时获取文章更新

微信公众号二维码

本文作者:StubbornHuang

版权声明:本文为站长原创文章,如果转载请注明原文链接!

原文标题:Pytorch – 模型微调时删除原有模型中的某一层的方法

原文链接:https://www.stubbornhuang.com/2284/

发布于:2022年08月08日 8:48:19

修改于:2023年06月25日 20:44:25

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

文章末尾
上一篇
资源分享 - Artificial Intelligence for Games , Third Edition 英文PDF下载
计算几何与计算机图形学资源
下一篇
资源分享 - Rotation Transforms for Computer Graphics , First Edition 英文PDF下载
计算几何与计算机图形学资源
当前分类随机文章推荐

发表评论

您必须 [ 登录 ] 才能发表留言!

关注我们的公众号

微信公众号