从 x_index、y_index、值创建 CSR 矩阵

Create CSR matrix from x_index, y_index, value

我有 (x_index, y_index, value) 格式的数据,我正在尝试使用 scipy (scipy.sparse.csr.csr_matrix) 创建 CSR 矩阵。

例如,转换:

0 0 10
0 1 5
1 0 3
1 1 4

以下内容:

10 5
3  4

我已阅读此处的文档:http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

但是我仍然不清楚哪些示例适用于我的用例。

如果可以将输入数据分成一系列行索引、一系列列索引和相应的值索引序列,则可以使用 csr_matrix 文档字符串中显示的第四个选项来创建矩阵.

例如,假设您已经将数据放在一个数组中,data, 其中前两列是索引,第三列包含值。例如

In [213]: data
Out[213]: 
array([[ 0,  0, 10],
       [ 0,  1,  5],
       [ 1,  0,  3],
       [ 1,  1,  4]])

然后您可以创建一个 CSR 矩阵,如下所示:

In [214]: a = csr_matrix((data[:, 2], (data[:, 0], data[:, 1])))

In [215]: a
Out[215]: 
<2x2 sparse matrix of type '<type 'numpy.int64'>'
    with 4 stored elements in Compressed Sparse Row format>

In [216]: a.A
Out[216]: 
array([[10,  5],
       [ 3,  4]])

根据您的数据,您可能需要明确指定形状。例如,这里我使用相同的数据,但在 3x3 矩阵中:

In [217]: b = csr_matrix((data[:, 2], (data[:, 0], data[:, 1])), shape=(3, 3))

In [218]: b
Out[218]: 
<3x3 sparse matrix of type '<type 'numpy.int64'>'
    with 4 stored elements in Compressed Sparse Row format>

In [219]: b.A
Out[219]: 
array([[10,  5,  0],
       [ 3,  4,  0],
       [ 0,  0,  0]])