torch.linalg.norm¶
- torch.linalg.norm(A, ord=None, dim=None, keepdim=False, *, out=None, dtype=None) Tensor ¶
计算向量或矩阵的范数。
支持输入浮点型、双精度浮点型、复浮点型和复双精度浮点型数据类型。
该函数计算向量范数还是矩阵范数,如下确定:
如果
dim
是整数,则计算向量范数。如果
dim
是二元组,则计算矩阵范数。如果
dim
为空且ord
为空,则A
将被展平为 1D,并计算得到的向量的 2-范数。如果
dim
为空且ord
不为空,则A
必须是 1D 或 2D。
ord
定义了要计算的范数。以下范数被支持:ord
矩阵范数
向量规范
(默认值)
Frobenius 范数
2-范数(见下文)
‘fro’
Frobenius 范数
– 不支持 –
‘nuc’
核范数
– 不支持 –
无穷
求 max(sum(abs(x), dim=1))
max(绝对值(x))
-无穷大
求 x 的绝对值之和的最小值(按维度 1)
min(绝对值(x))
0
– 不支持 –
sum(x 不等于 0)
1
求 x 的绝对值之和的最大值(按维度 0)
如下所示
-1
求 x 的绝对值之和的最小值(按维度 0)
如下所示
2
最大的奇异值
如下所示
-2
最小的奇异值
如下所示
其他整数或浮点数
– 不支持 –
sum(abs(x)^{ord})^{(1 / ord)}
其中 inf 指的是 float(‘inf’), NumPy 的 inf 对象,或任何等效对象。
参见
torch.linalg.vector_norm()
计算向量范数。torch.linalg.matrix_norm()
计算矩阵范数。上述函数通常比使用
torch.linalg.norm()
更清晰、更灵活。例如,torch.linalg.norm(A, ord=1, dim=(0, 1)) 总是计算矩阵范数,但使用 torch.linalg.vector_norm(A, ord=1, dim=(0, 1)) 可以在两个维度上计算向量范数。- 参数:
A (张量) – 形状为 (*, n) 或 (*, m, n) 的张量,其中 * 表示零个或多个批处理维度
ord (int, float, inf, -inf, 'fro', 'nuc', 可选) – 范数的阶。默认:None
dim (int, Tuple[int], 可选) – 计算向量或矩阵范数的维度。见上文关于
dim
= None 时的行为。默认:Nonekeepdim (bool, 可选) – 如果设置为 True,则减少的维度在结果中保留为大小为一的维度。默认:False
- 关键字参数:
out(张量,可选)- 输出张量。如果为 None 则忽略。默认:None。
dtype (
torch.dtype
,可选) – 如果指定,则在执行操作之前将输入张量转换为dtype
,返回的张量类型将为dtype
。默认:None
- 返回值:
实值张量,即使
A
是复数。
示例:
>>> from torch import linalg as LA >>> a = torch.arange(9, dtype=torch.float) - 4 >>> a tensor([-4., -3., -2., -1., 0., 1., 2., 3., 4.]) >>> B = a.reshape((3, 3)) >>> B tensor([[-4., -3., -2.], [-1., 0., 1.], [ 2., 3., 4.]]) >>> LA.norm(a) tensor(7.7460) >>> LA.norm(B) tensor(7.7460) >>> LA.norm(B, 'fro') tensor(7.7460) >>> LA.norm(a, float('inf')) tensor(4.) >>> LA.norm(B, float('inf')) tensor(9.) >>> LA.norm(a, -float('inf')) tensor(0.) >>> LA.norm(B, -float('inf')) tensor(2.) >>> LA.norm(a, 1) tensor(20.) >>> LA.norm(B, 1) tensor(7.) >>> LA.norm(a, -1) tensor(0.) >>> LA.norm(B, -1) tensor(6.) >>> LA.norm(a, 2) tensor(7.7460) >>> LA.norm(B, 2) tensor(7.3485) >>> LA.norm(a, -2) tensor(0.) >>> LA.norm(B.double(), -2) tensor(1.8570e-16, dtype=torch.float64) >>> LA.norm(a, 3) tensor(5.8480) >>> LA.norm(a, -3) tensor(0.)
使用
dim
参数来计算向量范数:>>> c = torch.tensor([[1., 2., 3.], ... [-1, 1, 4]]) >>> LA.norm(c, dim=0) tensor([1.4142, 2.2361, 5.0000]) >>> LA.norm(c, dim=1) tensor([3.7417, 4.2426]) >>> LA.norm(c, ord=1, dim=1) tensor([6., 6.])
使用
dim
参数来计算矩阵范数:>>> A = torch.arange(8, dtype=torch.float).reshape(2, 2, 2) >>> LA.norm(A, dim=(1,2)) tensor([ 3.7417, 11.2250]) >>> LA.norm(A[0, :, :]), LA.norm(A[1, :, :]) (tensor(3.7417), tensor(11.2250))