有效改变 scipy.spare.csr_matrix 的维度

Effectively change dimension of scipy.spare.csr_matrix

我有一个函数接受 csr_matrix 并对其进行一些计算。

这些计算的行为要求这个矩阵的形状是特定的(比如 NxM)。

我发送的输入有较少的列和准确的行数。

(例如它的形状=(A,B),其中 A < N 且 B == M)

例如:我有对象x

>>>x = csr_matrix([[1,2],[1,2]])
>>>x
(0, 0)  1
(0, 1)  2
(1, 0)  1
(1, 1)  2
>>>x.shape
(2, 2)

还有一个函数f:

def f(csr_mat):
    """csr_mat.shape should be (2,3)"""

然后我想在x上做点什么,所以会变成y:

>>>y = csr_matrix([[1,2,0],[1,2,0]])
>>>y
(0, 0)  1
(0, 1)  2
(1, 0)  1
(1, 1)  2
>>>y.shape
(2, 3)

在此示例中,xy 具有相同的 none-零值,但 y 具有不同的形状。我想要的是有效地 'extend' x 到一个新的维度,用零填充新的列。即,给定 xnew_shape=(2,3),它应该 return y.
我已经试过了 reshape:

x.reshape((2,3))

但后来我得到了:

NotImplementedError

我的第二个选择是创建具有不同形状的新 csr_matrix

z = csr_matrix(x,shape=(3,3))

但这也失败了:

NotImplementedError: Reshaping not implemented for csr_matrix.

编辑:使用 csc_matrix 带来了同样的错误。

有什么想法吗?

谢谢

在 CSR 格式中,所需 y 的基础 dataindicesindptr 数组与 x 的数组相同矩阵。您可以使用新的 shape:

将它们传递给 csr_matrix 构造函数
y = csr_matrix((x.data, x.indices, x.indptr), shape=(2, 3))

请注意,构造函数默认为 copy=False,因此这将在 x 和 [=15] 之间共享 dataindicesindptr =]. y 上的某些操作将反映在 x 中。您可以通过 copy=True 使 xy 相互独立。

如果您想查看 csr_matrix 未记录的内部结构,您可以设置内部 _shape 属性以使 x 数组具有您想要的形状:

x._shape = (2, 3)

这样做并没有真正的优势。