LayerList

class paddle.nn. LayerList ( sublayers=None ) [source]

LayerList holds sublayers, and sublayers it contains are properly registered. Holded sublayers can be indexed like a regular python list.

Parameters

sublayers (iterable of Layer, optional) – sublayers to hold

Examples

>>> import paddle

>>> class MyLayer(paddle.nn.Layer):
...     def __init__(self):
...         super().__init__()
...         self.linears = paddle.nn.LayerList(
...             [paddle.nn.Linear(10, 10) for i in range(10)])
...
...     def forward(self, x):
...         # LayerList can act as an iterable, or be indexed using ints
...         for i, l in enumerate(self.linears):
...             x = self.linears[i // 2](x) + l(x)
...         return x
append ( sublayer )

append

Appends a sublayer to the end of the list.

Parameters

sublayer (Layer) – sublayer to append

Examples

>>> import paddle

>>> linears = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(10)])
>>> another = paddle.nn.Linear(10, 10)
>>> linears.append(another)
>>> print(len(linears))
11
insert ( index, sublayer )

insert

Insert a sublayer before a given index in the list.

Parameters
  • index (int) – index to insert.

  • sublayer (Layer) – sublayer to insert

Examples

>>> import paddle

>>> linears = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(10)])
>>> another = paddle.nn.Linear(10, 10)
>>> linears.insert(3, another)
>>> print(linears[3] is another)
True
>>> another = paddle.nn.Linear(10, 10)
>>> linears.insert(-1, another)
>>> print(linears[-2] is another)
True
extend ( sublayers )

extend

Appends sublayers to the end of the list.

Parameters

sublayers (iterable of Layer) – iterable of sublayers to append

Returns

None

Examples

>>> import paddle

>>> linears = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(10)])
>>> another_list = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(5)])
>>> linears.extend(another_list)
>>> print(len(linears))
15
>>> print(another_list[0] is linears[10])
True