Linear

class paddle.compat.nn. Linear ( in_features, out_features, bias, device=None, dtype=None ) [源代码]

PyTorch 兼容的 Linear 版本:

  • 与 PyTorch 一致的数学意义:

\[Out = XW^T + b\]

其中 \(W\) 是权重张量, \(b\) 是偏置张量, \(X\) 是输入张量

  • 与 PyTorch 一致的默认可视化方法: Kaiming normal 用于权重初始化,平均分布用于偏置初始化

  • 支持设定 Linear 的数据类型以及运行设备

使用前请详细参考:【仅参数名不一致】torch.nn.Linear 以确定是否使用此模块。

参数

  • in_features (int) - 输入单元数。

  • out_features (int) - 输出单元数。

  • bias (bool, 可选) - 如果为 True,将创建偏置(一个形状为 \([out\_features]\) 的一维张量)并添加到输出。默认值 True。

  • device (PlaceLike, 可选) - 创建参数所在的设备。默认值为 None,表示默认 Paddle 设备。

  • dtype (DTypeLike, 可选) - 创建参数的数据类型。默认值为 None,并设置为 Linear 的默认数据类型(float32)。

形状

  • 输入 : 多维张量,形状为 \([*, in\_features]\) 。数据类型为 float16、float32、float64,默认为 float32。

  • 输出 : 多维张量,形状为 \([*, out\_features]\) 。数据类型与输入相同。

代码示例

>>> import paddle
>>> paddle.seed(100)

>>> # Define the linear layer.
>>> linear = paddle.compat.nn.Linear(2, 4, bias=True)
>>> print(linear.weight)
Parameter containing:
Tensor(shape=[4, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
       [[-0.49191639,  0.28120756],
        [-0.17887023,  0.40572405],
        [ 0.35139430,  0.45717543],
        [-0.06135514, -0.21088189]])

>>> print(linear.bias)
Parameter containing:
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=False,
       [ 0.49166456, -0.06108528, -0.14973064,  0.31168410])

>>> x = paddle.arange(6, dtype="float32").reshape([3, 2])
>>> y = linear(x)
>>> print(y)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=False,
       [[ 0.77287209,  0.34463876,  0.30744481,  0.10080221],
        [ 0.35145447,  0.79834640,  1.92458415, -0.44367185],
        [-0.06996319,  1.25205410,  3.54172373, -0.98814595]])