PyTorch 获取模型的所有层 [英] PyTorch get all layers of model

查看:100
本文介绍了PyTorch 获取模型的所有层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有任何 nn.Sequence 分组的情况下,采用 pytorch 模型并获取所有层的列表的最简单方法是什么?例如,有更好的方法来做到这一点吗?

导入预训练模型定义解包模型(模型):对于我在儿童中(模型):if isinstance(i, nn.Sequential): unwrap_model(i)其他: l.append(i)模型 = pretrainedmodels.__dict__['xception'](num_classes=1000, pretrained='imagenet')l = []unwrap_model(模型)打印(升)

解决方案

您可以使用 modules() 方法.这是一个简单的例子:

<预><代码>>>>模型 = nn.Sequential(nn.Linear(2, 2),nn.ReLU(),nn.Sequential(nn.Linear(2, 1),nn.Sigmoid()))>>>l = [model.modules() 中的模块的模块,如果不是 isinstance(module, nn.Sequential)]>>>升[线性(输入特征=2,输出特征=2,偏差=真),ReLU(),线性(输入特征=2,输出特征=1,偏差=真),Sigmoid()]

What's the easiest way to take a pytorch model and get a list of all the layers without any nn.Sequence groupings? For example, a better way to do this?

import pretrainedmodels

def unwrap_model(model):
    for i in children(model):
        if isinstance(i, nn.Sequential): unwrap_model(i)
        else: l.append(i)

model = pretrainedmodels.__dict__['xception'](num_classes=1000, pretrained='imagenet')
l = []
unwrap_model(model)            
            
print(l)
    

解决方案

You can iterate over all modules of a model (including those inside each Sequential) with the modules() method. Here's a simple example:

>>> model = nn.Sequential(nn.Linear(2, 2), 
                          nn.ReLU(),
                          nn.Sequential(nn.Linear(2, 1),
                          nn.Sigmoid()))

>>> l = [module for module in model.modules() if not isinstance(module, nn.Sequential)]

>>> l

[Linear(in_features=2, out_features=2, bias=True),
 ReLU(),
 Linear(in_features=2, out_features=1, bias=True),
 Sigmoid()]

这篇关于PyTorch 获取模型的所有层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