[英]sparse matrix multipliction with dictionaris in python
稀疏矩陣是其大多數成員具有零值的矩陣。 因此,為了節省內存和存儲矩陣,可以方便地在以下配置中使用字典來表示它們:對於矩陣中不為零的每個單元格,將在表示坐標的字典中存儲一個元組鍵單元格的值,值表示矩陣中單元格的值(一些類型為 int 或 float 的數字),通常在數學中,矩陣的索引從 1 開始。 • 單元格坐標(j, i) 包含自然數,因此該坐標表示第i 行第j 列中的單元格。 • 字典中的順序並不重要。 實現函數 sparse_mult(n, mat2, mat1) 接收 2 個字典,mat1 和 mat2,代表大小為 n×n 的稀疏方陣,返回一個代表 mat2×mat1 矩陣乘法矩陣的字典。 請注意:
for i in range(1, n + 1):
temp = 0
for j in range(1, n + 1):
if (mat1.get((i, j), 0) != 0)|(mat2.get((j, i), 0) != 0):
temp += mat1.get((i, j), 0) * mat2.get((j, i), 0)
if temp !=0:
resultrow[(i, i)]=temp
那是我的代碼,我知道我弄錯了,但我就是不知道
所以我最終明白了,如果有人關心的話:
result = {}
# iterate over the rows and columns of the result matrix
for i in range(1, n + 1):
for j in range(1, n + 1):
# initialize the sum to 0
sum = 0
# iterate over the columns of the first matrix and the rows of the second matrix
for k in range(1, n + 1):
# check if the cell (i, k) in the first matrix and the cell (k, j) in the second matrix are non-zero
if (i, k) in mat1 and (k, j) in mat2:
sum += mat1[(i, k)] * mat2[(k, j)]
# add the result to the dictionary if it is non-zero
if sum != 0:
result[(i, j)] = sum
# return the result dictionary
return result
將兩個稀疏矩陣相乘時,遍歷二維索引集中的所有索引是低效的。 相反,您可以遍歷所有鍵對,其中從每個稀疏矩陣中提取 1 對。 給定這樣一對(i,j)
和(k,l)
,當且僅當j == k
時,它貢獻 2 個數字的乘積。 在這種情況下,相應的產品將進入整個產品中的條目(i,l)
。 最終的字典理解可以擺脫任何零條目。 如果數字是浮點數並且某些條目僅由於舍入錯誤而非零,則最后一步可能不充分。 在那種情況下,閾值方法會刪除接近零的條目,而不僅僅是等於零。
def sparse_multiply(a,b):
c = {}
for i,j in a.keys():
for k,l in b.keys():
if j == k:
p = a[(i,j)]*b[(k,l)]
if (i,l) in c:
c[(i,l)] += p
else:
c[(i,l)] = p
return {k:v for k,v in c.items() if v != 0}
請注意, n
在這里不起作用。 復雜度為mk
,其中m
是第一個矩陣中非零條目的數量, k
是第二個矩陣中此類條目的數量。 對於非常稀疏的矩陣,這將比使用直接矩陣乘法的n^3
快得多。 會有一些閾值mk
實際上會大於n^3
,但在那個階段矩陣不再稀疏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.