【问题标题】:How to convert a numpy array dtype=object to a sparse matrix?如何将 numpy 数组 dtype=object 转换为稀疏矩阵?
【发布时间】:2019-04-27 01:06:02
【问题描述】:

我有一个 dtype = object 的 numpy 数组,其中包含多个其他元素数组,我需要将其转换为稀疏矩阵。

例如:

a = np.array([np.array([1,0,2]),np.array([1,3])])
array([array([1, 0, 2]), array([1, 3])], dtype=object)

我尝试了Convert numpy object array to sparse matrix给出的解决方案,没有成功。

In [45]: M=sparse.coo_matrix(a)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-45-d75020bb3a38> in <module>()
----> 1 M=sparse.coo_matrix(a)

/home/arturcastiel/.local/lib/python3.6/site-packages/scipy/sparse/coo.py in __init__(self, arg1, shape, dtype, copy)
    183                     self._shape = check_shape(M.shape)
    184 
--> 185                 self.row, self.col = M.nonzero()
    186                 self.data = M[self.row, self.col]
    187                 self.has_canonical_format = True

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

正如在 cmets 上所解释的,这实际上是一个锯齿状数组。 本质上,这个数组表示一个图,我必须将其转换为稀疏矩阵,以便我可以使用 scipy.sparse.csgraph.shortest_path 例程。

因此,

np.array([np.array([1,0,2]),np.array([1,3])])

应该变成这样的:

(1,1) 1
(1,2) 0
(1,3) 2
(2,1) 1
(2,2) 3

【问题讨论】:

  • 最终矩阵的形状应该是什么?第二个数组的数字1, 3 应该有什么坐标?
  • 你有一个参差不齐的数组,很多方法都不能满足这个要求

标签: python numpy scipy


【解决方案1】:

你不能。当它试图找到a 的非零元素时会出现此错误。稀疏矩阵只存储矩阵的非零元素。试试

np.nonzero(a)  

如果您的数组包含列表而不是数组,它会起作用 - 有点:

In [615]: a = np.array([[1,0,1],[1,3]])                                              
In [616]: np.nonzero(a)                                                              
Out[616]: (array([0, 1]),)

In [618]: sparse.coo_matrix(a)                                                       
Out[618]: 
<1x2 sparse matrix of type '<class 'numpy.object_'>'
    with 2 stored elements in COOrdinate format>
In [619]: print(_)                                                                   
  (0, 0)    [1, 0, 1]
  (0, 1)    [1, 3]

注意这是一个 (1,2) 形状的数组,有 2 个非零元素,它们都是原始的列表(对象)。

但是coo 格式几乎没有处理。例如,它不能转换为 csr 进行计算:

In [622]: _618.tocsr()                                                               
---------------------------------------------------------------------------
TypeError: no supported conversion for types: (dtype('O'),)

如果数组不是锯齿状的,它可以做成一个有用的稀疏矩阵:

In [623]: a = np.array([[1,0,1],[1,3,0]])                                            
In [624]: a                                                                          
Out[624]: 
array([[1, 0, 1],
       [1, 3, 0]])

In [626]: sparse.coo_matrix(a)                                                       
Out[626]: 
<2x3 sparse matrix of type '<class 'numpy.int64'>'
    with 4 stored elements in COOrdinate format>
In [628]: print(_)                                                                   
  (0, 0)    1
  (0, 2)    1
  (1, 0)    1
  (1, 1)    3

请注意,0 值已被省略。在大型有用的稀疏矩阵中,超过 90% 的元素为零。

===

这是一种从数组数组构造稀疏矩阵的方法。我从a 中的各个数组构建coo 格式矩阵的row,col,data 属性。

In [630]: a = np.array([np.array([1,0,1]),np.array([1,3])])                          
In [631]: row, col, data = [],[],[]                                                  
In [632]: for i,n in enumerate(a): 
     ...:     row.extend([i]*len(n)) 
     ...:     col.extend(np.arange(len(n))) 
     ...:     data.extend(n) 
     ...:                                                                            
In [633]: row,col,data                                                               
Out[633]: ([0, 0, 0, 1, 1], [0, 1, 2, 0, 1], [1, 0, 1, 1, 3])
In [634]: M = sparse.coo_matrix((data, (row,col)))                                   
In [635]: M                                                                          
Out[635]: 
<2x3 sparse matrix of type '<class 'numpy.int64'>'
    with 5 stored elements in COOrdinate format>
In [636]: print(M)                                                                   
  (0, 0)    1
  (0, 1)    0
  (0, 2)    1
  (1, 0)    1
  (1, 1)    3
In [637]: M.A                                                                        
Out[637]: 
array([[1, 0, 1],
       [1, 3, 0]])

另一种方法是填充a 以创建一个二维数值数组,并从中生成稀疏数组。之前已经询问过使用各种解决方案填充锯齿状列表/数组。这是更容易记住和使用的一种:

In [658]: alist = list(zip(*(itertools.zip_longest(*a,fillvalue=0))))                                                                            
In [659]: alist                                                                      
Out[659]: [(1, 0, 1), (1, 3, 0)]
In [661]: sparse.coo_matrix(alist)                                                   
Out[661]: 
<2x3 sparse matrix of type '<class 'numpy.int64'>'
    with 4 stored elements in COOrdinate format>
In [662]: _.A                                                                        
Out[662]: 
array([[1, 0, 1],
       [1, 3, 0]])

【讨论】:

  • 有没有办法把这个锯齿状数组变成一个规则矩阵,用 0 填充剩余的空间?
  • 我添加了一些想法。
【解决方案2】:

如果您的数组有很多遗漏的尾随零,我会考虑使用dok_matrix

In [98]: dok = sparse.dok_matrix((2, 3), dtype=np.int64)

In [99]: for r_num, row in enumerate(a):
    ...:     for col_num, el in enumerate(row):
    ...:         dok[r_num, col_num] = el 
    ...:         

In [100]: dok.toarray()
Out[100]: 
array([[1, 0, 1],
       [1, 3, 0]], dtype=int64)

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2014-12-21
    • 2018-05-30
    • 1970-01-01
    • 2023-04-10
    • 2017-07-02
    • 2019-02-11
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多