Assign

class paddle.nn.initializer. Assign ( value, name=None ) [source]

Init an parameter with a numpy array, list, or tensor.

Parameters
  • value (Tensor|numpy.ndarray|list|tuple) – numpy array, list, tuple, or tensor to initialize the parameter.

  • name (str, optional) – Normally there is no need for user to set this property. For more information, please refer to Name. Default is None.

Returns

A parameter initialized by the input numpy array, list, or tensor.

Examples

>>> import paddle
>>> import numpy as np

>>> # numpy array
>>> data_1 = paddle.ones(shape=[1, 2], dtype='float32')
>>> weight_attr_1 = paddle.ParamAttr(
...     name="linear_weight_1",
...     initializer=paddle.nn.initializer.Assign(np.array([2, 2])))
>>> bias_attr_1 = paddle.ParamAttr(
...     name="linear_bias_1",
...     initializer=paddle.nn.initializer.Assign(np.array([2])))
>>> linear_1 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_1, bias_attr=bias_attr_1)
>>> print(linear_1.weight.numpy())
[2. 2.]
>>> print(linear_1.bias.numpy())
[2.]

>>> res_1 = linear_1(data_1)
>>> print(res_1.numpy())
[6.]

>>> # python list
>>> data_2 = paddle.ones(shape=[1, 2], dtype='float32')
>>> weight_attr_2 = paddle.ParamAttr(
...     name="linear_weight_2",
...     initializer=paddle.nn.initializer.Assign([2, 2]))
>>> bias_attr_2 = paddle.ParamAttr(
...     name="linear_bias_2",
...     initializer=paddle.nn.initializer.Assign([2]))
>>> linear_2 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_2, bias_attr=bias_attr_2)
>>> print(linear_2.weight.numpy())
[2. 2.]
>>> print(linear_2.bias.numpy())
[2.]

>>> res_2 = linear_2(data_2)
>>> print(res_2.numpy())
[6.]

>>> # tensor
>>> data_3 = paddle.ones(shape=[1, 2], dtype='float32')
>>> weight_attr_3 = paddle.ParamAttr(
...     name="linear_weight_3",
...     initializer=paddle.nn.initializer.Assign(paddle.full([2], 2)))
>>> bias_attr_3 = paddle.ParamAttr(
...     name="linear_bias_3",
...     initializer=paddle.nn.initializer.Assign(paddle.full([1], 2)))
>>> linear_3 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_3, bias_attr=bias_attr_3)
>>> print(linear_3.weight.numpy())
[2. 2.]
>>> print(linear_3.bias.numpy())
[2.]

>>> res_3 = linear_3(data_3)
>>> print(res_3.numpy())
[6.]