让我们做一个小的演示 csr 矩阵:
In [212]: M = (sparse.random(12,3,.5, 'csr')*10).astype(int)
In [213]: M
Out[213]:
<12x3 sparse matrix of type '<class 'numpy.int64'>'
with 18 stored elements in Compressed Sparse Row format>
In [214]: M.A
Out[214]:
array([[3, 1, 3],
[0, 0, 1],
[1, 0, 9],
[0, 6, 0],
[5, 4, 0],
[4, 5, 6],
[3, 0, 0],
[0, 0, 5],
[0, 0, 2],
[0, 1, 0],
[0, 0, 0],
[0, 9, 0]])
您的分组会生成一个小型 csr 矩阵列表
In [216]: alist = [M[i::3] for i in range(3)]
In [217]: alist
Out[217]:
[<4x3 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in Compressed Sparse Row format>,
<4x3 sparse matrix of type '<class 'numpy.int64'>'
with 4 stored elements in Compressed Sparse Row format>,
<4x3 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in Compressed Sparse Row format>]
看K案例:
In [218]: data = []
In [219]: data.extend(alist[2])
In [220]: data
Out[220]:
[<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 1 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 1 stored elements in Compressed Sparse Row format>]
List extend 将可迭代的元素添加到列表中(在“平面”意义上)。稀疏矩阵 (alist[2]) 上的迭代会产生一堆 1 行稀疏矩阵(仍然是 2d)。
我们可以使用sparse.vstack加入他们:
In [221]: sparse.vstack(data)
Out[221]:
<4x3 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in Compressed Sparse Row format>
In [222]: sparse.vstack(data).A
Out[222]:
array([[1, 0, 9],
[4, 5, 6],
[0, 0, 2],
[0, 9, 0]])
这与子矩阵的来源相同。
In [223]: alist[2]
Out[223]:
<4x3 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in Compressed Sparse Row format>
In [224]: alist[2].A
Out[224]:
array([[1, 0, 9],
[4, 5, 6],
[0, 0, 2],
[0, 9, 0]])
将data 列表放入array 只会生成一个包含 1 行稀疏矩阵的 1d 对象 dtype 数组。矩阵只是np.array 的外来对象。作为一般规则,不要指望numpy 函数使用稀疏矩阵做“正确”的事情。
In [225]: np.array(data)
Out[225]:
array([<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 1 stored elements in Compressed Sparse Row format>,
<1x3 sparse matrix of type '<class 'numpy.int64'>'
with 1 stored elements in Compressed Sparse Row format>], dtype=object)
不要只看形状。检查dtype,并检查一些元素!