MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / norm

Function norm

imperative/python/megengine/functional/math.py:901–963  ·  view source on GitHub ↗

r"""Calculates the norm of tensor elements over a given axis. This function is able to return different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ord parameter. Args: inp: input tensor. Should have a numeric dat

(
    inp: Tensor, ord: float = None, axis: int = None, keepdims=False,
)

Source from the content-addressed store, hash-verified

899
900
901def norm(
902 inp: Tensor, ord: float = None, axis: int = None, keepdims=False,
903):
904 r"""Calculates the norm of tensor elements over a given axis.
905
906 This function is able to return different matrix norms,
907 or one of an infinite number of vector norms (described below), depending on the value of the ord parameter.
908
909 Args:
910 inp: input tensor. Should have a numeric data type.
911 ord: Order of the norm (see table under Notes). If not specified, the default is 2.
912 axis: Axis along which to compute vector norms.
913 If axis is an integer, it specifies the axis of inp along which to compute the vector norms.
914 keepdims: If this is set to ``True``,
915 the axes which are normed over are left in the result as dimensions with size one.
916
917 Returns:
918 Norm of the matrix or vector(s).
919
920 .. note::
921
922 Now the following norms can be calculated:
923
924 * inf: norm-:math:`\infty` (maximum of absolute values).
925 * -inf: norm-:math:`-\infty` (minimum of absolute values).
926 * 2: 2-norm (largest singluar value).
927
928 The Frobenius norm is given by to ``sum(abs(x)**ord)**(1./ord)``:
929
930 .. math::
931
932 \|A\|_F=\left[\sum_{i, j} a b s\left(a_{i, j}\right)^2\right]^{1 / 2}
933
934 .. seealso:: :func:`numpy.linalg.norm` / :func:`~.functional.normalize`
935
936 Examples:
937
938 >>> import math
939 >>> x = Tensor([1, 2, 3])
940 >>> F.norm(x, ord=math.inf)
941 Tensor(3, dtype=int32, device=xpux:0)
942 >>> F.norm(x, ord=-math.inf)
943 Tensor(1, dtype=int32, device=xpux:0)
944
945 >>> x = Tensor([[1, 2, 3], [4, 5, 6]])
946 >>> F.norm(x, ord=2, axis=0)
947 Tensor([4.1231 5.3852 6.7082], device=xpux:0)
948 >>> F.norm(x, ord=2, axis=1)
949 Tensor([3.7417 8.775 ], device=xpux:0)
950
951 """
952 if axis is None:
953 if inp.ndim != 1:
954 raise TypeError("axis is required unless input is a vector")
955 if ord is None:
956 ord = 2
957 if ord == 0:
958 return sum(inp != 0, axis=axis, keepdims=keepdims)

Callers 7

normalizeFunction · 0.70
get_cosineFunction · 0.50
clip_grad_normFunction · 0.50
__init__Method · 0.50
__init__Method · 0.50
__init__Method · 0.50
on_var_replacedMethod · 0.50

Calls 4

sumFunction · 0.85
maxFunction · 0.85
absFunction · 0.70
minFunction · 0.70

Tested by

no test coverage detected