pytorch中的named_parameters(), nam
2021-01-17 本文已影响0人
劲草浅躬行
- named_modules
内部采用yield关键字,得到生成器。可以看到函数内部给出的例子,当外部迭代调用net.named_modules()时,会先返回prefix='',以及net对象本身。然后下一步会递归的调用named_modules(),继而深度优先的返回每一个module。
def named_modules(self, memo: Optional[Set['Module']] = None, prefix: str = ''):
r"""Returns an iterator over all modules in the network, yielding
both the name of the module as well as the module itself.
Yields:
(string, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, ``l`` will be returned only once.
Example::
>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
print(idx, '->', m)
0 -> ('', Sequential(
(0): Linear(in_features=2, out_features=2, bias=True)
(1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
"""
if memo is None:
memo = set()
if self not in memo:
memo.add(self)
yield prefix, self
for name, module in self._modules.items():
if module is None:
continue
submodule_prefix = prefix + ('.' if prefix else '') + name
for m in module.named_modules(memo, submodule_prefix):
yield m