【问题标题】:Slicing a sparse scipy matrix to subsample for every 10th row and column对稀疏 scipy 矩阵进行切片以对每 10 行和每列进行二次采样
【发布时间】:2013-10-22 12:01:59
【问题描述】:

我正在尝试将 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 倍的尺寸。

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

【问题讨论】:

    标签: python numpy sparse-matrix slice subsampling


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 2015-07-28
      • 2011-11-28
      • 1970-01-01
      • 2017-01-22
      • 2015-08-24
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多