MCPcopy Create free account
hub / github.com/numpy/numpy / vector_norm

Function vector_norm

numpy/array_api/linalg.py:421–464  ·  view source on GitHub ↗

Array API compatible wrapper for :py:func:`np.linalg.norm `. See its docstring for more information.

(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2)

Source from the content-addressed store, hash-verified

419# The type for ord should be Optional[Union[int, float, Literal[np.inf,
420# -np.inf]]] but Literal does not support floating-point literals.
421def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array:
422 """
423 Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.
424
425 See its docstring for more information.
426 """
427 # Note: the restriction to floating-point dtypes only is different from
428 # np.linalg.norm.
429 if x.dtype not in _floating_dtypes:
430 raise TypeError('Only floating-point dtypes are allowed in norm')
431
432 # np.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
433 # when axis=None and the input is 2-D, so to force a vector norm, we make
434 # it so the input is 1-D (for axis=None), or reshape so that norm is done
435 # on a single dimension.
436 a = x._array
437 if axis is None:
438 # Note: np.linalg.norm() doesn't handle 0-D arrays
439 a = a.ravel()
440 _axis = 0
441 elif isinstance(axis, tuple):
442 # Note: The axis argument supports any number of axes, whereas
443 # np.linalg.norm() only supports a single axis for vector norm.
444 normalized_axis = normalize_axis_tuple(axis, x.ndim)
445 rest = tuple(i for i in range(a.ndim) if i not in normalized_axis)
446 newshape = axis + rest
447 a = np.transpose(a, newshape).reshape(
448 (np.prod([a.shape[i] for i in axis], dtype=int), *[a.shape[i] for i in rest]))
449 _axis = 0
450 else:
451 _axis = axis
452
453 res = Array._new(np.linalg.norm(a, axis=_axis, ord=ord))
454
455 if keepdims:
456 # We can't reuse np.linalg.norm(keepdims) because of the reshape hacks
457 # above to avoid matrix norm logic.
458 shape = list(x.shape)
459 _axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
460 for i in _axis:
461 shape[i] = 1
462 res = reshape(res, tuple(shape))
463
464 return res
465
466__all__ = ['cholesky', 'cross', 'det', 'diagonal', 'eigh', 'eigvalsh', 'inv', 'matmul', 'matrix_norm', 'matrix_power', 'matrix_rank', 'matrix_transpose', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'svdvals', 'tensordot', 'trace', 'vecdot', 'vector_norm']

Callers

nothing calls this directly

Calls 6

normalize_axis_tupleFunction · 0.85
reshapeMethod · 0.80
_newMethod · 0.80
reshapeFunction · 0.70
ravelMethod · 0.45
prodMethod · 0.45

Tested by

no test coverage detected