【问题标题】:Sparse arrays from tuples来自元组的稀疏数组
【发布时间】:2013-12-06 05:48:25
【问题描述】:

我在网上搜索了 Scipy 稀疏矩阵的指南,但失败了。如果有人愿意分享它的任何来源,我会很高兴,但现在要质疑:

我有一个元组数组。我想将元组数组更改为稀疏矩阵,其中元组出现在主对角线和旁边的对角线上,如下例所示。什么是花哨(高效)的方法?

import numpy as np
A=np.asarray([[1,2],[3,4],[5,6],[7,8]])
B=np.zeros((A.shape[0],A.shape[0]+1))
for i in range(A.shape[0]):
    B[i,i]=A[i,0]
    B[i,i+1]=A[i,1]
print B

输出是:

[[ 1.  2.  0.  0.  0.]
 [ 0.  3.  4.  0.  0.]
 [ 0.  0.  5.  6.  0.]
 [ 0.  0.  0.  7.  8.]]

【问题讨论】:

  • 这可能是我猜的最愚蠢的方式。
  • scipy sparse 包的主要信息来源是它的参考页面:docs.scipy.org/doc/scipy/reference/sparse.html。然而,这不是一个精致的用户或初学者指南。请记住,此软件包仍在开发中。 Matlab 的稀疏矩阵可能有更好的文档。

标签: python arrays numpy scipy sparse-matrix


【解决方案1】:

试试diags from scipy

import numpy as np
import scipy.sparse

A = np.asarray([[1,2],[3,4],[5,6],[7,8]])
B = scipy.sparse.diags([A[:,0], A[:,1]], [0, 1], [4, 5])

当我print B.todense()时,它给了我

[[ 1.  2.  0.  0.  0.]
 [ 0.  3.  4.  0.  0.]
 [ 0.  0.  5.  6.  0.]
 [ 0.  0.  0.  7.  8.]]

【讨论】:

  • 更简洁:sparse.diags(A.T,[0,1],(4,5)).A
【解决方案2】:

您可以将它们构建为一个 CSR 矩阵,速度非常快:

>>> A = np.asarray([[1,2],[3,4],[5,6],[7,8]])
>>> rows = len(A)
>>> cols = rows + 1
>>> data = A.flatten() # we want a copy
>>> indptr = np.arange(0, len(data)+1, 2) # 2 non-zero entries per row
>>> indices = np.repeat(np.arange(cols), [1] + [2] * (cols-2) + [1])
>>> import scipy.sparse as sps
>>> a_sps = sps.csr_matrix((data, indices, indptr), shape=(rows, cols))
>>> a_sps.A
array([[1, 2, 0, 0, 0],
       [0, 3, 4, 0, 0],
       [0, 0, 5, 6, 0],
       [0, 0, 0, 7, 8]])

【讨论】:

  • 非常感谢。如果你知道的话,能否请你也给我这个稀疏矩阵的来源。
  • wikipedia page on sparse matrices 是了解这三个数组(dataindicesindptr)是什么的一个很好的起点。了解它们通常可以非常快速地完成(至少目前)超出sipy.sparse API 的事情。
猜你喜欢
  • 2021-03-01
  • 2019-07-10
  • 2012-06-20
  • 2018-08-22
  • 2011-02-02
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多