linear

paddle.compat.nn.functional. linear ( input: Tensor, weight: Tensor, bias: Tensor | None = None ) Tensor [source]

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

\[Out = xW^T + b\]

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

If the weight is a 2-D tensor of shape \([out\_features, in\_features]\) , input should be a multi-dimensional tensor of shape \([*, in\_features]\) , where \(*\) means any number of additional dimensions. The linear operator multiplies input tensor with weight and produces an output tensor of shape \([*, 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.

This implementation is aligned with PyTorch’s linear function which computes \(y = xW^T + b\).

Parameters
  • input (Tensor) – Input tensor. The data type should be bfloat16, float16, float32 or float64. The input tensor should be of shape \([*, in\_features]\), where \(*\) means any number of additional dimensions, including none

  • weight (Tensor) – Weight tensor. The data type should be float16, float32 or float64. Shape should be [out_features, in_features].

  • 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.

Returns

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

Examples

>>> import paddle

>>> paddle.seed(2025)

>>> x = paddle.arange(6, dtype=paddle.float32).reshape([3, 2])
>>> x
Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
       [[0., 1.],
        [2., 3.],
        [4., 5.]])
>>> weight = paddle.full(shape=[4, 2], fill_value=0.5, dtype="float32", name="weight")
>>> weight
Tensor(shape=[4, 2], 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")
>>> y = paddle.compat.nn.functional.linear(x, weight, bias)
>>> print(y)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
       [[1.50000000, 1.50000000, 1.50000000, 1.50000000],
        [3.50000000, 3.50000000, 3.50000000, 3.50000000],
        [5.50000000, 5.50000000, 5.50000000, 5.50000000]])