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?
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.
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).
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.
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.
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