Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stacking sparse and dense matrices

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

like image 328
Abhishek Thakur Avatar asked Aug 24 '13 11:08

Abhishek Thakur


People also ask

What is the difference between sparse and dense matrix?

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.

How do you make a sparse matrix dense?

1 Answer. You can use either todense() or toarray() function to convert a CSR matrix to a dense matrix.

Why is sparse matrix important than 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.

What is density in sparse matrix?

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.


1 Answers

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>
like image 199
Saullo G. P. Castro Avatar answered Oct 12 '22 10:10

Saullo G. P. Castro