python - 将稀疏 scipy 矩阵切片以每 10 行和 10 列进行子采​​样

标签 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 倍的尺寸。

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

最佳答案

你不能对 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.]])

关于python - 将稀疏 scipy 矩阵切片以每 10 行和 10 列进行子采​​样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19368414/

相关文章:

python - 将一个 NumPy 数组除以另一个 NumPy 数组

c++ - 如何在 C++ 中针对稀疏矩阵优化 Gauss-Seidel 例程?

python - 对数缩放(应用函数?)稀疏矩阵

python - pipenv:如何解决依赖冲突

python - 如何获取通常在 Django 中递增的字段的默认值?

python - 在 Matplotlib 中自定义复选按钮

python - 如何从更大的稀疏矩阵的 block 总和中有效地创建新矩阵

python - 如何读取多个数据集,并创建具有年份列的单个数据框

python - 根据 HSV 色调范围将选定像素转为黑色

python - 如何计算滚动窗口中数据框的列中相同实例的数量