scipy sparse matrix to cvxopt spmatrix?

。_饼干妹妹 提交于 2020-01-23 06:31:25

问题


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?


回答1:


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.




回答2:


taken from http://maggotroot.blogspot.co.il/2013/11/constrained-linear-least-squares-in.html

coo = A.tocoo()
SP = spmatrix(coo.data, coo.row.tolist(), coo.col.tolist())



回答3:


From http://cvxopt.org/userguide/matrices.html#sparse-matrices

cvxopt.spmatrix(x, I, J[, size[, tc]])

looks similar to the scipy.sparse

coo_matrix((data, (i, j)), [shape=(M, N)])

My guess is that if A is a matrix in coo format, that

cvxopt.spmatrix(A.data, A.row, A.col, A.shape)

would work. (I don't have cvxopt installed to test this.)



来源:https://stackoverflow.com/questions/25314067/scipy-sparse-matrix-to-cvxopt-spmatrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!