linalg.py 83 KB

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