linear
PyTorch 兼容的线性函数版本:
与 PyTorch 一致的数学意义:
\[Out = X W^T + b\]其中 \(W\) 是权重张量
weight, \(b\) 是偏置张量bias, \(X\) 是输入张量input
此实现与 PyTorch 的线性函数对齐,计算 \(y = XW^T + b\)。
参数
input (Tensor) - 输入张量。数据类型应为 bfloat16、float16、float32 或 float64。输入张量的形状应为 \([*, in\_features]\),其中 \(*\) 表示任意数量的额外维度,包括无。
weight (Tensor) - 权重张量。数据类型应为 float16、float32 或 float64。形状应为 \([out\_features, in\_features]\)。
bias (Tensor, 可选) - 偏置张量。数据类型应为 float16、float32 或 float64。如果为 None,则不添加偏置到输出单元。默认值 None。
形状
输入 : 多维张量,形状为 \([*, in\_features]\) 。数据类型为 bfloat16、float16、float32 或 float64。
输出 : 多维张量,形状为 \([*, out\_features]\) 。数据类型与输入相同。
代码示例
>>> 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]])