There does not seem to be a method in scipy.sparse which gives the minimum of a sparse matrix. In particular, I seek the minimum of the columns.
No method appears in the docs and numpy minimum does not apply. If X
is a sparse matrix, X.min()
also throws the error: *** AttributeError: 'module' object has no attribute 'min'
.
Surely this must be something people use. How is this done?
The above sparse matrix contains only 9 non-zero elements, with 26 zero elements. Its sparsity is 74%, and its density is 26%. In numerical analysis and scientific computing, a sparse matrix or sparse array is a matrix in which most of the elements are zero.
A sparse matrix is a matrix that is comprised of mostly zero values. Sparse matrices are distinct from matrices with mostly non-zero values, which are referred to as dense matrices. A matrix is sparse if many of its coefficients are zero.
To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true.
The function csr_matrix() is used to create a sparse matrix of compressed sparse row format whereas csc_matrix() is used to create a sparse matrix of compressed sparse column format.
With CSR/CSC matrices, use
def min_sparse(X):
if len(X.data) == 0:
return 0
m = X.data.min()
return m if X.getnnz() == X.size else min(m, 0)
To do this per row or column, you can map
this over X.getrow(i) for i in X.shape[0]
or X.shape[1]
.
But you're right, this should be a method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With