When SciPy is built using the optimized ATLAS LAPACK and BLAS
libraries, it has very fast linear algebra capabilities. If you dig
deep enough, all of the raw LAPACK and BLAS libraries are available
for your use for even more speed. In this section, some easier-to-use
interfaces to these routines are described.
All of these linear algebra routines expect an object that can be
converted into a 2-D array. The output of these routines is
also a 2-D array.
scipy.linalg vs numpy.linalg
scipy.linalg contains all the functions in
numpy.linalg.
plus some other more advanced ones not contained in numpy.linalg.
Another advantage of using scipy.linalg over numpy.linalg is that
it is always compiled with BLAS/LAPACK support, while for NumPy this is
optional. Therefore, the SciPy version might be faster depending on how
NumPy was installed.
Therefore, unless you don’t want to add scipy as a dependency to
your numpy program, use scipy.linalg instead of numpy.linalg.
numpy.matrix vs 2-D numpy.ndarray
The classes that represent matrices, and basic operations, such as
matrix multiplications and transpose are a part of numpy.
For convenience, we summarize the differences between numpy.matrix
and numpy.ndarray here.
numpy.matrix is matrix class that has a more convenient interface
than numpy.ndarray for matrix operations. This class supports, for
example, MATLAB-like creation syntax via the semicolon, has matrix
multiplication as default for the * operator, and contains I
and T members that serve as shortcuts for inverse and transpose:
Despite its convenience, the use of the numpy.matrix class is
discouraged, since it adds nothing that cannot be accomplished
with 2-D numpy.ndarray objects, and may lead to a confusion of which class
is being used. For example, the above code can be rewritten as:
scipy.linalg operations can be applied equally to
numpy.matrix or to 2D numpy.ndarray objects.
Basic routines
Finding the inverse
The inverse of a matrix A is the matrix
B, such that AB=I, where
I is the identity matrix consisting of ones down the
main diagonal. Usually, B is denoted
B=A−1 . In SciPy, the matrix inverse of
the NumPy array, A, is obtained using linalg.inv(A), or
using A.I if A is a Matrix. For example, let
Solving linear systems of equations is straightforward using the scipy
command linalg.solve. This command expects an input matrix and
a right-hand side vector. The solution vector is then computed. An
option for entering a symmetric matrix is offered, which can speed up
the processing when applicable. As an example, suppose it is desired
to solve the following simultaneous equations:
The determinant of a square matrix A is often denoted
∣A∣ and is a quantity often used in linear
algebra. Suppose aij are the elements of the matrix
A and let
be the determinant of the matrix left by removing the
row and column from
. Then, for any row
Computing norms
Matrix and vector norms can also be computed with SciPy. A wide range
of norm definitions are available using different parameters to the
order argument of linalg.norm. This function takes a rank-1
(vectors) or a rank-2 (matrices) array and an optional order argument
(default is 2). Based on these inputs, a vector or matrix norm of the
requested order is computed.
For vector x, the order parameter can be any real number including
inf or -inf. The computed norm is
Solving linear least-squares problems and pseudo-inverses
Linear least-squares problems occur in many branches of applied
mathematics. In this problem, a set of linear scaling coefficients is
sought that allows a model to fit the data. In particular, it is assumed
that data yi is related to data xi
through a set of coefficients cj and model functions
via the model
Generalized inverse
The generalized inverse is calculated using the command
linalg.pinv. Let A be an
M×N matrix, then if M>N, the generalized
inverse is
Decompositions
In many applications, it is useful to decompose a matrix using other
representations. There are several decompositions supported by SciPy.
Eigenvalues and eigenvectors
The eigenvalue-eigenvector problem is one of the most commonly
employed linear algebra operations. In one popular form, the
eigenvalue-eigenvector problem is to find for some square matrix
A scalars λ and corresponding vectors
v, such that
Av=λv.
For an N×N matrix, there are N (not necessarily
distinct) eigenvalues — roots of the (characteristic) polynomial
∣A−λI∣=0.
The eigenvectors, v, are also sometimes called right
eigenvectors to distinguish them from another set of left eigenvectors
that satisfy
vLHA=λvLH
or
AHvL=λ∗vL.
With its default optional arguments, the command linalg.eig
returns λ and v. However, it can also
return vL and just λ by itself (
returns just as well).
In addition, linalg.eig can also solve the more general eigenvalue problem
for square matrices A and B. The
standard eigenvalue problem is an example of the general eigenvalue
problem for B=I. When a generalized
eigenvalue problem can be solved, it provides a decomposition of
A as
A=BVΛV−1,
where V is the collection of eigenvectors into
columns and Λ is a diagonal matrix of
eigenvalues.
By definition, eigenvectors are only defined up to a constant scale
factor. In SciPy, the scaling factor for the eigenvectors is chosen so
that ∥v∥2=∑ivi2=1.
As an example, consider finding the eigenvalues and eigenvectors of
the matrix
The eigenvectors corresponding to each eigenvalue can be found using
the original equation. The eigenvectors associated with these
eigenvalues can then be found.
Singular value decomposition (SVD) can be thought of as an extension of
the eigenvalue problem to matrices that are not square. Let
A be an M×N matrix with M and
N arbitrary. The matrices AHA and
are square hermitian matrices of
size and , respectively. It is known
that the eigenvalues of square hermitian matrices are real and
non-negative. In addition, there are at most
identical non-zero eigenvalues of
and
Define these positive eigenvalues as The
square-root of these are called singular values of
The eigenvectors of are collected by
columns into an unitary matrix
, while the eigenvectors of
are collected by columns in the
unitary matrix , the singular values are collected
in an zero matrix
with main diagonal entries set to
the singular values. Then
LU decomposition
The LU decomposition finds a representation for the M\times N
matrix \mathbf{A} as
\mathbf{A}=\mathbf{P}\,\mathbf{L}\,\mathbf{U},
where \mathbf{P} is an M\times M permutation matrix (a
permutation of the rows of the identity matrix), \mathbf{L} is
in M\times K lower triangular or trapezoidal matrix (
K=\min\left(M,N\right)) with unit-diagonal, and
\mathbf{U} is an upper triangular or trapezoidal matrix. The
SciPy command for this decomposition is linalg.lu.
Such a decomposition is often useful for solving many simultaneous
equations where the left-hand side does not change but the right-hand
side does. For example, suppose we are going to solve
\mathbf{A}\mathbf{x}_{i}=\mathbf{b}_{i}
for many different \mathbf{b}_{i}. The LU decomposition allows this to be written as
\mathbf{PLUx}_{i}=\mathbf{b}_{i}.
Cholesky decomposition
Cholesky decomposition is a special case of LU decomposition
applicable to Hermitian positive definite matrices. When
\mathbf{A}=\mathbf{A}^{H} and
\mathbf{x}^{H}\mathbf{Ax}\geq0 for all \mathbf{x},
then decompositions of \mathbf{A} can be found so that
where \mathbf{L} is lower triangular and \mathbf{U} is
upper triangular. Notice that \mathbf{L}=\mathbf{U}^{H}. The
command linalg.cholesky computes the Cholesky
factorization. For using the Cholesky factorization to solve systems of
equations, there are also linalg.cho_factor and
routines that work similarly to their LU
decomposition counterparts.
QR decomposition
The QR decomposition (sometimes called a polar decomposition) works
for any M\times N array and finds an M\times M unitary
matrix \mathbf{Q} and an M\times N upper-trapezoidal
matrix \mathbf{R}, such that
\mathbf{A=QR}.
Notice that if the SVD of \mathbf{A} is known, then the QR decomposition can be found.
implies that \mathbf{Q}=\mathbf{U} and
\mathbf{R}=\boldsymbol{\Sigma}\mathbf{V}^{H}. Note, however,
that in SciPy independent algorithms are used to find QR and SVD
decompositions. The command for QR decomposition is linalg.qr.
Schur decomposition
For a square N\times N matrix, \mathbf{A}, the Schur
decomposition finds (not necessarily unique) matrices
\mathbf{T} and \mathbf{Z}, such that
\mathbf{A}=\mathbf{ZT}\mathbf{Z}^{H},
where \mathbf{Z} is a unitary matrix and \mathbf{T} is
either upper triangular or quasi upper triangular, depending on whether
or not a real Schur form or complex Schur form is requested. For a
real Schur form both \mathbf{T} and \mathbf{Z} are
real-valued when \mathbf{A} is real-valued. When
\mathbf{A} is a real-valued matrix, the real Schur form is only
quasi upper triangular because 2\times2 blocks extrude from
the main diagonal corresponding to any complex-valued
eigenvalues. The command linalg.schur finds the Schur
decomposition, while the command converts
and from a real Schur form to a
complex Schur form. The Schur form is especially useful in calculating
functions of matrices.
Interpolative decomposition
scipy.linalg.interpolative contains routines for computing the
interpolative decomposition (ID) of a matrix. For a matrix A
\in \mathbb{C}^{m \times n} of rank k \leq \min \{ m, n \}
this is a factorization
A \Pi =
\begin{bmatrix}
A \Pi_{1} & A \Pi_{2}
\end{bmatrix} =
A \Pi_{1}
\begin{bmatrix}
I & T
\end{bmatrix},
where \Pi = [\Pi_{1}, \Pi_{2}] is a permutation matrix with
\Pi_{1} \in \{ 0, 1 \}^{n \times k}, i.e., A \Pi_{2} =
A \Pi_{1} T. This can equivalently be written as A = BP,
where B = A \Pi_{1} and P = [I, T] \Pi^{\mathsf{T}}
are the skeleton and interpolation matrices, respectively.
Matrix functions
Consider the function f\left(x\right) with Taylor series expansion
The matrix exponential is one of the more common matrix functions.
The preferred method for implementing the matrix exponential is to use
scaling and a Padé approximation for e^{x}. This algorithm is
implemented as linalg.expm.
The inverse of the matrix exponential is the matrix logarithm defined
as the inverse of the matrix exponential:
The matrix logarithm can be obtained with linalg.logm.
Trigonometric functions
The trigonometric functions, \sin, \cos, and
\tan, are implemented for matrices in linalg.sinm,
linalg.cosm, and linalg.tanm, respectively. The matrix
sine and cosine can be defined using Euler’s identity as
Finally, any arbitrary function that takes one complex number and
returns a complex number can be called as a matrix function using the
command linalg.funm. This command takes the matrix and an
arbitrary Python function. It then implements an algorithm from Golub
and Van Loan’s book “Matrix Computations” to compute the function applied
to the matrix using a Schur decomposition. Note that the function
needs to accept complex numbers as input in order to work with this
algorithm. For example, the following code computes the zeroth-order
Bessel function applied to a matrix.
For examples of the use of these functions, see their respective docstrings.
Advanced Features
Batch Support
Some of SciPy’s linear algebra functions can process batches of scalars, 1D-, or
2D-arrays given N-d array input.
For example, a linear algebra function that typically accepts a (2D) matrix may accept
an array of shape (4,3,2), which it would interpret as a batch of four 3-by-2
matrices. In this case, we say that the the core shape of the input is (3, 2) and the
batch shape is (4,). Likewise, a linear algebra function that typically accepts
a (1D) vector would treat a (4,3,2) array as a (4,3) batch of vectors,
in which case the core shape of the input is (2,) and the batch shape is
(4,3). The length of the core shape is also referred to as the core dimension.
In these cases, the final shape of the output is the batch shape of the input
concatenated with the core shape of the output (i.e., the shape of the output when
the batch shape of the input is ()). For more information, see Batched Linear Operations.
overwrite_* arguments
Many linear algebra functions have overwrite_* arguments to signal that an operation
is allowed to work in-place and overwrite the input array (the naming convention is
that an array argument a has a matching overwrite_a; a b argument has a
matching overwrite_b and so on).
By default, scipy.linalg functions preserve their inputs and make copies internally.
In some cases, working in-place may improve performance or avoid running out of memory—
it is however advisable to measure and make sure you actually see improvements
for your specific workloads.
Note however that setting overwrite_a=True only indicates that it may work in-place;
whether it actually does depends on whether additional requirements are met.
For most functions, an in-place operation requires that all of the following conditions
are true:
However, it is better to use the linalg.solve command, which can be
faster and more numerically stable. In this case, it, however, gives the
same answer as shown in the following example:
This is a recursive way to define the determinant, where the base case
is defined by accepting that the determinant of a 1×1 matrix is the only matrix element. In SciPy the determinant can be
calculated with linalg.det. For example, the determinant of
where A† is called the pseudo-inverse of
A. Notice that using this definition of
A the model can be written
y=Ac+ϵ.
The command linalg.lstsq will solve the linear least-squares
problem for c given A and
y . In addition, linalg.pinv will find
A† given A.
The following example and figure demonstrate the use of
linalg.lstsq and linalg.pinv for solving a data-fitting
problem. The data shown below were generated using the model:
yi=c1e−xi+c2xi,
where xi=0.1i for i=1,…,10 , c1=5,
and c2=4. Noise is added to yi and the
coefficients c1 and c2 are estimated using
linear least squares.
is the singular value decomposition of A. Every
matrix has a singular value decomposition. Sometimes, the singular
values are called the spectrum of A. The command
linalg.svd will return U ,
VH, and σi as an array of the
singular values. To obtain the matrix Σ, use
linalg.diagsvd. The following example illustrates the use of
linalg.svd:
Because \mathbf{L} is lower-triangular, the equation can be
solved for \mathbf{U}\mathbf{x}_{i} and, finally,
\mathbf{x}_{i} very rapidly using forward- and
back-substitution. An initial time spent factoring \mathbf{A}
allows for very rapid solution of similar systems of equations in the
future. If the intent for performing LU decomposition is for solving
linear systems, then the command linalg.lu_factor should be used
followed by repeated applications of the command
linalg.lu_solve to solve the system for each new
right-hand side.
linalg.cho_solve
linalg.rsf2csf
\mathbf{T}
\mathbf{Z}
The following example illustrates the Schur decomposition:
Note how, by virtue of how matrix analytic functions are defined,
the Bessel function has acted on the matrix eigenvalues.
the dtype of the input array is LAPACK-compatible: only single and double precision
float (float{32,64}) and complex (complex{64,128}) arrays are compatible;
the array is Fortran-ordered;
currently only two-dimensional arrays, ndim==2, are compatible; batched arrays
use an internal buffer of the size of the core shaped array. This however may change
in a future SciPy version.
If any of these conditions are violated, a copy is made under the hood, regardless of
whether overwrite_a is True or False.
Some functions may relax some of these requirements or impose additional constraints
for working in-place.
Note that this all is completely opaque: if you set overwrite_a=True but the
function has to operate on a copy, no warnings or diagnostic output will be generated.
As an illustration, consider a simple inversion operation:
Since a is of integer dtype, the scipy.linalg.inv function internally makes a
floating-point copy, which it feeds into the LAPACK’s inversion routine. Thus setting
overwrite_a to True makes no difference:
Note that the input array, af, has now been overwritten. We can check that the
input and output arrays actually use the same memory buffer:
>>> np.shares_memory(af,a_inv)True
In general, it may or may not hold that a_invisaf: the only guarantee is
that inputs and outputs share some part of the memory buffer.
Finally, we recommend that you only use these overwrite_a arguments if
performance / memory measurements show a significant improvement. In the vast
majority of usages, adding them is a premature optimization.