norm

paddle. norm ( x, p='fro', axis=None, keepdim=False, name=None ) [source]

Returns the matrix norm (Frobenius) or vector norm (the 1-norm, the Euclidean or 2-norm, and in general the p-norm for p > 0) of a given tensor.

Parameters
  • x (Tensor) – The input tensor could be N-D tensor, and the input data type could be float32 or float64.

  • p (float|string, optional) – Order of the norm. Supported values are fro, 0, 1, 2, inf, -inf and any positive real number yielding the corresponding p-norm. Not supported: ord < 0 and nuclear norm. Default value is fro.

  • axis (int|list|tuple, optional) – The axis on which to apply norm operation. If axis is int or list(int)/tuple(int) with only one element, the vector norm is computed over the axis. If axis < 0, the dimension to norm operation is rank(input) + axis. If axis is a list(int)/tuple(int) with two elements, the matrix norm is computed over the axis. Defalut value is None.

  • keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result tensor will have fewer dimension than the input unless keepdim is true, default value is False.

  • name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to Name.

Returns

results of norm operation on the specified axis of input tensor, it’s data type is the same as input’s Tensor.

Return type

Tensor

Examples

import paddle
import numpy as np
shape=[2, 3, 4]
np_input = np.arange(24).astype('float32') - 12
np_input = np_input.reshape(shape)
x = paddle.to_tensor(np_input)
#[[[-12. -11. -10.  -9.] [ -8.  -7.  -6.  -5.] [ -4.  -3.  -2.  -1.]]
# [[  0.   1.   2.   3.] [  4.   5.   6.   7.] [  8.   9.  10.  11.]]]

# compute frobenius norm along last two dimensions.
out_fro = paddle.norm(x, p='fro', axis=[0,1])
# out_fro.numpy() [17.435596 16.911535 16.7332   16.911535]

# compute 2-order vector norm along last dimension.
out_pnorm = paddle.norm(x, p=2, axis=-1)
#out_pnorm.numpy(): [[21.118711  13.190906   5.477226]
#                    [ 3.7416575 11.224972  19.131126]]

# compute 2-order  norm along [0,1] dimension.
out_pnorm = paddle.norm(x, p=2, axis=[0,1])
#out_pnorm.numpy(): [17.435596 16.911535 16.7332   16.911535]

# compute inf-order  norm
out_pnorm = paddle.norm(x, p=np.inf)
#out_pnorm.numpy()  = [12.]
out_pnorm = paddle.norm(x, p=np.inf, axis=0)
#out_pnorm.numpy(): [[12. 11. 10. 9.] [8. 7. 6. 7.] [8. 9. 10. 11.]]

# compute -inf-order  norm
out_pnorm = paddle.norm(x, p=-np.inf)
#out_pnorm.numpy(): [0.]
out_pnorm = paddle.norm(x, p=-np.inf, axis=0)
#out_pnorm.numpy(): [[0. 1. 2. 3.] [4. 5. 6. 5.] [4. 3. 2. 1.]]