sparse.base

Base class for sparse matrices

Module Contents

Classes

SparseWarning()
SparseFormatWarning()
SparseEfficiencyWarning()
spmatrix(self,maxprint=MAXPRINT) This class provides a base class for all sparse matrices. It

Functions

isspmatrix(x) Is x of a sparse matrix type?
class SparseWarning
class SparseFormatWarning
class SparseEfficiencyWarning
class spmatrix(maxprint=MAXPRINT)

This class provides a base class for all sparse matrices. It cannot be instantiated. Most of the work is provided by subclasses.

__init__(maxprint=MAXPRINT)
set_shape(shape)

See reshape.

get_shape()

Get shape of a matrix.

reshape(shape, order="C")

Gives a new shape to a sparse matrix without changing its data.

shape : length-2 tuple of ints
The new shape should be compatible with the original shape.
order : ‘C’, optional
This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used.

reshaped_matrix : self with the new dimensions of shape

np.matrix.reshape : NumPy’s implementation of ‘reshape’ for matrices

astype(dtype, casting="unsafe", copy=True)

Cast the matrix elements to a specified type.

dtype : string or numpy dtype
Typecode or data-type to which to cast the data.
casting : {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility. ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done.
copy : bool, optional
If copy is False, the result might share some memory with this matrix. If copy is True, it is guaranteed that the result and this matrix do not share any memory.
asfptype()

Upcast matrix to a floating point format (if necessary)

__iter__()
getmaxprint()

Maximum number of elements to display when printed.

count_nonzero()

Number of non-zero entries, equivalent to

np.count_nonzero(a.toarray())

Unlike getnnz() and the nnz property, which return the number of stored entries (the length of the data attribute), this method counts the actual number of non-zero entries in data.

getnnz(axis=None)

Number of stored values, including explicit zeros.

axis : None, 0, or 1
Select between the number of values across the whole matrix, in each column, or in each row.

count_nonzero : Number of non-zero entries

nnz()

Number of stored values, including explicit zeros.

count_nonzero : Number of non-zero entries

getformat()

Format of a matrix representation as a string.

__repr__()
__str__()
__bool__()
__len__()
asformat(format)

Return this matrix in a given sparse format

format : {string, None}
desired sparse matrix format
  • None for no format conversion
  • “csr” for csr_matrix format
  • “csc” for csc_matrix format
  • “lil” for lil_matrix format
  • “dok” for dok_matrix format and so on
multiply(other)

Point-wise multiplication by another matrix

maximum(other)

Element-wise maximum between this and another matrix.

minimum(other)

Element-wise minimum between this and another matrix.

dot(other)

Ordinary dot product

>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> v = np.array([1, 0, -1])
>>> A.dot(v)
array([ 1, -3, -1], dtype=int64)
power(n, dtype=None)

Element-wise power.

__eq__(other)
__ne__(other)
__lt__(other)
__gt__(other)
__le__(other)
__ge__(other)
__abs__()
_add_sparse(other)
_add_dense(other)
_sub_sparse(other)
_sub_dense(other)
_rsub_dense(other)
__add__(other)
__radd__(other)
__sub__(other)
__rsub__(other)
__mul__(other)

interpret other and call one of the following

self._mul_scalar() self._mul_vector() self._mul_multivector() self._mul_sparse_matrix()

_mul_scalar(other)
_mul_vector(other)
_mul_multivector(other)
_mul_sparse_matrix(other)
__rmul__(other)
__matmul__(other)
__rmatmul__(other)
_divide(other, true_divide=False, rdivide=False)
__truediv__(other)
__div__(other)
__rtruediv__(other)
__rdiv__(other)
__neg__()
__iadd__(other)
__isub__(other)
__imul__(other)
__idiv__(other)
__itruediv__(other)
__pow__(other)
__getattr__(attr)
transpose(axes=None, copy=False)

Reverses the dimensions of the sparse matrix.

axes : None, optional
This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value.
copy : bool, optional
Indicates whether or not attributes of self should be copied whenever possible. The degree to which attributes are copied varies depending on the type of sparse matrix being used.

p : self with the dimensions reversed.

np.matrix.transpose : NumPy’s implementation of ‘transpose’
for matrices
conj()

Element-wise complex conjugation.

If the matrix is of non-complex data type, then this method does nothing and the data is not copied.

conjugate()
getH()

Return the Hermitian transpose of this matrix.

np.matrix.getH : NumPy’s implementation of getH for matrices

_real()
_imag()
nonzero()

nonzero indices

Returns a tuple of arrays (row,col) containing the indices of the non-zero elements of the matrix.

>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix([[1,2,0],[0,0,3],[4,0,5]])
>>> A.nonzero()
(array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))
getcol(j)

Returns a copy of column j of the matrix, as an (m x 1) sparse matrix (column vector).

getrow(i)

Returns a copy of row i of the matrix, as a (1 x n) sparse matrix (row vector).

todense(order=None, out=None)

