linear

paddle.nn.functional. linear ( x, weight, bias=None, name=None ) [source]

Fully-connected linear transformation operator. For each input \(X\) , the equation is:

\[Out = XW + b\]

where \(W\) is the weight and \(b\) is the bias.

If the weight is a 2-D tensor of shape \([in\_features, out\_features]\) , input should be a multi-dimensional tensor of shape \([batch\_size, *, in\_features]\) , where \(*\) means any number of additional dimensions. The linear operator multiplies input tensor with weight and produces an output tensor of shape \([batch\_size, *, out\_features]\) , If \(bias\) is not None, the bias should be a 1-D tensor of shape \([out\_features]\) and will be added to the output.

Parameters
  • x (Tensor) – Input tensor. The data type should be bfloat16, float16, float32 or float64.

  • weight (Tensor) – Weight tensor. The data type should be float16, float32 or float64.

  • bias (Tensor, optional) – Bias tensor. The data type should be float16, float32 or float64. If it is set to None, no bias will be added to the output units.

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

Returns

Tensor, the shape is \([batch\_size, *, out\_features]\) and the data type is the same with input \(x\) .

Examples

>>> import paddle
>>> paddle.seed(2023)
>>> x = paddle.randn((3, 2), dtype="float32")
>>> print(x)
Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 0.06132207,  1.11349595],
 [ 0.41906244, -0.24858207],
 [-1.85169315, -1.50370061]])
>>> weight = paddle.full(shape=[2, 4], fill_value="0.5", dtype="float32", name="weight")
>>> print(weight)
Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.50000000, 0.50000000, 0.50000000, 0.50000000],
 [0.50000000, 0.50000000, 0.50000000, 0.50000000]])
>>> bias = paddle.ones(shape=[4], dtype="float32", name="bias")
>>> print(bias)
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[1., 1., 1., 1.])
>>> y = paddle.nn.functional.linear(x, weight, bias)
>>> print(y)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 1.58740902,  1.58740902,  1.58740902,  1.58740902],
 [ 1.08524013,  1.08524013,  1.08524013,  1.08524013],
 [-0.67769694, -0.67769694, -0.67769694, -0.67769694]])