is it possible to stack a sparse and a dense numpy array in python? I know this can be done for dense numpy arrays using vstack/hstack. I have some columns that I would like to add to a sparse matrix in order to increase the number of feature vectors
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.
1 Answer. You can use either todense() or toarray() function to convert a CSR matrix to a dense matrix.
Operations using standard dense-matrix structures and algorithms are slow and inefficient when applied to large sparse matrices as processing and memory are wasted on the zeros. Sparse data is by nature more easily compressed and thus requires significantly less storage.
The density of a matrix is the number of non-zero elements divided by the total number of matrix elements. Matrices with very low density are often good candidates for use of the sparse format. Converting Full to Sparse. You can convert a full matrix to sparse storage using the sparse function with a single argument.
Yes, you can use scipy.sparse.vstack
and scipy.sparse.hstack
, in the same way as you would use numpy.vstack
and numpy.hstack
for dense arrays.
Example:
from scipy.sparse import coo_matrix
m = coo_matrix(np.array([[0,0,1],[1,0,0],[1,0,0]]))
a = np.ones(m.shape)
With np.vstack
:
np.vstack((a,m))
#ValueError: all the input array dimensions except for the concatenation axis must match exactly
With scipy.sparse.vstack
:
scipy.sparse.vstack((a,m))
#<6x3 sparse matrix of type '<type 'numpy.float64'>'
# with 12 stored elements in COOrdinate format>
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