如何将 numpy 数组 dtype=object 转换为稀疏矩阵?



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

前任:

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

我已经尝试了将 numpy 对象数组转换为稀疏矩阵给出的解决方案,但没有成功。

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()

正如评论中所解释的那样,这实际上是一个锯齿状数组。 从本质上讲,这个数组表示一个图形,我必须将其转换为稀疏矩阵,以便我可以使用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

你不能。 当它试图找到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]])

如果您的数组有很多遗漏的尾随零,我会考虑使用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)

最新更新