linear

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

线性变换 OP。对于每个输入 Tensor \(X\),计算公式为:

\[Out = XW + b\]

其中,\(W\)\(b\) 分别为权重和偏置。

如果权重 \(W\) 是一个形状为 \([in\_features, out\_features]\) 的 2-D Tensor,输入则可以是一个多维 Tensor 形状为 \([batch\_size, *, in\_features]\),其中 \(*\) 表示可以为任意个额外的维度。 linear 接口可以计算输入 Tensor 与权重矩阵 \(W\) 的乘积,生成形状为 \([batch\_size, *, out\_features]\) 的输出 Tensor。 如果偏置 \(bias\) 不是 None,它必须是一个形状为 \([out\_features]\) 的 1-D Tensor,且将会被其加到输出中。

参数

  • x (Tensor) – 输入 Tensor。它的数据类型可以为 bfloat16、 float16、float32 或 float64。

  • weight (Tensor) – 权重 Tensor。它的数据类型可以为 bfloat16、 float16、float32 或 float64。

  • bias (Tensor,可选) – 偏置 Tensor。它的数据类型可以为 bfloat16、 float16、float32 或 float64。如果不为 None,则将会被加到输出中。默认值为 None。

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

返回

Tensor,形状为 \([batch\_size, *, out\_features]\),数据类型与输入 Tensor 相同。

代码示例

>>> 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]])

使用本API的教程文档