1.torch.norm的参数

def norm(input, p="fro", dim=None, keepdim=False, out=None, dtype=None):

根据python源码,可以看出torch.norm的参数有主要如下参数:

  1. input:输入tensor类型的数据
  2. p:指定的范数。

    ①:默认为p=‘fro’,计算矩阵的FFrobenius norm (Frobenius 范数),就是矩阵A各项元素的绝对值平方的总和,数学表达式为:

    ②:p='nuc’时,是求核范数,核范数是矩阵奇异值的和。(不常用)
    ③:常用的是第三种,p为int的形式,则是如下形式:
  3. dim:指定在哪个维度进行,如果不指定,则是在所有维度进行计算。
dim (int, tuple of ints, list of ints, optional):
    Specifies which dimension or dimensions of :attr:`input` to
    calculate the norm across. If :attr:`dim` is ``None``, the norm will
    be calculated across all dimensions of :attr:`input`. If the norm
    type indicated by :attr:`p` does not support the specified number of
    dimensions, an error will occur.
  1. keepdim:True or False,如果True,则保留dim指定的维度,False则不保留。
  2. out:输出的tensor,文档没说具体含义,暂时不知。
out (Tensor, optional): the output tensor. Ignored if
    :attr:`dim` = ``None`` and :attr:`out` = ``None``.
  1. dtype:指定输出的tensor的数据类型。

2.示例

代码如下:

import torch
t = torch.ones(64, 3, 3, 3)
t_norm = t.norm(1, 3)
print(t_norm)

指定p=1,dim=3。也就是在t的第3个维度(从0开始)进行1范数计算。
调试一下可以发现:t_norm的shape为(64,3,3),而且每一个元素都是为3.
足以验证第1节的说法。

来源:little student

物联沃分享整理
物联沃-IOTWORD物联网 » 详细的torch.norm的用法

发表评论