繁体   English   中英

对第10行和第10列的切片稀疏矩阵进行子采样

[英]Slicing a sparse scipy matrix to subsample for every 10th row and column

我正在尝试像这样的numpy矩阵对scipy稀疏矩阵进行二次采样,以获取第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倍的尺寸。

这种类型的子采样现在适用于稀疏矩阵吗? 当我使用较小的矩阵时,这似乎可以工作,但是我无法给出正确的答案。

您不能对CSR矩阵的第10行和第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.]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM