PyTorch get all layers of model(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?
You can iterate over all modules of a model (including those inside each Sequential
) with the modules()
method. Here's a simple example:
这篇关于PyTorch 获取模型的所有层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!