linalg.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746
  1. """Lite version of scipy.linalg.
  2. Notes
  3. -----
  4. This module is a lite version of the linalg.py module in SciPy which
  5. contains high-level Python interface to the LAPACK library. The lite
  6. version only accesses the following LAPACK functions: dgesv, zgesv,
  7. dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
  8. zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
  9. """
  10. from __future__ import division, absolute_import, print_function
  11. __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
  12. 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det',
  13. 'svd', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', 'matrix_rank',
  14. 'LinAlgError', 'multi_dot']
  15. import functools
  16. import operator
  17. import warnings
  18. from numpy.core import (
  19. array, asarray, zeros, empty, empty_like, intc, single, double,
  20. csingle, cdouble, inexact, complexfloating, newaxis, all, Inf, dot,
  21. add, multiply, sqrt, fastCopyAndTranspose, sum, isfinite,
  22. finfo, errstate, geterrobj, moveaxis, amin, amax, product, abs,
  23. atleast_2d, intp, asanyarray, object_, matmul,
  24. swapaxes, divide, count_nonzero, isnan, sign
  25. )
  26. from numpy.core.multiarray import normalize_axis_index
  27. from numpy.core.overrides import set_module
  28. from numpy.core import overrides
  29. from numpy.lib.twodim_base import triu, eye
  30. from numpy.linalg import lapack_lite, _umath_linalg
  31. array_function_dispatch = functools.partial(
  32. overrides.array_function_dispatch, module='numpy.linalg')
  33. # For Python2/3 compatibility
  34. _N = b'N'
  35. _V = b'V'
  36. _A = b'A'
  37. _S = b'S'
  38. _L = b'L'
  39. fortran_int = intc
  40. @set_module('numpy.linalg')
  41. class LinAlgError(Exception):
  42. """
  43. Generic Python-exception-derived object raised by linalg functions.
  44. General purpose exception class, derived from Python's exception.Exception
  45. class, programmatically raised in linalg functions when a Linear
  46. Algebra-related condition would prevent further correct execution of the
  47. function.
  48. Parameters
  49. ----------
  50. None
  51. Examples
  52. --------
  53. >>> from numpy import linalg as LA
  54. >>> LA.inv(np.zeros((2,2)))
  55. Traceback (most recent call last):
  56. File "<stdin>", line 1, in <module>
  57. File "...linalg.py", line 350,
  58. in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
  59. File "...linalg.py", line 249,
  60. in solve
  61. raise LinAlgError('Singular matrix')
  62. numpy.linalg.LinAlgError: Singular matrix
  63. """
  64. def _determine_error_states():
  65. errobj = geterrobj()
  66. bufsize = errobj[0]
  67. with errstate(invalid='call', over='ignore',
  68. divide='ignore', under='ignore'):
  69. invalid_call_errmask = geterrobj()[1]
  70. return [bufsize, invalid_call_errmask, None]
  71. # Dealing with errors in _umath_linalg
  72. _linalg_error_extobj = _determine_error_states()
  73. del _determine_error_states
  74. def _raise_linalgerror_singular(err, flag):
  75. raise LinAlgError("Singular matrix")
  76. def _raise_linalgerror_nonposdef(err, flag):
  77. raise LinAlgError("Matrix is not positive definite")
  78. def _raise_linalgerror_eigenvalues_nonconvergence(err, flag):
  79. raise LinAlgError("Eigenvalues did not converge")
  80. def _raise_linalgerror_svd_nonconvergence(err, flag):
  81. raise LinAlgError("SVD did not converge")
  82. def _raise_linalgerror_lstsq(err, flag):
  83. raise LinAlgError("SVD did not converge in Linear Least Squares")
  84. def get_linalg_error_extobj(callback):
  85. extobj = list(_linalg_error_extobj) # make a copy
  86. extobj[2] = callback
  87. return extobj
  88. def _makearray(a):
  89. new = asarray(a)
  90. wrap = getattr(a, "__array_prepare__", new.__array_wrap__)
  91. return new, wrap
  92. def isComplexType(t):
  93. return issubclass(t, complexfloating)
  94. _real_types_map = {single : single,
  95. double : double,
  96. csingle : single,
  97. cdouble : double}
  98. _complex_types_map = {single : csingle,
  99. double : cdouble,
  100. csingle : csingle,
  101. cdouble : cdouble}
  102. def _realType(t, default=double):
  103. return _real_types_map.get(t, default)
  104. def _complexType(t, default=cdouble):
  105. return _complex_types_map.get(t, default)
  106. def _linalgRealType(t):
  107. """Cast the type t to either double or cdouble."""
  108. return double
  109. def _commonType(*arrays):
  110. # in lite version, use higher precision (always double or cdouble)
  111. result_type = single
  112. is_complex = False
  113. for a in arrays:
  114. if issubclass(a.dtype.type, inexact):
  115. if isComplexType(a.dtype.type):
  116. is_complex = True
  117. rt = _realType(a.dtype.type, default=None)
  118. if rt is None:
  119. # unsupported inexact scalar
  120. raise TypeError("array type %s is unsupported in linalg" %
  121. (a.dtype.name,))
  122. else:
  123. rt = double
  124. if rt is double:
  125. result_type = double
  126. if is_complex:
  127. t = cdouble
  128. result_type = _complex_types_map[result_type]
  129. else:
  130. t = double
  131. return t, result_type
  132. # _fastCopyAndTranpose assumes the input is 2D (as all the calls in here are).
  133. _fastCT = fastCopyAndTranspose
  134. def _to_native_byte_order(*arrays):
  135. ret = []
  136. for arr in arrays:
  137. if arr.dtype.byteorder not in ('=', '|'):
  138. ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('=')))
  139. else:
  140. ret.append(arr)
  141. if len(ret) == 1:
  142. return ret[0]
  143. else:
  144. return ret
  145. def _fastCopyAndTranspose(type, *arrays):
  146. cast_arrays = ()
  147. for a in arrays:
  148. if a.dtype.type is type:
  149. cast_arrays = cast_arrays + (_fastCT(a),)
  150. else:
  151. cast_arrays = cast_arrays + (_fastCT(a.astype(type)),)
  152. if len(cast_arrays) == 1:
  153. return cast_arrays[0]
  154. else:
  155. return cast_arrays
  156. def _assert_2d(*arrays):
  157. for a in arrays:
  158. if a.ndim != 2:
  159. raise LinAlgError('%d-dimensional array given. Array must be '
  160. 'two-dimensional' % a.ndim)
  161. def _assert_stacked_2d(*arrays):
  162. for a in arrays:
  163. if a.ndim < 2:
  164. raise LinAlgError('%d-dimensional array given. Array must be '
  165. 'at least two-dimensional' % a.ndim)
  166. def _assert_stacked_square(*arrays):
  167. for a in arrays:
  168. m, n = a.shape[-2:]
  169. if m != n:
  170. raise LinAlgError('Last 2 dimensions of the array must be square')
  171. def _assert_finite(*arrays):
  172. for a in arrays:
  173. if not isfinite(a).all():
  174. raise LinAlgError("Array must not contain infs or NaNs")
  175. def _is_empty_2d(arr):
  176. # check size first for efficiency
  177. return arr.size == 0 and product(arr.shape[-2:]) == 0
  178. def transpose(a):
  179. """
  180. Transpose each matrix in a stack of matrices.
  181. Unlike np.transpose, this only swaps the last two axes, rather than all of
  182. them
  183. Parameters
  184. ----------
  185. a : (...,M,N) array_like
  186. Returns
  187. -------
  188. aT : (...,N,M) ndarray
  189. """
  190. return swapaxes(a, -1, -2)
  191. # Linear equations
  192. def _tensorsolve_dispatcher(a, b, axes=None):
  193. return (a, b)
  194. @array_function_dispatch(_tensorsolve_dispatcher)
  195. def tensorsolve(a, b, axes=None):
  196. """
  197. Solve the tensor equation ``a x = b`` for x.
  198. It is assumed that all indices of `x` are summed over in the product,
  199. together with the rightmost indices of `a`, as is done in, for example,
  200. ``tensordot(a, x, axes=b.ndim)``.
  201. Parameters
  202. ----------
  203. a : array_like
  204. Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
  205. the shape of that sub-tensor of `a` consisting of the appropriate
  206. number of its rightmost indices, and must be such that
  207. ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
  208. 'square').
  209. b : array_like
  210. Right-hand tensor, which can be of any shape.
  211. axes : tuple of ints, optional
  212. Axes in `a` to reorder to the right, before inversion.
  213. If None (default), no reordering is done.
  214. Returns
  215. -------
  216. x : ndarray, shape Q
  217. Raises
  218. ------
  219. LinAlgError
  220. If `a` is singular or not 'square' (in the above sense).
  221. See Also
  222. --------
  223. numpy.tensordot, tensorinv, numpy.einsum
  224. Examples
  225. --------
  226. >>> a = np.eye(2*3*4)
  227. >>> a.shape = (2*3, 4, 2, 3, 4)
  228. >>> b = np.random.randn(2*3, 4)
  229. >>> x = np.linalg.tensorsolve(a, b)
  230. >>> x.shape
  231. (2, 3, 4)
  232. >>> np.allclose(np.tensordot(a, x, axes=3), b)
  233. True
  234. """
  235. a, wrap = _makearray(a)
  236. b = asarray(b)
  237. an = a.ndim
  238. if axes is not None:
  239. allaxes = list(range(0, an))
  240. for k in axes:
  241. allaxes.remove(k)
  242. allaxes.insert(an, k)
  243. a = a.transpose(allaxes)
  244. oldshape = a.shape[-(an-b.ndim):]
  245. prod = 1
  246. for k in oldshape:
  247. prod *= k
  248. a = a.reshape(-1, prod)
  249. b = b.ravel()
  250. res = wrap(solve(a, b))
  251. res.shape = oldshape
  252. return res
  253. def _solve_dispatcher(a, b):
  254. return (a, b)
  255. @array_function_dispatch(_solve_dispatcher)
  256. def solve(a, b):
  257. """
  258. Solve a linear matrix equation, or system of linear scalar equations.
  259. Computes the "exact" solution, `x`, of the well-determined, i.e., full
  260. rank, linear matrix equation `ax = b`.
  261. Parameters
  262. ----------
  263. a : (..., M, M) array_like
  264. Coefficient matrix.
  265. b : {(..., M,), (..., M, K)}, array_like
  266. Ordinate or "dependent variable" values.
  267. Returns
  268. -------
  269. x : {(..., M,), (..., M, K)} ndarray
  270. Solution to the system a x = b. Returned shape is identical to `b`.
  271. Raises
  272. ------
  273. LinAlgError
  274. If `a` is singular or not square.
  275. Notes
  276. -----
  277. .. versionadded:: 1.8.0
  278. Broadcasting rules apply, see the `numpy.linalg` documentation for
  279. details.
  280. The solutions are computed using LAPACK routine ``_gesv``.
  281. `a` must be square and of full-rank, i.e., all rows (or, equivalently,
  282. columns) must be linearly independent; if either is not true, use
  283. `lstsq` for the least-squares best "solution" of the
  284. system/equation.
  285. References
  286. ----------
  287. .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
  288. FL, Academic Press, Inc., 1980, pg. 22.
  289. Examples
  290. --------
  291. Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``:
  292. >>> a = np.array([[3,1], [1,2]])
  293. >>> b = np.array([9,8])
  294. >>> x = np.linalg.solve(a, b)
  295. >>> x
  296. array([2., 3.])
  297. Check that the solution is correct:
  298. >>> np.allclose(np.dot(a, x), b)
  299. True
  300. """
  301. a, _ = _makearray(a)
  302. _assert_stacked_2d(a)
  303. _assert_stacked_square(a)
  304. b, wrap = _makearray(b)
  305. t, result_t = _commonType(a, b)
  306. # We use the b = (..., M,) logic, only if the number of extra dimensions
  307. # match exactly
  308. if b.ndim == a.ndim - 1:
  309. gufunc = _umath_linalg.solve1
  310. else:
  311. gufunc = _umath_linalg.solve
  312. signature = 'DD->D' if isComplexType(t) else 'dd->d'
  313. extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
  314. r = gufunc(a, b, signature=signature, extobj=extobj)
  315. return wrap(r.astype(result_t, copy=False))
  316. def _tensorinv_dispatcher(a, ind=None):
  317. return (a,)
  318. @array_function_dispatch(_tensorinv_dispatcher)
  319. def tensorinv(a, ind=2):
  320. """
  321. Compute the 'inverse' of an N-dimensional array.
  322. The result is an inverse for `a` relative to the tensordot operation
  323. ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
  324. ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
  325. tensordot operation.
  326. Parameters
  327. ----------
  328. a : array_like
  329. Tensor to 'invert'. Its shape must be 'square', i. e.,
  330. ``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
  331. ind : int, optional
  332. Number of first indices that are involved in the inverse sum.
  333. Must be a positive integer, default is 2.
  334. Returns
  335. -------
  336. b : ndarray
  337. `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``.
  338. Raises
  339. ------
  340. LinAlgError
  341. If `a` is singular or not 'square' (in the above sense).
  342. See Also
  343. --------
  344. numpy.tensordot, tensorsolve
  345. Examples
  346. --------
  347. >>> a = np.eye(4*6)
  348. >>> a.shape = (4, 6, 8, 3)
  349. >>> ainv = np.linalg.tensorinv(a, ind=2)
  350. >>> ainv.shape
  351. (8, 3, 4, 6)
  352. >>> b = np.random.randn(4, 6)
  353. >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
  354. True
  355. >>> a = np.eye(4*6)
  356. >>> a.shape = (24, 8, 3)
  357. >>> ainv = np.linalg.tensorinv(a, ind=1)
  358. >>> ainv.shape
  359. (8, 3, 24)
  360. >>> b = np.random.randn(24)
  361. >>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
  362. True
  363. """
  364. a = asarray(a)
  365. oldshape = a.shape
  366. prod = 1
  367. if ind > 0:
  368. invshape = oldshape[ind:] + oldshape[:ind]
  369. for k in oldshape[ind:]:
  370. prod *= k
  371. else:
  372. raise ValueError("Invalid ind argument.")
  373. a = a.reshape(prod, -1)
  374. ia = inv(a)
  375. return ia.reshape(*invshape)
  376. # Matrix inversion
  377. def _unary_dispatcher(a):
  378. return (a,)
  379. @array_function_dispatch(_unary_dispatcher)
  380. def inv(a):
  381. """
  382. Compute the (multiplicative) inverse of a matrix.
  383. Given a square matrix `a`, return the matrix `ainv` satisfying
  384. ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
  385. Parameters
  386. ----------
  387. a : (..., M, M) array_like
  388. Matrix to be inverted.
  389. Returns
  390. -------
  391. ainv : (..., M, M) ndarray or matrix
  392. (Multiplicative) inverse of the matrix `a`.
  393. Raises
  394. ------
  395. LinAlgError
  396. If `a` is not square or inversion fails.
  397. Notes
  398. -----
  399. .. versionadded:: 1.8.0
  400. Broadcasting rules apply, see the `numpy.linalg` documentation for
  401. details.
  402. Examples
  403. --------
  404. >>> from numpy.linalg import inv
  405. >>> a = np.array([[1., 2.], [3., 4.]])
  406. >>> ainv = inv(a)
  407. >>> np.allclose(np.dot(a, ainv), np.eye(2))
  408. True
  409. >>> np.allclose(np.dot(ainv, a), np.eye(2))
  410. True
  411. If a is a matrix object, then the return value is a matrix as well:
  412. >>> ainv = inv(np.matrix(a))
  413. >>> ainv
  414. matrix([[-2. , 1. ],
  415. [ 1.5, -0.5]])
  416. Inverses of several matrices can be computed at once:
  417. >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
  418. >>> inv(a)
  419. array([[[-2. , 1. ],
  420. [ 1.5 , -0.5 ]],
  421. [[-1.25, 0.75],
  422. [ 0.75, -0.25]]])
  423. """
  424. a, wrap = _makearray(a)
  425. _assert_stacked_2d(a)
  426. _assert_stacked_square(a)
  427. t, result_t = _commonType(a)
  428. signature = 'D->D' if isComplexType(t) else 'd->d'
  429. extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
  430. ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
  431. return wrap(ainv.astype(result_t, copy=False))
  432. def _matrix_power_dispatcher(a, n):
  433. return (a,)
  434. @array_function_dispatch(_matrix_power_dispatcher)
  435. def matrix_power(a, n):
  436. """
  437. Raise a square matrix to the (integer) power `n`.
  438. For positive integers `n`, the power is computed by repeated matrix
  439. squarings and matrix multiplications. If ``n == 0``, the identity matrix
  440. of the same shape as M is returned. If ``n < 0``, the inverse
  441. is computed and then raised to the ``abs(n)``.
  442. .. note:: Stacks of object matrices are not currently supported.
  443. Parameters
  444. ----------
  445. a : (..., M, M) array_like
  446. Matrix to be "powered".
  447. n : int
  448. The exponent can be any integer or long integer, positive,
  449. negative, or zero.
  450. Returns
  451. -------
  452. a**n : (..., M, M) ndarray or matrix object
  453. The return value is the same shape and type as `M`;
  454. if the exponent is positive or zero then the type of the
  455. elements is the same as those of `M`. If the exponent is
  456. negative the elements are floating-point.
  457. Raises
  458. ------
  459. LinAlgError
  460. For matrices that are not square or that (for negative powers) cannot
  461. be inverted numerically.
  462. Examples
  463. --------
  464. >>> from numpy.linalg import matrix_power
  465. >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
  466. >>> matrix_power(i, 3) # should = -i
  467. array([[ 0, -1],
  468. [ 1, 0]])
  469. >>> matrix_power(i, 0)
  470. array([[1, 0],
  471. [0, 1]])
  472. >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
  473. array([[ 0., 1.],
  474. [-1., 0.]])
  475. Somewhat more sophisticated example
  476. >>> q = np.zeros((4, 4))
  477. >>> q[0:2, 0:2] = -i
  478. >>> q[2:4, 2:4] = i
  479. >>> q # one of the three quaternion units not equal to 1
  480. array([[ 0., -1., 0., 0.],
  481. [ 1., 0., 0., 0.],
  482. [ 0., 0., 0., 1.],
  483. [ 0., 0., -1., 0.]])
  484. >>> matrix_power(q, 2) # = -np.eye(4)
  485. array([[-1., 0., 0., 0.],
  486. [ 0., -1., 0., 0.],
  487. [ 0., 0., -1., 0.],
  488. [ 0., 0., 0., -1.]])
  489. """
  490. a = asanyarray(a)
  491. _assert_stacked_2d(a)
  492. _assert_stacked_square(a)
  493. try:
  494. n = operator.index(n)
  495. except TypeError:
  496. raise TypeError("exponent must be an integer")
  497. # Fall back on dot for object arrays. Object arrays are not supported by
  498. # the current implementation of matmul using einsum
  499. if a.dtype != object:
  500. fmatmul = matmul
  501. elif a.ndim == 2:
  502. fmatmul = dot
  503. else:
  504. raise NotImplementedError(
  505. "matrix_power not supported for stacks of object arrays")
  506. if n == 0:
  507. a = empty_like(a)
  508. a[...] = eye(a.shape[-2], dtype=a.dtype)
  509. return a
  510. elif n < 0:
  511. a = inv(a)
  512. n = abs(n)
  513. # short-cuts.
  514. if n == 1:
  515. return a
  516. elif n == 2:
  517. return fmatmul(a, a)
  518. elif n == 3:
  519. return fmatmul(fmatmul(a, a), a)
  520. # Use binary decomposition to reduce the number of matrix multiplications.
  521. # Here, we iterate over the bits of n, from LSB to MSB, raise `a` to
  522. # increasing powers of 2, and multiply into the result as needed.
  523. z = result = None
  524. while n > 0:
  525. z = a if z is None else fmatmul(z, z)
  526. n, bit = divmod(n, 2)
  527. if bit:
  528. result = z if result is None else fmatmul(result, z)
  529. return result
  530. # Cholesky decomposition
  531. @array_function_dispatch(_unary_dispatcher)
  532. def cholesky(a):
  533. """
  534. Cholesky decomposition.
  535. Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`,
  536. where `L` is lower-triangular and .H is the conjugate transpose operator
  537. (which is the ordinary transpose if `a` is real-valued). `a` must be
  538. Hermitian (symmetric if real-valued) and positive-definite. Only `L` is
  539. actually returned.
  540. Parameters
  541. ----------
  542. a : (..., M, M) array_like
  543. Hermitian (symmetric if all elements are real), positive-definite
  544. input matrix.
  545. Returns
  546. -------
  547. L : (..., M, M) array_like
  548. Upper or lower-triangular Cholesky factor of `a`. Returns a
  549. matrix object if `a` is a matrix object.
  550. Raises
  551. ------
  552. LinAlgError
  553. If the decomposition fails, for example, if `a` is not
  554. positive-definite.
  555. Notes
  556. -----
  557. .. versionadded:: 1.8.0
  558. Broadcasting rules apply, see the `numpy.linalg` documentation for
  559. details.
  560. The Cholesky decomposition is often used as a fast way of solving
  561. .. math:: A \\mathbf{x} = \\mathbf{b}
  562. (when `A` is both Hermitian/symmetric and positive-definite).
  563. First, we solve for :math:`\\mathbf{y}` in
  564. .. math:: L \\mathbf{y} = \\mathbf{b},
  565. and then for :math:`\\mathbf{x}` in
  566. .. math:: L.H \\mathbf{x} = \\mathbf{y}.
  567. Examples
  568. --------
  569. >>> A = np.array([[1,-2j],[2j,5]])
  570. >>> A
  571. array([[ 1.+0.j, -0.-2.j],
  572. [ 0.+2.j, 5.+0.j]])
  573. >>> L = np.linalg.cholesky(A)
  574. >>> L
  575. array([[1.+0.j, 0.+0.j],
  576. [0.+2.j, 1.+0.j]])
  577. >>> np.dot(L, L.T.conj()) # verify that L * L.H = A
  578. array([[1.+0.j, 0.-2.j],
  579. [0.+2.j, 5.+0.j]])
  580. >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
  581. >>> np.linalg.cholesky(A) # an ndarray object is returned
  582. array([[1.+0.j, 0.+0.j],
  583. [0.+2.j, 1.+0.j]])
  584. >>> # But a matrix object is returned if A is a matrix object
  585. >>> np.linalg.cholesky(np.matrix(A))
  586. matrix([[ 1.+0.j, 0.+0.j],
  587. [ 0.+2.j, 1.+0.j]])
  588. """
  589. extobj = get_linalg_error_extobj(_raise_linalgerror_nonposdef)
  590. gufunc = _umath_linalg.cholesky_lo
  591. a, wrap = _makearray(a)
  592. _assert_stacked_2d(a)
  593. _assert_stacked_square(a)
  594. t, result_t = _commonType(a)
  595. signature = 'D->D' if isComplexType(t) else 'd->d'
  596. r = gufunc(a, signature=signature, extobj=extobj)
  597. return wrap(r.astype(result_t, copy=False))
  598. # QR decompostion
  599. def _qr_dispatcher(a, mode=None):
  600. return (a,)
  601. @array_function_dispatch(_qr_dispatcher)
  602. def qr(a, mode='reduced'):
  603. """
  604. Compute the qr factorization of a matrix.
  605. Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is
  606. upper-triangular.
  607. Parameters
  608. ----------
  609. a : array_like, shape (M, N)
  610. Matrix to be factored.
  611. mode : {'reduced', 'complete', 'r', 'raw'}, optional
  612. If K = min(M, N), then
  613. * 'reduced' : returns q, r with dimensions (M, K), (K, N) (default)
  614. * 'complete' : returns q, r with dimensions (M, M), (M, N)
  615. * 'r' : returns r only with dimensions (K, N)
  616. * 'raw' : returns h, tau with dimensions (N, M), (K,)
  617. The options 'reduced', 'complete, and 'raw' are new in numpy 1.8,
  618. see the notes for more information. The default is 'reduced', and to
  619. maintain backward compatibility with earlier versions of numpy both
  620. it and the old default 'full' can be omitted. Note that array h
  621. returned in 'raw' mode is transposed for calling Fortran. The
  622. 'economic' mode is deprecated. The modes 'full' and 'economic' may
  623. be passed using only the first letter for backwards compatibility,
  624. but all others must be spelled out. See the Notes for more
  625. explanation.
  626. Returns
  627. -------
  628. q : ndarray of float or complex, optional
  629. A matrix with orthonormal columns. When mode = 'complete' the
  630. result is an orthogonal/unitary matrix depending on whether or not
  631. a is real/complex. The determinant may be either +/- 1 in that
  632. case.
  633. r : ndarray of float or complex, optional
  634. The upper-triangular matrix.
  635. (h, tau) : ndarrays of np.double or np.cdouble, optional
  636. The array h contains the Householder reflectors that generate q
  637. along with r. The tau array contains scaling factors for the
  638. reflectors. In the deprecated 'economic' mode only h is returned.
  639. Raises
  640. ------
  641. LinAlgError
  642. If factoring fails.
  643. Notes
  644. -----
  645. This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``,
  646. ``dorgqr``, and ``zungqr``.
  647. For more information on the qr factorization, see for example:
  648. https://en.wikipedia.org/wiki/QR_factorization
  649. Subclasses of `ndarray` are preserved except for the 'raw' mode. So if
  650. `a` is of type `matrix`, all the return values will be matrices too.
  651. New 'reduced', 'complete', and 'raw' options for mode were added in
  652. NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'. In
  653. addition the options 'full' and 'economic' were deprecated. Because
  654. 'full' was the previous default and 'reduced' is the new default,
  655. backward compatibility can be maintained by letting `mode` default.
  656. The 'raw' option was added so that LAPACK routines that can multiply
  657. arrays by q using the Householder reflectors can be used. Note that in
  658. this case the returned arrays are of type np.double or np.cdouble and
  659. the h array is transposed to be FORTRAN compatible. No routines using
  660. the 'raw' return are currently exposed by numpy, but some are available
  661. in lapack_lite and just await the necessary work.
  662. Examples
  663. --------
  664. >>> a = np.random.randn(9, 6)
  665. >>> q, r = np.linalg.qr(a)
  666. >>> np.allclose(a, np.dot(q, r)) # a does equal qr
  667. True
  668. >>> r2 = np.linalg.qr(a, mode='r')
  669. >>> np.allclose(r, r2) # mode='r' returns the same r as mode='full'
  670. True
  671. Example illustrating a common use of `qr`: solving of least squares
  672. problems
  673. What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
  674. the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
  675. and you'll see that it should be y0 = 0, m = 1.) The answer is provided
  676. by solving the over-determined matrix equation ``Ax = b``, where::
  677. A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
  678. x = array([[y0], [m]])
  679. b = array([[1], [0], [2], [1]])
  680. If A = qr such that q is orthonormal (which is always possible via
  681. Gram-Schmidt), then ``x = inv(r) * (q.T) * b``. (In numpy practice,
  682. however, we simply use `lstsq`.)
  683. >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
  684. >>> A
  685. array([[0, 1],
  686. [1, 1],
  687. [1, 1],
  688. [2, 1]])
  689. >>> b = np.array([1, 0, 2, 1])
  690. >>> q, r = np.linalg.qr(A)
  691. >>> p = np.dot(q.T, b)
  692. >>> np.dot(np.linalg.inv(r), p)
  693. array([ 1.1e-16, 1.0e+00])
  694. """
  695. if mode not in ('reduced', 'complete', 'r', 'raw'):
  696. if mode in ('f', 'full'):
  697. # 2013-04-01, 1.8
  698. msg = "".join((
  699. "The 'full' option is deprecated in favor of 'reduced'.\n",
  700. "For backward compatibility let mode default."))
  701. warnings.warn(msg, DeprecationWarning, stacklevel=3)
  702. mode = 'reduced'
  703. elif mode in ('e', 'economic'):
  704. # 2013-04-01, 1.8
  705. msg = "The 'economic' option is deprecated."
  706. warnings.warn(msg, DeprecationWarning, stacklevel=3)
  707. mode = 'economic'
  708. else:
  709. raise ValueError("Unrecognized mode '%s'" % mode)
  710. a, wrap = _makearray(a)
  711. _assert_2d(a)
  712. m, n = a.shape
  713. t, result_t = _commonType(a)
  714. a = _fastCopyAndTranspose(t, a)
  715. a = _to_native_byte_order(a)
  716. mn = min(m, n)
  717. tau = zeros((mn,), t)
  718. if isComplexType(t):
  719. lapack_routine = lapack_lite.zgeqrf
  720. routine_name = 'zgeqrf'
  721. else:
  722. lapack_routine = lapack_lite.dgeqrf
  723. routine_name = 'dgeqrf'
  724. # calculate optimal size of work data 'work'
  725. lwork = 1
  726. work = zeros((lwork,), t)
  727. results = lapack_routine(m, n, a, max(1, m), tau, work, -1, 0)
  728. if results['info'] != 0:
  729. raise LinAlgError('%s returns %d' % (routine_name, results['info']))
  730. # do qr decomposition
  731. lwork = max(1, n, int(abs(work[0])))
  732. work = zeros((lwork,), t)
  733. results = lapack_routine(m, n, a, max(1, m), tau, work, lwork, 0)
  734. if results['info'] != 0:
  735. raise LinAlgError('%s returns %d' % (routine_name, results['info']))
  736. # handle modes that don't return q
  737. if mode == 'r':
  738. r = _fastCopyAndTranspose(result_t, a[:, :mn])
  739. return wrap(triu(r))
  740. if mode == 'raw':
  741. return a, tau
  742. if mode == 'economic':
  743. if t != result_t :
  744. a = a.astype(result_t, copy=False)
  745. return wrap(a.T)
  746. # generate q from a
  747. if mode == 'complete' and m > n:
  748. mc = m
  749. q = empty((m, m), t)
  750. else:
  751. mc = mn
  752. q = empty((n, m), t)
  753. q[:n] = a
  754. if isComplexType(t):
  755. lapack_routine = lapack_lite.zungqr
  756. routine_name = 'zungqr'
  757. else:
  758. lapack_routine = lapack_lite.dorgqr
  759. routine_name = 'dorgqr'
  760. # determine optimal lwork
  761. lwork = 1
  762. work = zeros((lwork,), t)
  763. results = lapack_routine(m, mc, mn, q, max(1, m), tau, work, -1, 0)
  764. if results['info'] != 0:
  765. raise LinAlgError('%s returns %d' % (routine_name, results['info']))
  766. # compute q
  767. lwork = max(1, n, int(abs(work[0])))
  768. work = zeros((lwork,), t)
  769. results = lapack_routine(m, mc, mn, q, max(1, m), tau, work, lwork, 0)
  770. if results['info'] != 0:
  771. raise LinAlgError('%s returns %d' % (routine_name, results['info']))
  772. q = _fastCopyAndTranspose(result_t, q[:mc])
  773. r = _fastCopyAndTranspose(result_t, a[:, :mc])
  774. return wrap(q), wrap(triu(r))
  775. # Eigenvalues
  776. @array_function_dispatch(_unary_dispatcher)
  777. def eigvals(a):
  778. """
  779. Compute the eigenvalues of a general matrix.
  780. Main difference between `eigvals` and `eig`: the eigenvectors aren't
  781. returned.
  782. Parameters
  783. ----------
  784. a : (..., M, M) array_like
  785. A complex- or real-valued matrix whose eigenvalues will be computed.
  786. Returns
  787. -------
  788. w : (..., M,) ndarray
  789. The eigenvalues, each repeated according to its multiplicity.
  790. They are not necessarily ordered, nor are they necessarily
  791. real for real matrices.
  792. Raises
  793. ------
  794. LinAlgError
  795. If the eigenvalue computation does not converge.
  796. See Also
  797. --------
  798. eig : eigenvalues and right eigenvectors of general arrays
  799. eigvalsh : eigenvalues of real symmetric or complex Hermitian
  800. (conjugate symmetric) arrays.
  801. eigh : eigenvalues and eigenvectors of real symmetric or complex
  802. Hermitian (conjugate symmetric) arrays.
  803. Notes
  804. -----
  805. .. versionadded:: 1.8.0
  806. Broadcasting rules apply, see the `numpy.linalg` documentation for
  807. details.
  808. This is implemented using the ``_geev`` LAPACK routines which compute
  809. the eigenvalues and eigenvectors of general square arrays.
  810. Examples
  811. --------
  812. Illustration, using the fact that the eigenvalues of a diagonal matrix
  813. are its diagonal elements, that multiplying a matrix on the left
  814. by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
  815. of `Q`), preserves the eigenvalues of the "middle" matrix. In other words,
  816. if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
  817. ``A``:
  818. >>> from numpy import linalg as LA
  819. >>> x = np.random.random()
  820. >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
  821. >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
  822. (1.0, 1.0, 0.0)
  823. Now multiply a diagonal matrix by ``Q`` on one side and by ``Q.T`` on the other:
  824. >>> D = np.diag((-1,1))
  825. >>> LA.eigvals(D)
  826. array([-1., 1.])
  827. >>> A = np.dot(Q, D)
  828. >>> A = np.dot(A, Q.T)
  829. >>> LA.eigvals(A)
  830. array([ 1., -1.]) # random
  831. """
  832. a, wrap = _makearray(a)
  833. _assert_stacked_2d(a)
  834. _assert_stacked_square(a)
  835. _assert_finite(a)
  836. t, result_t = _commonType(a)
  837. extobj = get_linalg_error_extobj(
  838. _raise_linalgerror_eigenvalues_nonconvergence)
  839. signature = 'D->D' if isComplexType(t) else 'd->D'
  840. w = _umath_linalg.eigvals(a, signature=signature, extobj=extobj)
  841. if not isComplexType(t):
  842. if all(w.imag == 0):
  843. w = w.real
  844. result_t = _realType(result_t)
  845. else:
  846. result_t = _complexType(result_t)
  847. return w.astype(result_t, copy=False)
  848. def _eigvalsh_dispatcher(a, UPLO=None):
  849. return (a,)
  850. @array_function_dispatch(_eigvalsh_dispatcher)
  851. def eigvalsh(a, UPLO='L'):
  852. """
  853. Compute the eigenvalues of a complex Hermitian or real symmetric matrix.
  854. Main difference from eigh: the eigenvectors are not computed.
  855. Parameters
  856. ----------
  857. a : (..., M, M) array_like
  858. A complex- or real-valued matrix whose eigenvalues are to be
  859. computed.
  860. UPLO : {'L', 'U'}, optional
  861. Specifies whether the calculation is done with the lower triangular
  862. part of `a` ('L', default) or the upper triangular part ('U').
  863. Irrespective of this value only the real parts of the diagonal will
  864. be considered in the computation to preserve the notion of a Hermitian
  865. matrix. It therefore follows that the imaginary part of the diagonal
  866. will always be treated as zero.
  867. Returns
  868. -------
  869. w : (..., M,) ndarray
  870. The eigenvalues in ascending order, each repeated according to
  871. its multiplicity.
  872. Raises
  873. ------
  874. LinAlgError
  875. If the eigenvalue computation does not converge.
  876. See Also
  877. --------
  878. eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian
  879. (conjugate symmetric) arrays.
  880. eigvals : eigenvalues of general real or complex arrays.
  881. eig : eigenvalues and right eigenvectors of general real or complex
  882. arrays.
  883. Notes
  884. -----
  885. .. versionadded:: 1.8.0
  886. Broadcasting rules apply, see the `numpy.linalg` documentation for
  887. details.
  888. The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``.
  889. Examples
  890. --------
  891. >>> from numpy import linalg as LA
  892. >>> a = np.array([[1, -2j], [2j, 5]])
  893. >>> LA.eigvalsh(a)
  894. array([ 0.17157288, 5.82842712]) # may vary
  895. >>> # demonstrate the treatment of the imaginary part of the diagonal
  896. >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
  897. >>> a
  898. array([[5.+2.j, 9.-2.j],
  899. [0.+2.j, 2.-1.j]])
  900. >>> # with UPLO='L' this is numerically equivalent to using LA.eigvals()
  901. >>> # with:
  902. >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
  903. >>> b
  904. array([[5.+0.j, 0.-2.j],
  905. [0.+2.j, 2.+0.j]])
  906. >>> wa = LA.eigvalsh(a)
  907. >>> wb = LA.eigvals(b)
  908. >>> wa; wb
  909. array([1., 6.])
  910. array([6.+0.j, 1.+0.j])
  911. """
  912. UPLO = UPLO.upper()
  913. if UPLO not in ('L', 'U'):
  914. raise ValueError("UPLO argument must be 'L' or 'U'")
  915. extobj = get_linalg_error_extobj(
  916. _raise_linalgerror_eigenvalues_nonconvergence)
  917. if UPLO == 'L':
  918. gufunc = _umath_linalg.eigvalsh_lo
  919. else:
  920. gufunc = _umath_linalg.eigvalsh_up
  921. a, wrap = _makearray(a)
  922. _assert_stacked_2d(a)
  923. _assert_stacked_square(a)
  924. t, result_t = _commonType(a)
  925. signature = 'D->d' if isComplexType(t) else 'd->d'
  926. w = gufunc(a, signature=signature, extobj=extobj)
  927. return w.astype(_realType(result_t), copy=False)
  928. def _convertarray(a):
  929. t, result_t = _commonType(a)
  930. a = _fastCT(a.astype(t))
  931. return a, t, result_t
  932. # Eigenvectors
  933. @array_function_dispatch(_unary_dispatcher)
  934. def eig(a):
  935. """
  936. Compute the eigenvalues and right eigenvectors of a square array.
  937. Parameters
  938. ----------
  939. a : (..., M, M) array
  940. Matrices for which the eigenvalues and right eigenvectors will
  941. be computed
  942. Returns
  943. -------
  944. w : (..., M) array
  945. The eigenvalues, each repeated according to its multiplicity.
  946. The eigenvalues are not necessarily ordered. The resulting
  947. array will be of complex type, unless the imaginary part is
  948. zero in which case it will be cast to a real type. When `a`
  949. is real the resulting eigenvalues will be real (0 imaginary
  950. part) or occur in conjugate pairs
  951. v : (..., M, M) array
  952. The normalized (unit "length") eigenvectors, such that the
  953. column ``v[:,i]`` is the eigenvector corresponding to the
  954. eigenvalue ``w[i]``.
  955. Raises
  956. ------
  957. LinAlgError
  958. If the eigenvalue computation does not converge.
  959. See Also
  960. --------
  961. eigvals : eigenvalues of a non-symmetric array.
  962. eigh : eigenvalues and eigenvectors of a real symmetric or complex
  963. Hermitian (conjugate symmetric) array.
  964. eigvalsh : eigenvalues of a real symmetric or complex Hermitian
  965. (conjugate symmetric) array.
  966. Notes
  967. -----
  968. .. versionadded:: 1.8.0
  969. Broadcasting rules apply, see the `numpy.linalg` documentation for
  970. details.
  971. This is implemented using the ``_geev`` LAPACK routines which compute
  972. the eigenvalues and eigenvectors of general square arrays.
  973. The number `w` is an eigenvalue of `a` if there exists a vector
  974. `v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and
  975. `v` satisfy the equations ``dot(a[:,:], v[:,i]) = w[i] * v[:,i]``
  976. for :math:`i \\in \\{0,...,M-1\\}`.
  977. The array `v` of eigenvectors may not be of maximum rank, that is, some
  978. of the columns may be linearly dependent, although round-off error may
  979. obscure that fact. If the eigenvalues are all different, then theoretically
  980. the eigenvectors are linearly independent. Likewise, the (complex-valued)
  981. matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e.,
  982. if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate
  983. transpose of `a`.
  984. Finally, it is emphasized that `v` consists of the *right* (as in
  985. right-hand side) eigenvectors of `a`. A vector `y` satisfying
  986. ``dot(y.T, a) = z * y.T`` for some number `z` is called a *left*
  987. eigenvector of `a`, and, in general, the left and right eigenvectors
  988. of a matrix are not necessarily the (perhaps conjugate) transposes
  989. of each other.
  990. References
  991. ----------
  992. G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
  993. Academic Press, Inc., 1980, Various pp.
  994. Examples
  995. --------
  996. >>> from numpy import linalg as LA
  997. (Almost) trivial example with real e-values and e-vectors.
  998. >>> w, v = LA.eig(np.diag((1, 2, 3)))
  999. >>> w; v
  1000. array([1., 2., 3.])
  1001. array([[1., 0., 0.],
  1002. [0., 1., 0.],
  1003. [0., 0., 1.]])
  1004. Real matrix possessing complex e-values and e-vectors; note that the
  1005. e-values are complex conjugates of each other.
  1006. >>> w, v = LA.eig(np.array([[1, -1], [1, 1]]))
  1007. >>> w; v
  1008. array([1.+1.j, 1.-1.j])
  1009. array([[0.70710678+0.j , 0.70710678-0.j ],
  1010. [0. -0.70710678j, 0. +0.70710678j]])
  1011. Complex-valued matrix with real e-values (but complex-valued e-vectors);
  1012. note that ``a.conj().T == a``, i.e., `a` is Hermitian.
  1013. >>> a = np.array([[1, 1j], [-1j, 1]])
  1014. >>> w, v = LA.eig(a)
  1015. >>> w; v
  1016. array([2.+0.j, 0.+0.j])
  1017. array([[ 0. +0.70710678j, 0.70710678+0.j ], # may vary
  1018. [ 0.70710678+0.j , -0. +0.70710678j]])
  1019. Be careful about round-off error!
  1020. >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
  1021. >>> # Theor. e-values are 1 +/- 1e-9
  1022. >>> w, v = LA.eig(a)
  1023. >>> w; v
  1024. array([1., 1.])
  1025. array([[1., 0.],
  1026. [0., 1.]])
  1027. """
  1028. a, wrap = _makearray(a)
  1029. _assert_stacked_2d(a)
  1030. _assert_stacked_square(a)
  1031. _assert_finite(a)
  1032. t, result_t = _commonType(a)
  1033. extobj = get_linalg_error_extobj(
  1034. _raise_linalgerror_eigenvalues_nonconvergence)
  1035. signature = 'D->DD' if isComplexType(t) else 'd->DD'
  1036. w, vt = _umath_linalg.eig(a, signature=signature, extobj=extobj)
  1037. if not isComplexType(t) and all(w.imag == 0.0):
  1038. w = w.real
  1039. vt = vt.real
  1040. result_t = _realType(result_t)
  1041. else:
  1042. result_t = _complexType(result_t)
  1043. vt = vt.astype(result_t, copy=False)
  1044. return w.astype(result_t, copy=False), wrap(vt)
  1045. @array_function_dispatch(_eigvalsh_dispatcher)
  1046. def eigh(a, UPLO='L'):
  1047. """
  1048. Return the eigenvalues and eigenvectors of a complex Hermitian
  1049. (conjugate symmetric) or a real symmetric matrix.
  1050. Returns two objects, a 1-D array containing the eigenvalues of `a`, and
  1051. a 2-D square array or matrix (depending on the input type) of the
  1052. corresponding eigenvectors (in columns).
  1053. Parameters
  1054. ----------
  1055. a : (..., M, M) array
  1056. Hermitian or real symmetric matrices whose eigenvalues and
  1057. eigenvectors are to be computed.
  1058. UPLO : {'L', 'U'}, optional
  1059. Specifies whether the calculation is done with the lower triangular
  1060. part of `a` ('L', default) or the upper triangular part ('U').
  1061. Irrespective of this value only the real parts of the diagonal will
  1062. be considered in the computation to preserve the notion of a Hermitian
  1063. matrix. It therefore follows that the imaginary part of the diagonal
  1064. will always be treated as zero.
  1065. Returns
  1066. -------
  1067. w : (..., M) ndarray
  1068. The eigenvalues in ascending order, each repeated according to
  1069. its multiplicity.
  1070. v : {(..., M, M) ndarray, (..., M, M) matrix}
  1071. The column ``v[:, i]`` is the normalized eigenvector corresponding
  1072. to the eigenvalue ``w[i]``. Will return a matrix object if `a` is
  1073. a matrix object.
  1074. Raises
  1075. ------
  1076. LinAlgError
  1077. If the eigenvalue computation does not converge.
  1078. See Also
  1079. --------
  1080. eigvalsh : eigenvalues of real symmetric or complex Hermitian
  1081. (conjugate symmetric) arrays.
  1082. eig : eigenvalues and right eigenvectors for non-symmetric arrays.
  1083. eigvals : eigenvalues of non-symmetric arrays.
  1084. Notes
  1085. -----
  1086. .. versionadded:: 1.8.0
  1087. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1088. details.
  1089. The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``,
  1090. ``_heevd``.
  1091. The eigenvalues of real symmetric or complex Hermitian matrices are
  1092. always real. [1]_ The array `v` of (column) eigenvectors is unitary
  1093. and `a`, `w`, and `v` satisfy the equations
  1094. ``dot(a, v[:, i]) = w[i] * v[:, i]``.
  1095. References
  1096. ----------
  1097. .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
  1098. FL, Academic Press, Inc., 1980, pg. 222.
  1099. Examples
  1100. --------
  1101. >>> from numpy import linalg as LA
  1102. >>> a = np.array([[1, -2j], [2j, 5]])
  1103. >>> a
  1104. array([[ 1.+0.j, -0.-2.j],
  1105. [ 0.+2.j, 5.+0.j]])
  1106. >>> w, v = LA.eigh(a)
  1107. >>> w; v
  1108. array([0.17157288, 5.82842712])
  1109. array([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
  1110. [ 0. +0.38268343j, 0. -0.92387953j]])
  1111. >>> np.dot(a, v[:, 0]) - w[0] * v[:, 0] # verify 1st e-val/vec pair
  1112. array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j])
  1113. >>> np.dot(a, v[:, 1]) - w[1] * v[:, 1] # verify 2nd e-val/vec pair
  1114. array([0.+0.j, 0.+0.j])
  1115. >>> A = np.matrix(a) # what happens if input is a matrix object
  1116. >>> A
  1117. matrix([[ 1.+0.j, -0.-2.j],
  1118. [ 0.+2.j, 5.+0.j]])
  1119. >>> w, v = LA.eigh(A)
  1120. >>> w; v
  1121. array([0.17157288, 5.82842712])
  1122. matrix([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
  1123. [ 0. +0.38268343j, 0. -0.92387953j]])
  1124. >>> # demonstrate the treatment of the imaginary part of the diagonal
  1125. >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
  1126. >>> a
  1127. array([[5.+2.j, 9.-2.j],
  1128. [0.+2.j, 2.-1.j]])
  1129. >>> # with UPLO='L' this is numerically equivalent to using LA.eig() with:
  1130. >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
  1131. >>> b
  1132. array([[5.+0.j, 0.-2.j],
  1133. [0.+2.j, 2.+0.j]])
  1134. >>> wa, va = LA.eigh(a)
  1135. >>> wb, vb = LA.eig(b)
  1136. >>> wa; wb
  1137. array([1., 6.])
  1138. array([6.+0.j, 1.+0.j])
  1139. >>> va; vb
  1140. array([[-0.4472136 +0.j , -0.89442719+0.j ], # may vary
  1141. [ 0. +0.89442719j, 0. -0.4472136j ]])
  1142. array([[ 0.89442719+0.j , -0. +0.4472136j],
  1143. [-0. +0.4472136j, 0.89442719+0.j ]])
  1144. """
  1145. UPLO = UPLO.upper()
  1146. if UPLO not in ('L', 'U'):
  1147. raise ValueError("UPLO argument must be 'L' or 'U'")
  1148. a, wrap = _makearray(a)
  1149. _assert_stacked_2d(a)
  1150. _assert_stacked_square(a)
  1151. t, result_t = _commonType(a)
  1152. extobj = get_linalg_error_extobj(
  1153. _raise_linalgerror_eigenvalues_nonconvergence)
  1154. if UPLO == 'L':
  1155. gufunc = _umath_linalg.eigh_lo
  1156. else:
  1157. gufunc = _umath_linalg.eigh_up
  1158. signature = 'D->dD' if isComplexType(t) else 'd->dd'
  1159. w, vt = gufunc(a, signature=signature, extobj=extobj)
  1160. w = w.astype(_realType(result_t), copy=False)
  1161. vt = vt.astype(result_t, copy=False)
  1162. return w, wrap(vt)
  1163. # Singular value decomposition
  1164. def _svd_dispatcher(a, full_matrices=None, compute_uv=None, hermitian=None):
  1165. return (a,)
  1166. @array_function_dispatch(_svd_dispatcher)
  1167. def svd(a, full_matrices=True, compute_uv=True, hermitian=False):
  1168. """
  1169. Singular Value Decomposition.
  1170. When `a` is a 2D array, it is factorized as ``u @ np.diag(s) @ vh
  1171. = (u * s) @ vh``, where `u` and `vh` are 2D unitary arrays and `s` is a 1D
  1172. array of `a`'s singular values. When `a` is higher-dimensional, SVD is
  1173. applied in stacked mode as explained below.
  1174. Parameters
  1175. ----------
  1176. a : (..., M, N) array_like
  1177. A real or complex array with ``a.ndim >= 2``.
  1178. full_matrices : bool, optional
  1179. If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and
  1180. ``(..., N, N)``, respectively. Otherwise, the shapes are
  1181. ``(..., M, K)`` and ``(..., K, N)``, respectively, where
  1182. ``K = min(M, N)``.
  1183. compute_uv : bool, optional
  1184. Whether or not to compute `u` and `vh` in addition to `s`. True
  1185. by default.
  1186. hermitian : bool, optional
  1187. If True, `a` is assumed to be Hermitian (symmetric if real-valued),
  1188. enabling a more efficient method for finding singular values.
  1189. Defaults to False.
  1190. .. versionadded:: 1.17.0
  1191. Returns
  1192. -------
  1193. u : { (..., M, M), (..., M, K) } array
  1194. Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
  1195. size as those of the input `a`. The size of the last two dimensions
  1196. depends on the value of `full_matrices`. Only returned when
  1197. `compute_uv` is True.
  1198. s : (..., K) array
  1199. Vector(s) with the singular values, within each vector sorted in
  1200. descending order. The first ``a.ndim - 2`` dimensions have the same
  1201. size as those of the input `a`.
  1202. vh : { (..., N, N), (..., K, N) } array
  1203. Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
  1204. size as those of the input `a`. The size of the last two dimensions
  1205. depends on the value of `full_matrices`. Only returned when
  1206. `compute_uv` is True.
  1207. Raises
  1208. ------
  1209. LinAlgError
  1210. If SVD computation does not converge.
  1211. Notes
  1212. -----
  1213. .. versionchanged:: 1.8.0
  1214. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1215. details.
  1216. The decomposition is performed using LAPACK routine ``_gesdd``.
  1217. SVD is usually described for the factorization of a 2D matrix :math:`A`.
  1218. The higher-dimensional case will be discussed below. In the 2D case, SVD is
  1219. written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`,
  1220. :math:`S= \\mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s`
  1221. contains the singular values of `a` and `u` and `vh` are unitary. The rows
  1222. of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are
  1223. the eigenvectors of :math:`A A^H`. In both cases the corresponding
  1224. (possibly non-zero) eigenvalues are given by ``s**2``.
  1225. If `a` has more than two dimensions, then broadcasting rules apply, as
  1226. explained in :ref:`routines.linalg-broadcasting`. This means that SVD is
  1227. working in "stacked" mode: it iterates over all indices of the first
  1228. ``a.ndim - 2`` dimensions and for each combination SVD is applied to the
  1229. last two indices. The matrix `a` can be reconstructed from the
  1230. decomposition with either ``(u * s[..., None, :]) @ vh`` or
  1231. ``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the
  1232. function ``np.matmul`` for python versions below 3.5.)
  1233. If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are
  1234. all the return values.
  1235. Examples
  1236. --------
  1237. >>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
  1238. >>> b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)
  1239. Reconstruction based on full SVD, 2D case:
  1240. >>> u, s, vh = np.linalg.svd(a, full_matrices=True)
  1241. >>> u.shape, s.shape, vh.shape
  1242. ((9, 9), (6,), (6, 6))
  1243. >>> np.allclose(a, np.dot(u[:, :6] * s, vh))
  1244. True
  1245. >>> smat = np.zeros((9, 6), dtype=complex)
  1246. >>> smat[:6, :6] = np.diag(s)
  1247. >>> np.allclose(a, np.dot(u, np.dot(smat, vh)))
  1248. True
  1249. Reconstruction based on reduced SVD, 2D case:
  1250. >>> u, s, vh = np.linalg.svd(a, full_matrices=False)
  1251. >>> u.shape, s.shape, vh.shape
  1252. ((9, 6), (6,), (6, 6))
  1253. >>> np.allclose(a, np.dot(u * s, vh))
  1254. True
  1255. >>> smat = np.diag(s)
  1256. >>> np.allclose(a, np.dot(u, np.dot(smat, vh)))
  1257. True
  1258. Reconstruction based on full SVD, 4D case:
  1259. >>> u, s, vh = np.linalg.svd(b, full_matrices=True)
  1260. >>> u.shape, s.shape, vh.shape
  1261. ((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
  1262. >>> np.allclose(b, np.matmul(u[..., :3] * s[..., None, :], vh))
  1263. True
  1264. >>> np.allclose(b, np.matmul(u[..., :3], s[..., None] * vh))
  1265. True
  1266. Reconstruction based on reduced SVD, 4D case:
  1267. >>> u, s, vh = np.linalg.svd(b, full_matrices=False)
  1268. >>> u.shape, s.shape, vh.shape
  1269. ((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
  1270. >>> np.allclose(b, np.matmul(u * s[..., None, :], vh))
  1271. True
  1272. >>> np.allclose(b, np.matmul(u, s[..., None] * vh))
  1273. True
  1274. """
  1275. a, wrap = _makearray(a)
  1276. if hermitian:
  1277. # note: lapack returns eigenvalues in reverse order to our contract.
  1278. # reversing is cheap by design in numpy, so we do so to be consistent
  1279. if compute_uv:
  1280. s, u = eigh(a)
  1281. s = s[..., ::-1]
  1282. u = u[..., ::-1]
  1283. # singular values are unsigned, move the sign into v
  1284. vt = transpose(u * sign(s)[..., None, :]).conjugate()
  1285. s = abs(s)
  1286. return wrap(u), s, wrap(vt)
  1287. else:
  1288. s = eigvalsh(a)
  1289. s = s[..., ::-1]
  1290. s = abs(s)
  1291. return s
  1292. _assert_stacked_2d(a)
  1293. t, result_t = _commonType(a)
  1294. extobj = get_linalg_error_extobj(_raise_linalgerror_svd_nonconvergence)
  1295. m, n = a.shape[-2:]
  1296. if compute_uv:
  1297. if full_matrices:
  1298. if m < n:
  1299. gufunc = _umath_linalg.svd_m_f
  1300. else:
  1301. gufunc = _umath_linalg.svd_n_f
  1302. else:
  1303. if m < n:
  1304. gufunc = _umath_linalg.svd_m_s
  1305. else:
  1306. gufunc = _umath_linalg.svd_n_s
  1307. signature = 'D->DdD' if isComplexType(t) else 'd->ddd'
  1308. u, s, vh = gufunc(a, signature=signature, extobj=extobj)
  1309. u = u.astype(result_t, copy=False)
  1310. s = s.astype(_realType(result_t), copy=False)
  1311. vh = vh.astype(result_t, copy=False)
  1312. return wrap(u), s, wrap(vh)
  1313. else:
  1314. if m < n:
  1315. gufunc = _umath_linalg.svd_m
  1316. else:
  1317. gufunc = _umath_linalg.svd_n
  1318. signature = 'D->d' if isComplexType(t) else 'd->d'
  1319. s = gufunc(a, signature=signature, extobj=extobj)
  1320. s = s.astype(_realType(result_t), copy=False)
  1321. return s
  1322. def _cond_dispatcher(x, p=None):
  1323. return (x,)
  1324. @array_function_dispatch(_cond_dispatcher)
  1325. def cond(x, p=None):
  1326. """
  1327. Compute the condition number of a matrix.
  1328. This function is capable of returning the condition number using
  1329. one of seven different norms, depending on the value of `p` (see
  1330. Parameters below).
  1331. Parameters
  1332. ----------
  1333. x : (..., M, N) array_like
  1334. The matrix whose condition number is sought.
  1335. p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
  1336. Order of the norm:
  1337. ===== ============================
  1338. p norm for matrices
  1339. ===== ============================
  1340. None 2-norm, computed directly using the ``SVD``
  1341. 'fro' Frobenius norm
  1342. inf max(sum(abs(x), axis=1))
  1343. -inf min(sum(abs(x), axis=1))
  1344. 1 max(sum(abs(x), axis=0))
  1345. -1 min(sum(abs(x), axis=0))
  1346. 2 2-norm (largest sing. value)
  1347. -2 smallest singular value
  1348. ===== ============================
  1349. inf means the numpy.inf object, and the Frobenius norm is
  1350. the root-of-sum-of-squares norm.
  1351. Returns
  1352. -------
  1353. c : {float, inf}
  1354. The condition number of the matrix. May be infinite.
  1355. See Also
  1356. --------
  1357. numpy.linalg.norm
  1358. Notes
  1359. -----
  1360. The condition number of `x` is defined as the norm of `x` times the
  1361. norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
  1362. (root-of-sum-of-squares) or one of a number of other matrix norms.
  1363. References
  1364. ----------
  1365. .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
  1366. Academic Press, Inc., 1980, pg. 285.
  1367. Examples
  1368. --------
  1369. >>> from numpy import linalg as LA
  1370. >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
  1371. >>> a
  1372. array([[ 1, 0, -1],
  1373. [ 0, 1, 0],
  1374. [ 1, 0, 1]])
  1375. >>> LA.cond(a)
  1376. 1.4142135623730951
  1377. >>> LA.cond(a, 'fro')
  1378. 3.1622776601683795
  1379. >>> LA.cond(a, np.inf)
  1380. 2.0
  1381. >>> LA.cond(a, -np.inf)
  1382. 1.0
  1383. >>> LA.cond(a, 1)
  1384. 2.0
  1385. >>> LA.cond(a, -1)
  1386. 1.0
  1387. >>> LA.cond(a, 2)
  1388. 1.4142135623730951
  1389. >>> LA.cond(a, -2)
  1390. 0.70710678118654746 # may vary
  1391. >>> min(LA.svd(a, compute_uv=False))*min(LA.svd(LA.inv(a), compute_uv=False))
  1392. 0.70710678118654746 # may vary
  1393. """
  1394. x = asarray(x) # in case we have a matrix
  1395. if _is_empty_2d(x):
  1396. raise LinAlgError("cond is not defined on empty arrays")
  1397. if p is None or p == 2 or p == -2:
  1398. s = svd(x, compute_uv=False)
  1399. with errstate(all='ignore'):
  1400. if p == -2:
  1401. r = s[..., -1] / s[..., 0]
  1402. else:
  1403. r = s[..., 0] / s[..., -1]
  1404. else:
  1405. # Call inv(x) ignoring errors. The result array will
  1406. # contain nans in the entries where inversion failed.
  1407. _assert_stacked_2d(x)
  1408. _assert_stacked_square(x)
  1409. t, result_t = _commonType(x)
  1410. signature = 'D->D' if isComplexType(t) else 'd->d'
  1411. with errstate(all='ignore'):
  1412. invx = _umath_linalg.inv(x, signature=signature)
  1413. r = norm(x, p, axis=(-2, -1)) * norm(invx, p, axis=(-2, -1))
  1414. r = r.astype(result_t, copy=False)
  1415. # Convert nans to infs unless the original array had nan entries
  1416. r = asarray(r)
  1417. nan_mask = isnan(r)
  1418. if nan_mask.any():
  1419. nan_mask &= ~isnan(x).any(axis=(-2, -1))
  1420. if r.ndim > 0:
  1421. r[nan_mask] = Inf
  1422. elif nan_mask:
  1423. r[()] = Inf
  1424. # Convention is to return scalars instead of 0d arrays
  1425. if r.ndim == 0:
  1426. r = r[()]
  1427. return r
  1428. def _matrix_rank_dispatcher(M, tol=None, hermitian=None):
  1429. return (M,)
  1430. @array_function_dispatch(_matrix_rank_dispatcher)
  1431. def matrix_rank(M, tol=None, hermitian=False):
  1432. """
  1433. Return matrix rank of array using SVD method
  1434. Rank of the array is the number of singular values of the array that are
  1435. greater than `tol`.
  1436. .. versionchanged:: 1.14
  1437. Can now operate on stacks of matrices
  1438. Parameters
  1439. ----------
  1440. M : {(M,), (..., M, N)} array_like
  1441. Input vector or stack of matrices.
  1442. tol : (...) array_like, float, optional
  1443. Threshold below which SVD values are considered zero. If `tol` is
  1444. None, and ``S`` is an array with singular values for `M`, and
  1445. ``eps`` is the epsilon value for datatype of ``S``, then `tol` is
  1446. set to ``S.max() * max(M.shape) * eps``.
  1447. .. versionchanged:: 1.14
  1448. Broadcasted against the stack of matrices
  1449. hermitian : bool, optional
  1450. If True, `M` is assumed to be Hermitian (symmetric if real-valued),
  1451. enabling a more efficient method for finding singular values.
  1452. Defaults to False.
  1453. .. versionadded:: 1.14
  1454. Returns
  1455. -------
  1456. rank : (...) array_like
  1457. Rank of M.
  1458. Notes
  1459. -----
  1460. The default threshold to detect rank deficiency is a test on the magnitude
  1461. of the singular values of `M`. By default, we identify singular values less
  1462. than ``S.max() * max(M.shape) * eps`` as indicating rank deficiency (with
  1463. the symbols defined above). This is the algorithm MATLAB uses [1]. It also
  1464. appears in *Numerical recipes* in the discussion of SVD solutions for linear
  1465. least squares [2].
  1466. This default threshold is designed to detect rank deficiency accounting for
  1467. the numerical errors of the SVD computation. Imagine that there is a column
  1468. in `M` that is an exact (in floating point) linear combination of other
  1469. columns in `M`. Computing the SVD on `M` will not produce a singular value
  1470. exactly equal to 0 in general: any difference of the smallest SVD value from
  1471. 0 will be caused by numerical imprecision in the calculation of the SVD.
  1472. Our threshold for small SVD values takes this numerical imprecision into
  1473. account, and the default threshold will detect such numerical rank
  1474. deficiency. The threshold may declare a matrix `M` rank deficient even if
  1475. the linear combination of some columns of `M` is not exactly equal to
  1476. another column of `M` but only numerically very close to another column of
  1477. `M`.
  1478. We chose our default threshold because it is in wide use. Other thresholds
  1479. are possible. For example, elsewhere in the 2007 edition of *Numerical
  1480. recipes* there is an alternative threshold of ``S.max() *
  1481. np.finfo(M.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe
  1482. this threshold as being based on "expected roundoff error" (p 71).
  1483. The thresholds above deal with floating point roundoff error in the
  1484. calculation of the SVD. However, you may have more information about the
  1485. sources of error in `M` that would make you consider other tolerance values
  1486. to detect *effective* rank deficiency. The most useful measure of the
  1487. tolerance depends on the operations you intend to use on your matrix. For
  1488. example, if your data come from uncertain measurements with uncertainties
  1489. greater than floating point epsilon, choosing a tolerance near that
  1490. uncertainty may be preferable. The tolerance may be absolute if the
  1491. uncertainties are absolute rather than relative.
  1492. References
  1493. ----------
  1494. .. [1] MATLAB reference documention, "Rank"
  1495. https://www.mathworks.com/help/techdoc/ref/rank.html
  1496. .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
  1497. "Numerical Recipes (3rd edition)", Cambridge University Press, 2007,
  1498. page 795.
  1499. Examples
  1500. --------
  1501. >>> from numpy.linalg import matrix_rank
  1502. >>> matrix_rank(np.eye(4)) # Full rank matrix
  1503. 4
  1504. >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
  1505. >>> matrix_rank(I)
  1506. 3
  1507. >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
  1508. 1
  1509. >>> matrix_rank(np.zeros((4,)))
  1510. 0
  1511. """
  1512. M = asarray(M)
  1513. if M.ndim < 2:
  1514. return int(not all(M==0))
  1515. S = svd(M, compute_uv=False, hermitian=hermitian)
  1516. if tol is None:
  1517. tol = S.max(axis=-1, keepdims=True) * max(M.shape[-2:]) * finfo(S.dtype).eps
  1518. else:
  1519. tol = asarray(tol)[..., newaxis]
  1520. return count_nonzero(S > tol, axis=-1)
  1521. # Generalized inverse
  1522. def _pinv_dispatcher(a, rcond=None, hermitian=None):
  1523. return (a,)
  1524. @array_function_dispatch(_pinv_dispatcher)
  1525. def pinv(a, rcond=1e-15, hermitian=False):
  1526. """
  1527. Compute the (Moore-Penrose) pseudo-inverse of a matrix.
  1528. Calculate the generalized inverse of a matrix using its
  1529. singular-value decomposition (SVD) and including all
  1530. *large* singular values.
  1531. .. versionchanged:: 1.14
  1532. Can now operate on stacks of matrices
  1533. Parameters
  1534. ----------
  1535. a : (..., M, N) array_like
  1536. Matrix or stack of matrices to be pseudo-inverted.
  1537. rcond : (...) array_like of float
  1538. Cutoff for small singular values.
  1539. Singular values less than or equal to
  1540. ``rcond * largest_singular_value`` are set to zero.
  1541. Broadcasts against the stack of matrices.
  1542. hermitian : bool, optional
  1543. If True, `a` is assumed to be Hermitian (symmetric if real-valued),
  1544. enabling a more efficient method for finding singular values.
  1545. Defaults to False.
  1546. .. versionadded:: 1.17.0
  1547. Returns
  1548. -------
  1549. B : (..., N, M) ndarray
  1550. The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
  1551. is `B`.
  1552. Raises
  1553. ------
  1554. LinAlgError
  1555. If the SVD computation does not converge.
  1556. Notes
  1557. -----
  1558. The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
  1559. defined as: "the matrix that 'solves' [the least-squares problem]
  1560. :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then
  1561. :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`.
  1562. It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular
  1563. value decomposition of A, then
  1564. :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
  1565. orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting
  1566. of A's so-called singular values, (followed, typically, by
  1567. zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix
  1568. consisting of the reciprocals of A's singular values
  1569. (again, followed by zeros). [1]_
  1570. References
  1571. ----------
  1572. .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
  1573. FL, Academic Press, Inc., 1980, pp. 139-142.
  1574. Examples
  1575. --------
  1576. The following example checks that ``a * a+ * a == a`` and
  1577. ``a+ * a * a+ == a+``:
  1578. >>> a = np.random.randn(9, 6)
  1579. >>> B = np.linalg.pinv(a)
  1580. >>> np.allclose(a, np.dot(a, np.dot(B, a)))
  1581. True
  1582. >>> np.allclose(B, np.dot(B, np.dot(a, B)))
  1583. True
  1584. """
  1585. a, wrap = _makearray(a)
  1586. rcond = asarray(rcond)
  1587. if _is_empty_2d(a):
  1588. m, n = a.shape[-2:]
  1589. res = empty(a.shape[:-2] + (n, m), dtype=a.dtype)
  1590. return wrap(res)
  1591. a = a.conjugate()
  1592. u, s, vt = svd(a, full_matrices=False, hermitian=hermitian)
  1593. # discard small singular values
  1594. cutoff = rcond[..., newaxis] * amax(s, axis=-1, keepdims=True)
  1595. large = s > cutoff
  1596. s = divide(1, s, where=large, out=s)
  1597. s[~large] = 0
  1598. res = matmul(transpose(vt), multiply(s[..., newaxis], transpose(u)))
  1599. return wrap(res)
  1600. # Determinant
  1601. @array_function_dispatch(_unary_dispatcher)
  1602. def slogdet(a):
  1603. """
  1604. Compute the sign and (natural) logarithm of the determinant of an array.
  1605. If an array has a very small or very large determinant, then a call to
  1606. `det` may overflow or underflow. This routine is more robust against such
  1607. issues, because it computes the logarithm of the determinant rather than
  1608. the determinant itself.
  1609. Parameters
  1610. ----------
  1611. a : (..., M, M) array_like
  1612. Input array, has to be a square 2-D array.
  1613. Returns
  1614. -------
  1615. sign : (...) array_like
  1616. A number representing the sign of the determinant. For a real matrix,
  1617. this is 1, 0, or -1. For a complex matrix, this is a complex number
  1618. with absolute value 1 (i.e., it is on the unit circle), or else 0.
  1619. logdet : (...) array_like
  1620. The natural log of the absolute value of the determinant.
  1621. If the determinant is zero, then `sign` will be 0 and `logdet` will be
  1622. -Inf. In all cases, the determinant is equal to ``sign * np.exp(logdet)``.
  1623. See Also
  1624. --------
  1625. det
  1626. Notes
  1627. -----
  1628. .. versionadded:: 1.8.0
  1629. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1630. details.
  1631. .. versionadded:: 1.6.0
  1632. The determinant is computed via LU factorization using the LAPACK
  1633. routine ``z/dgetrf``.
  1634. Examples
  1635. --------
  1636. The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:
  1637. >>> a = np.array([[1, 2], [3, 4]])
  1638. >>> (sign, logdet) = np.linalg.slogdet(a)
  1639. >>> (sign, logdet)
  1640. (-1, 0.69314718055994529) # may vary
  1641. >>> sign * np.exp(logdet)
  1642. -2.0
  1643. Computing log-determinants for a stack of matrices:
  1644. >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
  1645. >>> a.shape
  1646. (3, 2, 2)
  1647. >>> sign, logdet = np.linalg.slogdet(a)
  1648. >>> (sign, logdet)
  1649. (array([-1., -1., -1.]), array([ 0.69314718, 1.09861229, 2.07944154]))
  1650. >>> sign * np.exp(logdet)
  1651. array([-2., -3., -8.])
  1652. This routine succeeds where ordinary `det` does not:
  1653. >>> np.linalg.det(np.eye(500) * 0.1)
  1654. 0.0
  1655. >>> np.linalg.slogdet(np.eye(500) * 0.1)
  1656. (1, -1151.2925464970228)
  1657. """
  1658. a = asarray(a)
  1659. _assert_stacked_2d(a)
  1660. _assert_stacked_square(a)
  1661. t, result_t = _commonType(a)
  1662. real_t = _realType(result_t)
  1663. signature = 'D->Dd' if isComplexType(t) else 'd->dd'
  1664. sign, logdet = _umath_linalg.slogdet(a, signature=signature)
  1665. sign = sign.astype(result_t, copy=False)
  1666. logdet = logdet.astype(real_t, copy=False)
  1667. return sign, logdet
  1668. @array_function_dispatch(_unary_dispatcher)
  1669. def det(a):
  1670. """
  1671. Compute the determinant of an array.
  1672. Parameters
  1673. ----------
  1674. a : (..., M, M) array_like
  1675. Input array to compute determinants for.
  1676. Returns
  1677. -------
  1678. det : (...) array_like
  1679. Determinant of `a`.
  1680. See Also
  1681. --------
  1682. slogdet : Another way to represent the determinant, more suitable
  1683. for large matrices where underflow/overflow may occur.
  1684. Notes
  1685. -----
  1686. .. versionadded:: 1.8.0
  1687. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1688. details.
  1689. The determinant is computed via LU factorization using the LAPACK
  1690. routine ``z/dgetrf``.
  1691. Examples
  1692. --------
  1693. The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
  1694. >>> a = np.array([[1, 2], [3, 4]])
  1695. >>> np.linalg.det(a)
  1696. -2.0 # may vary
  1697. Computing determinants for a stack of matrices:
  1698. >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
  1699. >>> a.shape
  1700. (3, 2, 2)
  1701. >>> np.linalg.det(a)
  1702. array([-2., -3., -8.])
  1703. """
  1704. a = asarray(a)
  1705. _assert_stacked_2d(a)
  1706. _assert_stacked_square(a)
  1707. t, result_t = _commonType(a)
  1708. signature = 'D->D' if isComplexType(t) else 'd->d'
  1709. r = _umath_linalg.det(a, signature=signature)
  1710. r = r.astype(result_t, copy=False)
  1711. return r
  1712. # Linear Least Squares
  1713. def _lstsq_dispatcher(a, b, rcond=None):
  1714. return (a, b)
  1715. @array_function_dispatch(_lstsq_dispatcher)
  1716. def lstsq(a, b, rcond="warn"):
  1717. r"""
  1718. Return the least-squares solution to a linear matrix equation.
  1719. Solves the equation :math:`a x = b` by computing a vector `x` that
  1720. minimizes the squared Euclidean 2-norm :math:`\| b - a x \|^2_2`.
  1721. The equation may be under-, well-, or over-determined (i.e., the
  1722. number of linearly independent rows of `a` can be less than, equal
  1723. to, or greater than its number of linearly independent columns).
  1724. If `a` is square and of full rank, then `x` (but for round-off error)
  1725. is the "exact" solution of the equation.
  1726. Parameters
  1727. ----------
  1728. a : (M, N) array_like
  1729. "Coefficient" matrix.
  1730. b : {(M,), (M, K)} array_like
  1731. Ordinate or "dependent variable" values. If `b` is two-dimensional,
  1732. the least-squares solution is calculated for each of the `K` columns
  1733. of `b`.
  1734. rcond : float, optional
  1735. Cut-off ratio for small singular values of `a`.
  1736. For the purposes of rank determination, singular values are treated
  1737. as zero if they are smaller than `rcond` times the largest singular
  1738. value of `a`.
  1739. .. versionchanged:: 1.14.0
  1740. If not set, a FutureWarning is given. The previous default
  1741. of ``-1`` will use the machine precision as `rcond` parameter,
  1742. the new default will use the machine precision times `max(M, N)`.
  1743. To silence the warning and use the new default, use ``rcond=None``,
  1744. to keep using the old behavior, use ``rcond=-1``.
  1745. Returns
  1746. -------
  1747. x : {(N,), (N, K)} ndarray
  1748. Least-squares solution. If `b` is two-dimensional,
  1749. the solutions are in the `K` columns of `x`.
  1750. residuals : {(1,), (K,), (0,)} ndarray
  1751. Sums of residuals; squared Euclidean 2-norm for each column in
  1752. ``b - a*x``.
  1753. If the rank of `a` is < N or M <= N, this is an empty array.
  1754. If `b` is 1-dimensional, this is a (1,) shape array.
  1755. Otherwise the shape is (K,).
  1756. rank : int
  1757. Rank of matrix `a`.
  1758. s : (min(M, N),) ndarray
  1759. Singular values of `a`.
  1760. Raises
  1761. ------
  1762. LinAlgError
  1763. If computation does not converge.
  1764. Notes
  1765. -----
  1766. If `b` is a matrix, then all array results are returned as matrices.
  1767. Examples
  1768. --------
  1769. Fit a line, ``y = mx + c``, through some noisy data-points:
  1770. >>> x = np.array([0, 1, 2, 3])
  1771. >>> y = np.array([-1, 0.2, 0.9, 2.1])
  1772. By examining the coefficients, we see that the line should have a
  1773. gradient of roughly 1 and cut the y-axis at, more or less, -1.
  1774. We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
  1775. and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`:
  1776. >>> A = np.vstack([x, np.ones(len(x))]).T
  1777. >>> A
  1778. array([[ 0., 1.],
  1779. [ 1., 1.],
  1780. [ 2., 1.],
  1781. [ 3., 1.]])
  1782. >>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
  1783. >>> m, c
  1784. (1.0 -0.95) # may vary
  1785. Plot the data along with the fitted line:
  1786. >>> import matplotlib.pyplot as plt
  1787. >>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10)
  1788. >>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line')
  1789. >>> _ = plt.legend()
  1790. >>> plt.show()
  1791. """
  1792. a, _ = _makearray(a)
  1793. b, wrap = _makearray(b)
  1794. is_1d = b.ndim == 1
  1795. if is_1d:
  1796. b = b[:, newaxis]
  1797. _assert_2d(a, b)
  1798. m, n = a.shape[-2:]
  1799. m2, n_rhs = b.shape[-2:]
  1800. if m != m2:
  1801. raise LinAlgError('Incompatible dimensions')
  1802. t, result_t = _commonType(a, b)
  1803. # FIXME: real_t is unused
  1804. real_t = _linalgRealType(t)
  1805. result_real_t = _realType(result_t)
  1806. # Determine default rcond value
  1807. if rcond == "warn":
  1808. # 2017-08-19, 1.14.0
  1809. warnings.warn("`rcond` parameter will change to the default of "
  1810. "machine precision times ``max(M, N)`` where M and N "
  1811. "are the input matrix dimensions.\n"
  1812. "To use the future default and silence this warning "
  1813. "we advise to pass `rcond=None`, to keep using the old, "
  1814. "explicitly pass `rcond=-1`.",
  1815. FutureWarning, stacklevel=3)
  1816. rcond = -1
  1817. if rcond is None:
  1818. rcond = finfo(t).eps * max(n, m)
  1819. if m <= n:
  1820. gufunc = _umath_linalg.lstsq_m
  1821. else:
  1822. gufunc = _umath_linalg.lstsq_n
  1823. signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid'
  1824. extobj = get_linalg_error_extobj(_raise_linalgerror_lstsq)
  1825. if n_rhs == 0:
  1826. # lapack can't handle n_rhs = 0 - so allocate the array one larger in that axis
  1827. b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype)
  1828. x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj)
  1829. if m == 0:
  1830. x[...] = 0
  1831. if n_rhs == 0:
  1832. # remove the item we added
  1833. x = x[..., :n_rhs]
  1834. resids = resids[..., :n_rhs]
  1835. # remove the axis we added
  1836. if is_1d:
  1837. x = x.squeeze(axis=-1)
  1838. # we probably should squeeze resids too, but we can't
  1839. # without breaking compatibility.
  1840. # as documented
  1841. if rank != n or m <= n:
  1842. resids = array([], result_real_t)
  1843. # coerce output arrays
  1844. s = s.astype(result_real_t, copy=False)
  1845. resids = resids.astype(result_real_t, copy=False)
  1846. x = x.astype(result_t, copy=True) # Copying lets the memory in r_parts be freed
  1847. return wrap(x), wrap(resids), rank, s
  1848. def _multi_svd_norm(x, row_axis, col_axis, op):
  1849. """Compute a function of the singular values of the 2-D matrices in `x`.
  1850. This is a private utility function used by `numpy.linalg.norm()`.
  1851. Parameters
  1852. ----------
  1853. x : ndarray
  1854. row_axis, col_axis : int
  1855. The axes of `x` that hold the 2-D matrices.
  1856. op : callable
  1857. This should be either numpy.amin or `numpy.amax` or `numpy.sum`.
  1858. Returns
  1859. -------
  1860. result : float or ndarray
  1861. If `x` is 2-D, the return values is a float.
  1862. Otherwise, it is an array with ``x.ndim - 2`` dimensions.
  1863. The return values are either the minimum or maximum or sum of the
  1864. singular values of the matrices, depending on whether `op`
  1865. is `numpy.amin` or `numpy.amax` or `numpy.sum`.
  1866. """
  1867. y = moveaxis(x, (row_axis, col_axis), (-2, -1))
  1868. result = op(svd(y, compute_uv=False), axis=-1)
  1869. return result
  1870. def _norm_dispatcher(x, ord=None, axis=None, keepdims=None):
  1871. return (x,)
  1872. @array_function_dispatch(_norm_dispatcher)
  1873. def norm(x, ord=None, axis=None, keepdims=False):
  1874. """
  1875. Matrix or vector norm.
  1876. This function is able to return one of eight different matrix norms,
  1877. or one of an infinite number of vector norms (described below), depending
  1878. on the value of the ``ord`` parameter.
  1879. Parameters
  1880. ----------
  1881. x : array_like
  1882. Input array. If `axis` is None, `x` must be 1-D or 2-D, unless `ord`
  1883. is None. If both `axis` and `ord` are None, the 2-norm of
  1884. ``x.ravel`` will be returned.
  1885. ord : {non-zero int, inf, -inf, 'fro', 'nuc'}, optional
  1886. Order of the norm (see table under ``Notes``). inf means numpy's
  1887. `inf` object. The default is None.
  1888. axis : {None, int, 2-tuple of ints}, optional.
  1889. If `axis` is an integer, it specifies the axis of `x` along which to
  1890. compute the vector norms. If `axis` is a 2-tuple, it specifies the
  1891. axes that hold 2-D matrices, and the matrix norms of these matrices
  1892. are computed. If `axis` is None then either a vector norm (when `x`
  1893. is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default
  1894. is None.
  1895. .. versionadded:: 1.8.0
  1896. keepdims : bool, optional
  1897. If this is set to True, the axes which are normed over are left in the
  1898. result as dimensions with size one. With this option the result will
  1899. broadcast correctly against the original `x`.
  1900. .. versionadded:: 1.10.0
  1901. Returns
  1902. -------
  1903. n : float or ndarray
  1904. Norm of the matrix or vector(s).
  1905. Notes
  1906. -----
  1907. For values of ``ord <= 0``, the result is, strictly speaking, not a
  1908. mathematical 'norm', but it may still be useful for various numerical
  1909. purposes.
  1910. The following norms can be calculated:
  1911. ===== ============================ ==========================
  1912. ord norm for matrices norm for vectors
  1913. ===== ============================ ==========================
  1914. None Frobenius norm 2-norm
  1915. 'fro' Frobenius norm --
  1916. 'nuc' nuclear norm --
  1917. inf max(sum(abs(x), axis=1)) max(abs(x))
  1918. -inf min(sum(abs(x), axis=1)) min(abs(x))
  1919. 0 -- sum(x != 0)
  1920. 1 max(sum(abs(x), axis=0)) as below
  1921. -1 min(sum(abs(x), axis=0)) as below
  1922. 2 2-norm (largest sing. value) as below
  1923. -2 smallest singular value as below
  1924. other -- sum(abs(x)**ord)**(1./ord)
  1925. ===== ============================ ==========================
  1926. The Frobenius norm is given by [1]_:
  1927. :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
  1928. The nuclear norm is the sum of the singular values.
  1929. References
  1930. ----------
  1931. .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
  1932. Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
  1933. Examples
  1934. --------
  1935. >>> from numpy import linalg as LA
  1936. >>> a = np.arange(9) - 4
  1937. >>> a
  1938. array([-4, -3, -2, ..., 2, 3, 4])
  1939. >>> b = a.reshape((3, 3))
  1940. >>> b
  1941. array([[-4, -3, -2],
  1942. [-1, 0, 1],
  1943. [ 2, 3, 4]])
  1944. >>> LA.norm(a)
  1945. 7.745966692414834
  1946. >>> LA.norm(b)
  1947. 7.745966692414834
  1948. >>> LA.norm(b, 'fro')
  1949. 7.745966692414834
  1950. >>> LA.norm(a, np.inf)
  1951. 4.0
  1952. >>> LA.norm(b, np.inf)
  1953. 9.0
  1954. >>> LA.norm(a, -np.inf)
  1955. 0.0
  1956. >>> LA.norm(b, -np.inf)
  1957. 2.0
  1958. >>> LA.norm(a, 1)
  1959. 20.0
  1960. >>> LA.norm(b, 1)
  1961. 7.0
  1962. >>> LA.norm(a, -1)
  1963. -4.6566128774142013e-010
  1964. >>> LA.norm(b, -1)
  1965. 6.0
  1966. >>> LA.norm(a, 2)
  1967. 7.745966692414834
  1968. >>> LA.norm(b, 2)
  1969. 7.3484692283495345
  1970. >>> LA.norm(a, -2)
  1971. 0.0
  1972. >>> LA.norm(b, -2)
  1973. 1.8570331885190563e-016 # may vary
  1974. >>> LA.norm(a, 3)
  1975. 5.8480354764257312 # may vary
  1976. >>> LA.norm(a, -3)
  1977. 0.0
  1978. Using the `axis` argument to compute vector norms:
  1979. >>> c = np.array([[ 1, 2, 3],
  1980. ... [-1, 1, 4]])
  1981. >>> LA.norm(c, axis=0)
  1982. array([ 1.41421356, 2.23606798, 5. ])
  1983. >>> LA.norm(c, axis=1)
  1984. array([ 3.74165739, 4.24264069])
  1985. >>> LA.norm(c, ord=1, axis=1)
  1986. array([ 6., 6.])
  1987. Using the `axis` argument to compute matrix norms:
  1988. >>> m = np.arange(8).reshape(2,2,2)
  1989. >>> LA.norm(m, axis=(1,2))
  1990. array([ 3.74165739, 11.22497216])
  1991. >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])
  1992. (3.7416573867739413, 11.224972160321824)
  1993. """
  1994. x = asarray(x)
  1995. if not issubclass(x.dtype.type, (inexact, object_)):
  1996. x = x.astype(float)
  1997. # Immediately handle some default, simple, fast, and common cases.
  1998. if axis is None:
  1999. ndim = x.ndim
  2000. if ((ord is None) or
  2001. (ord in ('f', 'fro') and ndim == 2) or
  2002. (ord == 2 and ndim == 1)):
  2003. x = x.ravel(order='K')
  2004. if isComplexType(x.dtype.type):
  2005. sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag)
  2006. else:
  2007. sqnorm = dot(x, x)
  2008. ret = sqrt(sqnorm)
  2009. if keepdims:
  2010. ret = ret.reshape(ndim*[1])
  2011. return ret
  2012. # Normalize the `axis` argument to a tuple.
  2013. nd = x.ndim
  2014. if axis is None:
  2015. axis = tuple(range(nd))
  2016. elif not isinstance(axis, tuple):
  2017. try:
  2018. axis = int(axis)
  2019. except Exception:
  2020. raise TypeError("'axis' must be None, an integer or a tuple of integers")
  2021. axis = (axis,)
  2022. if len(axis) == 1:
  2023. if ord == Inf:
  2024. return abs(x).max(axis=axis, keepdims=keepdims)
  2025. elif ord == -Inf:
  2026. return abs(x).min(axis=axis, keepdims=keepdims)
  2027. elif ord == 0:
  2028. # Zero norm
  2029. return (x != 0).astype(x.real.dtype).sum(axis=axis, keepdims=keepdims)
  2030. elif ord == 1:
  2031. # special case for speedup
  2032. return add.reduce(abs(x), axis=axis, keepdims=keepdims)
  2033. elif ord is None or ord == 2:
  2034. # special case for speedup
  2035. s = (x.conj() * x).real
  2036. return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
  2037. else:
  2038. try:
  2039. ord + 1
  2040. except TypeError:
  2041. raise ValueError("Invalid norm order for vectors.")
  2042. absx = abs(x)
  2043. absx **= ord
  2044. ret = add.reduce(absx, axis=axis, keepdims=keepdims)
  2045. ret **= (1 / ord)
  2046. return ret
  2047. elif len(axis) == 2:
  2048. row_axis, col_axis = axis
  2049. row_axis = normalize_axis_index(row_axis, nd)
  2050. col_axis = normalize_axis_index(col_axis, nd)
  2051. if row_axis == col_axis:
  2052. raise ValueError('Duplicate axes given.')
  2053. if ord == 2:
  2054. ret = _multi_svd_norm(x, row_axis, col_axis, amax)
  2055. elif ord == -2:
  2056. ret = _multi_svd_norm(x, row_axis, col_axis, amin)
  2057. elif ord == 1:
  2058. if col_axis > row_axis:
  2059. col_axis -= 1
  2060. ret = add.reduce(abs(x), axis=row_axis).max(axis=col_axis)
  2061. elif ord == Inf:
  2062. if row_axis > col_axis:
  2063. row_axis -= 1
  2064. ret = add.reduce(abs(x), axis=col_axis).max(axis=row_axis)
  2065. elif ord == -1:
  2066. if col_axis > row_axis:
  2067. col_axis -= 1
  2068. ret = add.reduce(abs(x), axis=row_axis).min(axis=col_axis)
  2069. elif ord == -Inf:
  2070. if row_axis > col_axis:
  2071. row_axis -= 1
  2072. ret = add.reduce(abs(x), axis=col_axis).min(axis=row_axis)
  2073. elif ord in [None, 'fro', 'f']:
  2074. ret = sqrt(add.reduce((x.conj() * x).real, axis=axis))
  2075. elif ord == 'nuc':
  2076. ret = _multi_svd_norm(x, row_axis, col_axis, sum)
  2077. else:
  2078. raise ValueError("Invalid norm order for matrices.")
  2079. if keepdims:
  2080. ret_shape = list(x.shape)
  2081. ret_shape[axis[0]] = 1
  2082. ret_shape[axis[1]] = 1
  2083. ret = ret.reshape(ret_shape)
  2084. return ret
  2085. else:
  2086. raise ValueError("Improper number of dimensions to norm.")
  2087. # multi_dot
  2088. def _multidot_dispatcher(arrays):
  2089. return arrays
  2090. @array_function_dispatch(_multidot_dispatcher)
  2091. def multi_dot(arrays):
  2092. """
  2093. Compute the dot product of two or more arrays in a single function call,
  2094. while automatically selecting the fastest evaluation order.
  2095. `multi_dot` chains `numpy.dot` and uses optimal parenthesization
  2096. of the matrices [1]_ [2]_. Depending on the shapes of the matrices,
  2097. this can speed up the multiplication a lot.
  2098. If the first argument is 1-D it is treated as a row vector.
  2099. If the last argument is 1-D it is treated as a column vector.
  2100. The other arguments must be 2-D.
  2101. Think of `multi_dot` as::
  2102. def multi_dot(arrays): return functools.reduce(np.dot, arrays)
  2103. Parameters
  2104. ----------
  2105. arrays : sequence of array_like
  2106. If the first argument is 1-D it is treated as row vector.
  2107. If the last argument is 1-D it is treated as column vector.
  2108. The other arguments must be 2-D.
  2109. Returns
  2110. -------
  2111. output : ndarray
  2112. Returns the dot product of the supplied arrays.
  2113. See Also
  2114. --------
  2115. dot : dot multiplication with two arguments.
  2116. References
  2117. ----------
  2118. .. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378
  2119. .. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication
  2120. Examples
  2121. --------
  2122. `multi_dot` allows you to write::
  2123. >>> from numpy.linalg import multi_dot
  2124. >>> # Prepare some data
  2125. >>> A = np.random.random((10000, 100))
  2126. >>> B = np.random.random((100, 1000))
  2127. >>> C = np.random.random((1000, 5))
  2128. >>> D = np.random.random((5, 333))
  2129. >>> # the actual dot multiplication
  2130. >>> _ = multi_dot([A, B, C, D])
  2131. instead of::
  2132. >>> _ = np.dot(np.dot(np.dot(A, B), C), D)
  2133. >>> # or
  2134. >>> _ = A.dot(B).dot(C).dot(D)
  2135. Notes
  2136. -----
  2137. The cost for a matrix multiplication can be calculated with the
  2138. following function::
  2139. def cost(A, B):
  2140. return A.shape[0] * A.shape[1] * B.shape[1]
  2141. Assume we have three matrices
  2142. :math:`A_{10x100}, B_{100x5}, C_{5x50}`.
  2143. The costs for the two different parenthesizations are as follows::
  2144. cost((AB)C) = 10*100*5 + 10*5*50 = 5000 + 2500 = 7500
  2145. cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000
  2146. """
  2147. n = len(arrays)
  2148. # optimization only makes sense for len(arrays) > 2
  2149. if n < 2:
  2150. raise ValueError("Expecting at least two arrays.")
  2151. elif n == 2:
  2152. return dot(arrays[0], arrays[1])
  2153. arrays = [asanyarray(a) for a in arrays]
  2154. # save original ndim to reshape the result array into the proper form later
  2155. ndim_first, ndim_last = arrays[0].ndim, arrays[-1].ndim
  2156. # Explicitly convert vectors to 2D arrays to keep the logic of the internal
  2157. # _multi_dot_* functions as simple as possible.
  2158. if arrays[0].ndim == 1:
  2159. arrays[0] = atleast_2d(arrays[0])
  2160. if arrays[-1].ndim == 1:
  2161. arrays[-1] = atleast_2d(arrays[-1]).T
  2162. _assert_2d(*arrays)
  2163. # _multi_dot_three is much faster than _multi_dot_matrix_chain_order
  2164. if n == 3:
  2165. result = _multi_dot_three(arrays[0], arrays[1], arrays[2])
  2166. else:
  2167. order = _multi_dot_matrix_chain_order(arrays)
  2168. result = _multi_dot(arrays, order, 0, n - 1)
  2169. # return proper shape
  2170. if ndim_first == 1 and ndim_last == 1:
  2171. return result[0, 0] # scalar
  2172. elif ndim_first == 1 or ndim_last == 1:
  2173. return result.ravel() # 1-D
  2174. else:
  2175. return result
  2176. def _multi_dot_three(A, B, C):
  2177. """
  2178. Find the best order for three arrays and do the multiplication.
  2179. For three arguments `_multi_dot_three` is approximately 15 times faster
  2180. than `_multi_dot_matrix_chain_order`
  2181. """
  2182. a0, a1b0 = A.shape
  2183. b1c0, c1 = C.shape
  2184. # cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1
  2185. cost1 = a0 * b1c0 * (a1b0 + c1)
  2186. # cost2 = cost(A(BC)) = a1b0*b1c0*c1 + a0*a1b0*c1
  2187. cost2 = a1b0 * c1 * (a0 + b1c0)
  2188. if cost1 < cost2:
  2189. return dot(dot(A, B), C)
  2190. else:
  2191. return dot(A, dot(B, C))
  2192. def _multi_dot_matrix_chain_order(arrays, return_costs=False):
  2193. """
  2194. Return a np.array that encodes the optimal order of mutiplications.
  2195. The optimal order array is then used by `_multi_dot()` to do the
  2196. multiplication.
  2197. Also return the cost matrix if `return_costs` is `True`
  2198. The implementation CLOSELY follows Cormen, "Introduction to Algorithms",
  2199. Chapter 15.2, p. 370-378. Note that Cormen uses 1-based indices.
  2200. cost[i, j] = min([
  2201. cost[prefix] + cost[suffix] + cost_mult(prefix, suffix)
  2202. for k in range(i, j)])
  2203. """
  2204. n = len(arrays)
  2205. # p stores the dimensions of the matrices
  2206. # Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50]
  2207. p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]]
  2208. # m is a matrix of costs of the subproblems
  2209. # m[i,j]: min number of scalar multiplications needed to compute A_{i..j}
  2210. m = zeros((n, n), dtype=double)
  2211. # s is the actual ordering
  2212. # s[i, j] is the value of k at which we split the product A_i..A_j
  2213. s = empty((n, n), dtype=intp)
  2214. for l in range(1, n):
  2215. for i in range(n - l):
  2216. j = i + l
  2217. m[i, j] = Inf
  2218. for k in range(i, j):
  2219. q = m[i, k] + m[k+1, j] + p[i]*p[k+1]*p[j+1]
  2220. if q < m[i, j]:
  2221. m[i, j] = q
  2222. s[i, j] = k # Note that Cormen uses 1-based index
  2223. return (s, m) if return_costs else s
  2224. def _multi_dot(arrays, order, i, j):
  2225. """Actually do the multiplication with the given order."""
  2226. if i == j:
  2227. return arrays[i]
  2228. else:
  2229. return dot(_multi_dot(arrays, order, i, order[i, j]),
  2230. _multi_dot(arrays, order, order[i, j] + 1, j))