将稀疏的scipy矩阵切片为每10行和每列的子采样

时间:2013-10-14 20:08:19

标签: python numpy sparse-matrix slice subsampling

我试图将scipy稀疏矩阵子样本化为像这样的numpy矩阵,以获得每10行和每10列:

connections = sparse.csr_matrix((data,(node1_index,node2_index)),
                                shape=(dimensions,dimensions))
connections_sampled = np.zeros((dimensions/10, dimensions/10))
connections_sampled = connections[::10,::10]

然而,当我运行这个并查询connections_sampled的形状时,我得到连接的原始尺寸而不是减少了10倍的尺寸。

这种类型的子采样现在适用于稀疏矩阵吗?当我使用较小的矩阵时,它似乎有效,但我无法得到正确的答案。

1 个答案:

答案 0 :(得分:3)

您不能对CSR矩阵的每第10行和每列进行采样,至少不能在Scipy 0.12中采样:

>>> import scipy.sparse as sps
>>> a = sps.rand(1000, 1000, format='csr')
>>> a[::10, ::10]
Traceback (most recent call last):
...    
ValueError: slicing with step != 1 not supported

但是,您可以通过首先转换为LIL格式矩阵来实现:

>>> a.tolil()[::10, ::10]
<100x100 sparse matrix of type '<type 'numpy.float64'>'
    with 97 stored elements in LInked List format>

如您所见,形状已正确更新。如果你想要一个numpy数组,而不是稀疏矩阵,请尝试:

>>> a.tolil()[::10, ::10].A
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ..., 
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])