ParameterList

  • class paddle.fluid.dygraph.ParameterList(parameters=None)[源代码]

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

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

返回:无

代码示例

  1. import paddle.fluid as fluid
  2. import numpy as np
  3.  
  4. class MyLayer(fluid.Layer):
  5. def __init__(self, num_stacked_param):
  6. super(MyLayer, self).__init__()
  7. # 使用可迭代的 Parameters 创建 ParameterList
  8. self.params = fluid.dygraph.ParameterList(
  9. [fluid.layers.create_parameter(
  10. shape=[2, 2], dtype='float32')] * num_stacked_param)
  11. def forward(self, x):
  12. for i, p in enumerate(self.params):
  13. tmp = self._helper.create_variable_for_type_inference('float32')
  14. self._helper.append_op(
  15. type="mul",
  16. inputs={"X": x,
  17. "Y": p},
  18. outputs={"Out": tmp},
  19. attrs={"x_num_col_dims": 1,
  20. "y_num_col_dims": 1})
  21. x = tmp
  22. return x
  23.  
  24. data_np = np.random.uniform(-1, 1, [5, 2]).astype('float32')
  25. with fluid.dygraph.guard():
  26. x = fluid.dygraph.to_variable(data_np)
  27. num_stacked_param = 4
  28. model = MyLayer(num_stacked_param)
  29. print(len(model.params)) # 4
  30. res = model(x)
  31. print(res.shape) # [5, 2]
  32. replaced_param = fluid.layers.create_parameter(shape=[2, 3], dtype='float32')
  33. model.params[num_stacked_param - 1] = replaced_param # 替换最后一个参数
  34. res = model(x)
  35. print(res.shape) # [5, 3]
  36. model.params.append(fluid.layers.create_parameter(shape=[3, 4], dtype='float32')) # 添加参数
  37. print(len(model.params)) # 5
  38. res = model(x)
  39. print(res.shape) # [5, 4]