簡體   English   中英

使用scipy在python中構建和更新稀疏矩陣

[英]Building and updating a sparse matrix in python using scipy

當我從文件中讀取數據時,我正在嘗試構建和更新稀疏矩陣。 矩陣的大小為100000X40000

更新稀疏矩陣的多個條目的最有效方法是什么? 特別是我需要將每個條目遞增1。

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

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

所以以下所有條目必須加1:

(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,所以我要注意不要把它炸掉:)

創建與第二矩陣1在新的坐標S和它添加到現有的一個是這樣做的可能方式:

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

我認為它運作良好,不需要循環。 我直接關注文檔

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

這個答案擴展了@ 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]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM