Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scipy sparse matrix to cvxopt spmatrix?

I need to convert a scipy sparse matrix to cvxopt's sparse matrix format, spmatrix, and haven't come across anything yet (the matrix is too big to be converted to dense, of course). Any ideas how to do this?

like image 358
Elizabeth Orrico Avatar asked Aug 14 '14 17:08

Elizabeth Orrico


People also ask

How do you transpose a sparse matrix?

If we come across an element with the same row and column value, we simply add their values and insert the added data into the resultant matrix. To Transpose a matrix, we can simply change every column value to the row value and vice-versa, however, in this case, the resultant matrix won't be sorted as we require.

How do SciPy sparse matrices multiply?

We use the multiply() method provided in both csc_matrix and csr_matrix classes to multiply two sparse matrices. We can multiply two matrices of same format( both matrices are csc or csr format) and also of different formats ( one matrix is csc and other is csr format).

How does SciPy sparse matrix work?

Python's SciPy provides tools for creating sparse matrices using multiple data structures, as well as tools for converting a dense matrix to a sparse matrix. The sparse matrix representation outputs the row-column tuple where the matrix contains non-zero values along with those values.


1 Answers

The more robust answer is a combination of hpaulj's answer and OferHelman's answer.

def scipy_sparse_to_spmatrix(A):
    coo = A.tocoo()
    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
    return SP

Defining the shape variable preserves the dimensionality of A on SP. I found that any zero columns ending the scipy sparse matrix would be lost without this added step.

like image 78
Mtap1 Avatar answered Sep 28 '22 03:09

Mtap1