Return a dense matrix representation of this matrix.

order : {‘C’, ‘F’}, optional
Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. The default is ‘None’, indicating the NumPy default of C-ordered. Cannot be specified in conjunction with the out argument.
out : ndarray, 2-dimensional, optional
If specified, uses this array (or numpy.matrix) as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse matrix on which you are calling the method.
arr : numpy.matrix, 2-dimensional
A NumPy matrix object with the same shape and containing the same data represented by the sparse matrix, with the requested memory order. If out was passed and was an array (rather than a numpy.matrix), it will be filled with the appropriate values and returned wrapped in a numpy.matrix object that shares the same memory.
toarray(order=None, out=None)

Return a dense ndarray representation of this matrix.

order : {‘C’, ‘F’}, optional
Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. The default is ‘None’, indicating the NumPy default of C-ordered. Cannot be specified in conjunction with the out argument.
out : ndarray, 2-dimensional, optional
If specified, uses this array as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse matrix on which you are calling the method. For most sparse types, out is required to be memory contiguous (either C or Fortran ordered).
arr : ndarray, 2-dimensional
An array with the same shape and containing the same data represented by the sparse matrix, with the requested memory order. If out was passed, the same object is returned after being modified in-place to contain the appropriate values.
tocsr(copy=False)

Convert this matrix to Compressed Sparse Row format.

With copy=False, the data/indices may be shared between this matrix and the resultant csr_matrix.

todok(copy=False)

Convert this matrix to Dictionary Of Keys format.

With copy=False, the data/indices may be shared between this matrix and the resultant dok_matrix.

tocoo(copy=False)

Convert this matrix to COOrdinate format.

With copy=False, the data/indices may be shared between this matrix and the resultant coo_matrix.

tolil(copy=False)

Convert this matrix to LInked List format.

With copy=False, the data/indices may be shared between this matrix and the resultant lil_matrix.

todia(copy=False)

Convert this matrix to sparse DIAgonal format.

With copy=False, the data/indices may be shared between this matrix and the resultant dia_matrix.

tobsr(blocksize=None, copy=False)

Convert this matrix to Block Sparse Row format.

With copy=False, the data/indices may be shared between this matrix and the resultant bsr_matrix.

When blocksize=(R, C) is provided, it will be used for construction of the bsr_matrix.

tocsc(copy=False)

Convert this matrix to Compressed Sparse Column format.

With copy=False, the data/indices may be shared between this matrix and the resultant csc_matrix.

copy()

Returns a copy of this matrix.

No data/indices will be shared between the returned value and current matrix.

sum(axis=None, dtype=None, out=None)

Sum the matrix elements over a given axis.

axis : {-2, -1, 0, 1, None} optional
Axis along which the sum is computed. The default is to compute the sum of all the matrix elements, returning a scalar (i.e. axis = None).
dtype : dtype, optional
The type of the returned matrix and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
out : np.matrix, optional
Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
sum_along_axis : np.matrix
A matrix with the same shape as self, with the specified axis removed.

np.matrix.sum : NumPy’s implementation of ‘sum’ for matrices

mean(axis=None, dtype=None, out=None)

Compute the arithmetic mean along the specified axis.

Returns the average of the matrix elements. The average is taken over all elements in the matrix by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

axis : {-2, -1, 0, 1, None} optional
Axis along which the mean is computed. The default is to compute the mean of all elements in the matrix (i.e. axis = None).
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.
out : np.matrix, optional
Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

m : np.matrix

np.matrix.mean : NumPy’s implementation of ‘mean’ for matrices

diagonal(k=0)

Returns the k-th diagonal of the matrix.

k : int, optional
Which diagonal to set, corresponding to elements a[i, i+k]. Default: 0 (the main diagonal).

numpy.diagonal : Equivalent numpy function.

>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> A.diagonal()
array([1, 0, 5])
>>> A.diagonal(k=1)
array([2, 3])
setdiag(values, k=0)

Set diagonal or off-diagonal elements of the array.

values : array_like

New values of the diagonal elements.

Values may have any length. If the diagonal is longer than values, then the remaining diagonal entries will not be set. If values if longer than the diagonal, then the remaining values are ignored.

If a scalar value is given, all of the diagonal is set to it.

k : int, optional
Which off-diagonal to set, corresponding to elements a[i,i+k]. Default: 0 (the main diagonal).
_setdiag(values, k)
_process_toarray_args(order, out)
__numpy_ufunc__(func, method, pos, inputs, **kwargs)

Method for compatibility with NumPy’s ufuncs and dot functions.

isspmatrix(x)

Is x of a sparse matrix type?

x
object to check for being a sparse matrix
bool
True if x is a sparse matrix, False otherwise

issparse and isspmatrix are aliases for the same function.

>>> from scipy.sparse import csr_matrix, isspmatrix
>>> isspmatrix(csr_matrix([[5]]))
True
>>> from scipy.sparse import isspmatrix
>>> isspmatrix(5)
False