我正在尝试将 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/