ParameterList

class paddle.nn.ParameterList ( parameters=None ) [源代码]

参数列表容器。此容器的行为类似于Python列表,但它包含的参数将被正确地注册和添加。

参数:

  • parameters (iterable,可选) - 可迭代的Parameters。

返回:无

代码示例

  1. import paddle
  2. import numpy as np
  3. class MyLayer(paddle.nn.Layer):
  4. def __init__(self, num_stacked_param):
  5. super(MyLayer, self).__init__()
  6. # create ParameterList with iterable Parameters
  7. self.params = paddle.nn.ParameterList(
  8. [paddle.create_parameter(
  9. shape=[2, 2], dtype='float32')] * num_stacked_param)
  10. def forward(self, x):
  11. for i, p in enumerate(self.params):
  12. tmp = self._helper.create_variable_for_type_inference('float32')
  13. self._helper.append_op(
  14. type="mul",
  15. inputs={"X": x,
  16. "Y": p},
  17. outputs={"Out": tmp},
  18. attrs={"x_num_col_dims": 1,
  19. "y_num_col_dims": 1})
  20. x = tmp
  21. return x
  22. data_np = np.random.uniform(-1, 1, [5, 2]).astype('float32')
  23. x = paddle.to_tensor(data_np)
  24. num_stacked_param = 4
  25. model = MyLayer(num_stacked_param)
  26. print(len(model.params)) # 4
  27. res = model(x)
  28. print(res.shape) # [5, 2]
  29. replaced_param = paddle.create_parameter(shape=[2, 3], dtype='float32')
  30. model.params[num_stacked_param - 1] = replaced_param # replace last param
  31. res = model(x)
  32. print(res.shape) # [5, 3]
  33. model.params.append(paddle.create_parameter(shape=[3, 4], dtype='float32')) # append param
  34. print(len(model.params)) # 5
  35. res = model(x)
  36. print(res.shape) # [5, 4]