Skip to main content
 首页 » 编程设计

python之使用 scipy 动态更新 coo 矩阵

2025年05月04日12jillzhang

我在搜索站点后没有找到解决此问题的方法。很简单,我想更新一个已经存在的 coo 稀疏矩阵。所以假设我已经启动了一个 coo 矩阵:

from scipy.sparse import coo_matrix 
import numpy as np 
row  = np.array([0, 3, 1, 0]) 
col  = np.array([0, 3, 1, 2]) 
data = np.array([4, 5, 7, 9]) 
a=coo_matrix((data, (row, col)), shape=(4, 4)).toarray() 
array([[4, 0, 9, 0], 
      [0, 7, 0, 0], 
      [0, 0, 0, 0], 
      [0, 0, 0, 5]]) 

很好,但是如果我只想要一个空的稀疏数组并仅使用形状启动它,然后多次更新值怎么办。我成功的唯一方法是向我的旧矩阵添加一个新的 coo 矩阵

a=coo_matrix((4, 4), dtype=np.int8) 
a=a+coo_matrix((data, (row, col)), shape=(4, 4)) 
a.toarray() 
array([[4, 0, 9, 0], 
      [0, 7, 0, 0], 
      [0, 0, 0, 0], 
      [0, 0, 0, 5]]) 

而且我想多次更新这个稀疏数组。但这需要相当长的时间,因为我为每次更新调用 coo 函数。必须有更好的方法,但我觉得文档有点浅(至少我读过的)或者我只是没有看到它。

非常感谢

请您参考如下方法:

当您以这种方式制作 coo 矩阵时,它会将您的输入数组用作矩阵的属性(前提是它们的类型正确):

In [923]: row  = np.array([0, 3, 1, 0]) 
     ...: col  = np.array([0, 3, 1, 2]) 
     ...: data = np.array([4, 5, 7, 9]) 
     ...: A=sparse.coo_matrix((data, (row, col)), shape=(4, 4)) 
In [924]: A 
Out[924]:  
<4x4 sparse matrix of type '<class 'numpy.int32'>' 
    with 4 stored elements in COOrdinate format> 
In [925]: A.row 
Out[925]: array([0, 3, 1, 0]) 
In [926]: id(A.row) 
Out[926]: 3071951160 
In [927]: id(row) 
Out[927]: 3071951160 

对于 A.col 和 A.data 也是如此。

为了显示和计算,矩阵可能会转换为 csr 格式,因为其中许多操作未针对 coo 格式定义。

而且您肯定已经看到 coo 格式没有实现索引,无论是用于获取还是设置。

lil 格式旨在更轻松地进行增量更改。也可以对 csr 进行索引更改,但会发出警告。

但是 coo 通常用于构建新矩阵。例如在bmat格式中,将分量矩阵的coo属性组合成新的数组,然后用这些数组构造一个新的coo矩阵。

增量构建 coo 的一个好方法是不断将新值连接到您的 row、col 和 data 数组,然后定期从这些数组构建一个新的 coo。

关于更新 dok 格式: How to incrementally create an sparse matrix on python?

putting column into empty sparse matrix

creating a scipy.lil_matrix using a python generator efficiently