使用scipy在python中构建和更新稀疏矩阵

2024-10-02 22:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

当我从文件中读取数据时,我试图构建和更新一个稀疏矩阵。 矩阵的大小是100000X40000

更新稀疏矩阵的多个条目的最有效方法是什么? 具体来说,我需要将每个条目增加1。

假设我有行索引[2, 236, 246, 389, 1691]

和列索引[117, 3, 34, 2757, 74, 1635, 52]

因此,以下所有条目必须递增一:

(2,117) (2,3) (2,34) (2,2757) ...

(236,117) (236,3) (236, 34) (236,2757) ...

等等。

我已经在使用lil_matrix,因为当我试图更新一个条目时,它给了我一个使用警告。

lil_matrix格式已不支持多次更新。 matrix[1:3,0] += [2,3]给了我一个未实现的错误。

我可以很天真地做到这一点,将每个条目单独递增。我想知道是否有更好的方法来做到这一点,或更好的稀疏矩阵实现,我可以使用。

我的电脑也是一台普通的i5机器,内存为4GB,所以我必须小心不要把它炸掉:)


Tags: 方法内存目的机器警告格式错误条目
3条回答

这个答案扩展了@behzad.nouri的评论。要在行和列索引列表的“外部产品”处增加值,只需将它们创建为配置为广播的numpy数组。在本例中,这意味着将行放入列中。例如

In [59]: a = lil_matrix((4,4), dtype=int)

In [60]: a.A
Out[60]: 
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])

In [61]: rows = np.array([1,3]).reshape(-1, 1)

In [62]: rows
Out[62]: 
array([[1],
       [3]])

In [63]: cols = np.array([0, 2, 3])

In [64]: a[rows, cols] += np.ones((rows.size, cols.size))

In [65]: a.A
Out[65]: 
array([[0, 0, 0, 0],
       [1, 0, 1, 1],
       [0, 0, 0, 0],
       [1, 0, 1, 1]])

In [66]: rows = np.array([0, 1]).reshape(-1,1)

In [67]: cols = np.array([1, 2])

In [68]: a[rows, cols] += np.ones((rows.size, cols.size))

In [69]: a.A
Out[69]: 
array([[0, 1, 1, 0],
       [1, 1, 2, 1],
       [0, 0, 0, 0],
       [1, 0, 1, 1]])

在新坐标系中用1s创建第二个矩阵并将其添加到现有矩阵中是一种可能的方法:

>>> import scipy.sparse as sps
>>> shape = (1000, 2000)
>>> rows, cols = 1000, 2000
>>> sps_acc = sps.coo_matrix((rows, cols)) # empty matrix
>>> for j in xrange(100): # add 100 sets of 100 1's
...     r = np.random.randint(rows, size=100)
...     c = np.random.randint(cols, size=100)
...     d = np.ones((100,))
...     sps_acc = sps_acc + sps.coo_matrix((d, (r, c)), shape=(rows, cols))
... 
>>> sps_acc
<1000x2000 sparse matrix of type '<type 'numpy.float64'>'
    with 9985 stored elements in Compressed Sparse Row format>
import scipy.sparse

rows = [2, 236, 246, 389, 1691]
cols = [117, 3, 34, 2757, 74, 1635, 52]
prod = [(x, y) for x in rows for y in cols] # combinations
r = [x for (x, y) in prod] # x_coordinate
c = [y for (x, y) in prod] # y_coordinate
data = [1] * len(r)
m = scipy.sparse.coo_matrix((data, (r, c)), shape=(100000, 40000))

我认为它运行良好,不需要循环。我直接跟着doc

<100000x40000 sparse matrix of type '<type 'numpy.int32'>'
    with 35 stored elements in COOrdinate format>

相关问题 更多 >