Sparse arrays (scipy.sparse
)#
SciPy 2-D sparse array package for numeric data.
Note
This package is switching to an array interface, compatible with
NumPy arrays, from the older matrix interface. We recommend that
you use the array objects (bsr_array
, coo_array
, etc.) for
all new work.
When using the array interface, please note that:
x * y
no longer performs matrix multiplication, but element-wise multiplication (just like with NumPy arrays). To make code work with both arrays and matrices, usex @ y
for matrix multiplication.Operations such as
sum
, that used to produce dense matrices, now produce arrays, whose multiplication behavior differs similarly.Sparse arrays use array style slicing operations, returning scalars, 1D, or 2D sparse arrays. If you need 2D results, use an appropriate index. E.g.
A[:, i, None]
orA[:, [i]]
.
The construction utilities (eye
, kron
, random
, diags
, etc.)
have appropriate replacements (see Building sparse arrays).
For more information see Migration from spmatrix to sparray.
Submodules#
Sparse array classes#
|
Block Sparse Row format sparse array. |
|
A sparse array in COOrdinate format. |
|
Compressed Sparse Column array. |
|
Compressed Sparse Row array. |
|
Sparse array with DIAgonal storage. |
|
Dictionary Of Keys based sparse array. |
|
Row-based LIst of Lists sparse array. |
|
This class provides a base class for all sparse arrays. |
Building sparse arrays#
|
Construct a sparse array from diagonals. |
|
Identity matrix in sparse array format |
|
Return a sparse array of uniformly random numbers in [0, 1) |
|
Build a sparse array from sparse sub-blocks |
Combining arrays#
|
kronecker product of sparse matrices A and B |
|
kronecker sum of square sparse matrices A and B |
|
Build a block diagonal sparse matrix or array from provided matrices. |
|
Return the lower triangular portion of a sparse array or matrix |
|
Return the upper triangular portion of a sparse array or matrix |
|
Stack sparse matrices horizontally (column wise) |
|
Stack sparse arrays vertically (row wise) |
Sparse tools#
|
Save a sparse matrix or array to a file using |
|
Load a sparse array/matrix from a file using |
|
Return the indices and values of the nonzero elements of a matrix |
|
Based on input (integer) arrays a, determine a suitable index data type that can hold the data in the arrays. |
|
Safely cast sparse array indices to idx_dtype. |
Identifying sparse arrays#
|
Is x of a sparse array or sparse matrix type? |
Sparse matrix classes#
|
Block Sparse Row format sparse matrix. |
|
A sparse matrix in COOrdinate format. |
|
Compressed Sparse Column matrix. |
|
Compressed Sparse Row matrix. |
|
Sparse matrix with DIAgonal storage. |
|
Dictionary Of Keys based sparse matrix. |
|
Row-based LIst of Lists sparse matrix. |
|
This class provides a base class for all sparse matrix classes. |
Building sparse matrices#
|
Sparse matrix with ones on diagonal |
|
Identity matrix in sparse format |
|
Construct a sparse matrix from diagonals. |
|
Return a sparse matrix from diagonals. |
|
Build a sparse array or matrix from sparse sub-blocks |
|
Generate a sparse matrix of the given shape and density with randomly distributed values. |
|
Generate a sparse matrix of the given shape and density with uniformly distributed values. |
Combining matrices use the same functions as for Combining arrays.
Identifying sparse matrices#
|
Is x of a sparse array or sparse matrix type? |
|
Is x of a sparse matrix type? |
Is x of csc_matrix type? |
|
Is x of csr_matrix type? |
|
Is x of a bsr_matrix type? |
|
Is x of lil_matrix type? |
|
Is x of dok_array type? |
|
Is x of coo_matrix type? |
|
Is x of dia_matrix type? |
Warnings#
Usage information#
There are seven available sparse array types:
csc_array: Compressed Sparse Column format
csr_array: Compressed Sparse Row format
bsr_array: Block Sparse Row format
lil_array: List of Lists format
dok_array: Dictionary of Keys format
coo_array: COOrdinate format (aka IJV, triplet format)
dia_array: DIAgonal format
To construct an array efficiently, use any of coo_array
,
dok_array
or lil_array
. dok_array
and lil_array
support basic slicing and fancy indexing with a similar syntax
to NumPy arrays. The COO format does not support indexing (yet)
but can also be used to efficiently construct arrays using coord
and value info.
Despite their similarity to NumPy arrays, it is strongly discouraged to use NumPy functions directly on these arrays because NumPy typically treats them as generic Python objects rather than arrays, leading to unexpected (and incorrect) results. If you do want to apply a NumPy function to these arrays, first check if SciPy has its own implementation for the given sparse array class, or convert the sparse array to a NumPy array (e.g., using the toarray method of the class) before applying the method.
All conversions among the CSR, CSC, and COO formats are efficient, linear-time operations.
To perform manipulations such as multiplication or inversion, first
convert the array to either CSC or CSR format. The lil_array
format is row-based, so conversion to CSR is efficient, whereas
conversion to CSC is less so.
Matrix vector product#
To do a vector product between a 2D sparse array and a vector use
the matmul operator (i.e., @
) which performs a dot product (like the
dot
method):
>>> import numpy as np
>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> v = np.array([1, 0, -1])
>>> A @ v
array([ 1, -3, -1], dtype=int64)
The CSR format is especially suitable for fast matrix vector products.
Example 1#
Construct a 1000x1000 lil_array
and add some values to it:
>>> from scipy.sparse import lil_array
>>> from scipy.sparse.linalg import spsolve
>>> from numpy.linalg import solve, norm
>>> from numpy.random import rand
>>> A = lil_array((1000, 1000))
>>> A[0, :100] = rand(100)
>>> A.setdiag(rand(1000))
Now convert it to CSR format and solve A x = b for x:
>>> A = A.tocsr()
>>> b = rand(1000)
>>> x = spsolve(A, b)
Convert it to a dense array and solve, and check that the result is the same:
>>> x_ = solve(A.toarray(), b)
Now we can compute norm of the error with:
>>> err = norm(x-x_)
>>> err < 1e-10
True
It should be small :)
Example 2#
Construct an array in COO format:
>>> from scipy import sparse
>>> from numpy import array
>>> I = array([0,3,1,0])
>>> J = array([0,3,1,2])
>>> V = array([4,5,7,9])
>>> A = sparse.coo_array((V,(I,J)),shape=(4,4))
Notice that the indices do not need to be sorted.
Duplicate (i,j) entries are summed when converting to CSR or CSC.
>>> I = array([0,0,1,3,1,0,0])
>>> J = array([0,2,1,3,1,0,0])
>>> V = array([1,1,1,1,1,1,1])
>>> B = sparse.coo_array((V,(I,J)),shape=(4,4)).tocsr()
This is useful for constructing finite-element stiffness and mass matrices.
Further details#
CSR column indices are not necessarily sorted. Likewise for CSC row
indices. Use the .sorted_indices()
and .sort_indices()
methods when
sorted indices are required (e.g., when passing data to other libraries).