将 scipy.sparse() 稀疏矩阵输入 CVXOPT

Feeding scipy.sparse() sparse matrices into CVXOPT

[我正在关注答案 here]

我正在尝试在 CVXOPT 中提供稀疏矩阵。考虑以下最小示例:

import numpy
import cvxopt
import scipy.sparse

K = 10
n = 36

g_0 = numpy.random.randn(n, K)
d_0 = numpy.zeros(n) + 1.0
g_2 = scipy.sparse.dia_matrix(([d_0], [0]), shape=(n, n))
g_3 = scipy.sparse.dia_matrix(([-d_0], [0]), shape=(n, n))
g_1 = scipy.sparse.coo_matrix(g_0)
g_4 = scipy.sparse.hstack([g_1, g_2, g_3])

A   = cvxopt.spmatrix(g_4.data.tolist(), g_4.col.tolist(), g_4.row.tolist(), size = g_4.shape)

我得到:

TypeError: dimension too small

这是错误还是(更有可能)我误解了 this 答案?

您刚刚在矩阵创建调用期间将参数中的行列顺序切换为列行顺序。

这与大小g_4.shape的参数冲突。看看cvxopt's docs。大小首先处理,I(第二个参数),然后是 J(第三个参数)。

A   = cvxopt.spmatrix(g_4.data.tolist(), g_4.col.tolist(), g_4.row.tolist(), size = g_4.shape)  # wrong
A   = cvxopt.spmatrix(g_4.data.tolist(), g_4.row.tolist(), g_4.col.tolist(), size = g_4.shape)  # correct