Assign

class paddle.nn.initializer.Assign ( value, name=None ) [源代码]

该OP使用Numpy数组、Python列表、Tensor来初始化参数。

参数:

  • value (Tensor|numpy.ndarray|list) - 用于初始化参数的一个Numpy数组、Python列表、Tensor。

  • name (str,可选)- 具体用法请参见 Name,一般无需设置,默认值为None。

返回:

由Numpy数组、Python列表、Tensor初始化的参数。

代码示例

  1. import paddle
  2. import numpy as np
  3. # numpy array
  4. data_1 = paddle.ones(shape=[1, 2], dtype='float32')
  5. weight_attr_1 = paddle.framework.ParamAttr(
  6. name="linear_weight_1",
  7. initializer=paddle.nn.initializer.Assign(np.array([2, 2])))
  8. bias_attr_1 = paddle.framework.ParamAttr(
  9. name="linear_bias_1",
  10. initializer=paddle.nn.initializer.Assign(np.array([2])))
  11. linear_1 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_1, bias_attr=bias_attr_1)
  12. # linear_1.weight: [2. 2.]
  13. # linear_1.bias: [2.]
  14. res_1 = linear_1(data_1)
  15. # res_1: [6.]
  16. # python list
  17. data_2 = paddle.ones(shape=[1, 2], dtype='float32')
  18. weight_attr_2 = paddle.framework.ParamAttr(
  19. name="linear_weight_2",
  20. initializer=paddle.nn.initializer.Assign([2, 2]))
  21. bias_attr_2 = paddle.framework.ParamAttr(
  22. name="linear_bias_2",
  23. initializer=paddle.nn.initializer.Assign([2]))
  24. linear_2 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_2, bias_attr=bias_attr_2)
  25. # linear_2.weight: [2. 2.]
  26. # linear_2.bias: [2.]
  27. res_2 = linear_2(data_2)
  28. # res_2: [6.]
  29. # tensor
  30. data_3 = paddle.ones(shape=[1, 2], dtype='float32')
  31. weight_attr_3 = paddle.framework.ParamAttr(
  32. name="linear_weight_3",
  33. initializer=paddle.nn.initializer.Assign(paddle.full([2], 2)))
  34. bias_attr_3 = paddle.framework.ParamAttr(
  35. name="linear_bias_3",
  36. initializer=paddle.nn.initializer.Assign(paddle.full([1], 2)))
  37. linear_3 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_3, bias_attr=bias_attr_3)
  38. # linear_3.weight: [2. 2.]
  39. # linear_3.bias: [2.]
  40. res_3 = linear_3(data_3)
  41. # res_3: [6.]