comparison DEPENDENCIES/mingw32/Python27/Lib/site-packages/numpy/linalg/linalg.py @ 87:2a2c65a20a8b

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