misc.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. from __future__ import division, print_function, absolute_import
  2. import numpy as np
  3. from numpy.linalg import LinAlgError
  4. from .blas import get_blas_funcs
  5. from .lapack import get_lapack_funcs
  6. __all__ = ['LinAlgError', 'LinAlgWarning', 'norm']
  7. class LinAlgWarning(RuntimeWarning):
  8. """
  9. The warning emitted when a linear algebra related operation is close
  10. to fail conditions of the algorithm or loss of accuracy is expected.
  11. """
  12. pass
  13. def norm(a, ord=None, axis=None, keepdims=False):
  14. """
  15. Matrix or vector norm.
  16. This function is able to return one of seven different matrix norms,
  17. or one of an infinite number of vector norms (described below), depending
  18. on the value of the ``ord`` parameter.
  19. Parameters
  20. ----------
  21. a : (M,) or (M, N) array_like
  22. Input array. If `axis` is None, `a` must be 1-D or 2-D.
  23. ord : {non-zero int, inf, -inf, 'fro'}, optional
  24. Order of the norm (see table under ``Notes``). inf means numpy's
  25. `inf` object
  26. axis : {int, 2-tuple of ints, None}, optional
  27. If `axis` is an integer, it specifies the axis of `a` along which to
  28. compute the vector norms. If `axis` is a 2-tuple, it specifies the
  29. axes that hold 2-D matrices, and the matrix norms of these matrices
  30. are computed. If `axis` is None then either a vector norm (when `a`
  31. is 1-D) or a matrix norm (when `a` is 2-D) is returned.
  32. keepdims : bool, optional
  33. If this is set to True, the axes which are normed over are left in the
  34. result as dimensions with size one. With this option the result will
  35. broadcast correctly against the original `a`.
  36. Returns
  37. -------
  38. n : float or ndarray
  39. Norm of the matrix or vector(s).
  40. Notes
  41. -----
  42. For values of ``ord <= 0``, the result is, strictly speaking, not a
  43. mathematical 'norm', but it may still be useful for various numerical
  44. purposes.
  45. The following norms can be calculated:
  46. ===== ============================ ==========================
  47. ord norm for matrices norm for vectors
  48. ===== ============================ ==========================
  49. None Frobenius norm 2-norm
  50. 'fro' Frobenius norm --
  51. inf max(sum(abs(x), axis=1)) max(abs(x))
  52. -inf min(sum(abs(x), axis=1)) min(abs(x))
  53. 0 -- sum(x != 0)
  54. 1 max(sum(abs(x), axis=0)) as below
  55. -1 min(sum(abs(x), axis=0)) as below
  56. 2 2-norm (largest sing. value) as below
  57. -2 smallest singular value as below
  58. other -- sum(abs(x)**ord)**(1./ord)
  59. ===== ============================ ==========================
  60. The Frobenius norm is given by [1]_:
  61. :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
  62. The ``axis`` and ``keepdims`` arguments are passed directly to
  63. ``numpy.linalg.norm`` and are only usable if they are supported
  64. by the version of numpy in use.
  65. References
  66. ----------
  67. .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
  68. Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
  69. Examples
  70. --------
  71. >>> from scipy.linalg import norm
  72. >>> a = np.arange(9) - 4.0
  73. >>> a
  74. array([-4., -3., -2., -1., 0., 1., 2., 3., 4.])
  75. >>> b = a.reshape((3, 3))
  76. >>> b
  77. array([[-4., -3., -2.],
  78. [-1., 0., 1.],
  79. [ 2., 3., 4.]])
  80. >>> norm(a)
  81. 7.745966692414834
  82. >>> norm(b)
  83. 7.745966692414834
  84. >>> norm(b, 'fro')
  85. 7.745966692414834
  86. >>> norm(a, np.inf)
  87. 4
  88. >>> norm(b, np.inf)
  89. 9
  90. >>> norm(a, -np.inf)
  91. 0
  92. >>> norm(b, -np.inf)
  93. 2
  94. >>> norm(a, 1)
  95. 20
  96. >>> norm(b, 1)
  97. 7
  98. >>> norm(a, -1)
  99. -4.6566128774142013e-010
  100. >>> norm(b, -1)
  101. 6
  102. >>> norm(a, 2)
  103. 7.745966692414834
  104. >>> norm(b, 2)
  105. 7.3484692283495345
  106. >>> norm(a, -2)
  107. 0
  108. >>> norm(b, -2)
  109. 1.8570331885190563e-016
  110. >>> norm(a, 3)
  111. 5.8480354764257312
  112. >>> norm(a, -3)
  113. 0
  114. """
  115. # Differs from numpy only in non-finite handling and the use of blas.
  116. a = np.asarray_chkfinite(a)
  117. # Only use optimized norms if axis and keepdims are not specified.
  118. if a.dtype.char in 'fdFD' and axis is None and not keepdims:
  119. if ord in (None, 2) and (a.ndim == 1):
  120. # use blas for fast and stable euclidean norm
  121. nrm2 = get_blas_funcs('nrm2', dtype=a.dtype)
  122. return nrm2(a)
  123. if a.ndim == 2 and axis is None and not keepdims:
  124. # Use lapack for a couple fast matrix norms.
  125. # For some reason the *lange frobenius norm is slow.
  126. lange_args = None
  127. # Make sure this works if the user uses the axis keywords
  128. # to apply the norm to the transpose.
  129. if ord == 1:
  130. if np.isfortran(a):
  131. lange_args = '1', a
  132. elif np.isfortran(a.T):
  133. lange_args = 'i', a.T
  134. elif ord == np.inf:
  135. if np.isfortran(a):
  136. lange_args = 'i', a
  137. elif np.isfortran(a.T):
  138. lange_args = '1', a.T
  139. if lange_args:
  140. lange = get_lapack_funcs('lange', dtype=a.dtype)
  141. return lange(*lange_args)
  142. # Filter out the axis and keepdims arguments if they aren't used so they
  143. # are never inadvertently passed to a version of numpy that doesn't
  144. # support them.
  145. if axis is not None:
  146. if keepdims:
  147. return np.linalg.norm(a, ord=ord, axis=axis, keepdims=keepdims)
  148. return np.linalg.norm(a, ord=ord, axis=axis)
  149. return np.linalg.norm(a, ord=ord)
  150. def _datacopied(arr, original):
  151. """
  152. Strict check for `arr` not sharing any data with `original`,
  153. under the assumption that arr = asarray(original)
  154. """
  155. if arr is original:
  156. return False
  157. if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
  158. return False
  159. return arr.base is None