python 多线程稀疏矩阵乘法

Posted 一只有恒心的小菜鸟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 多线程稀疏矩阵乘法相关的知识,希望对你有一定的参考价值。

 1 import threading, time
 2 import numpy as np
 3 res = []
 4 class MyThread(threading.Thread):
 5     def __init__(self,i,j,m1,m2):
 6         threading.Thread.__init__(self)
 7         self.x, self.y = i,j
 8         self.m1, self.m2 = m1, m2
 9     def run(self):
10         global res, lock
11         if lock.acquire():
12             m1 = self.m1[self.m1[:,0]==self.x]
13             m2 = self.m2[self.m2[:,1]==self.y]
14             value = 0.
15             for item1 in m1:
16                 for item2 in m2:
17                     if item1[1] == item2[0]:
18                         value += item1[2]*item2[2]
19             res.append([self.x,self.y,value])
20             lock.release()
21 if "__main__" == __name__:
22     m1 = [[2,2],[0,0,1],[0,1,2],[1,0,3],[1,1,4]]
23     m2 = [[2,3],[0,0,2],[0,2,1],[1,2,3],[1,1,4]]
24     s1, s2 = m1[0], m2[0]
25     assert s1[1]==s2[0], \'mismatch\'
26     m1_value = np.array(m1[1:])
27     m2_value = np.array(m2[1:])  
28     rows, cols = s1[0], s2[1]
29     res.append([rows, cols])
30     ThreadList = []
31     lock = threading.Lock()
32     for i in range(rows):
33         for j in range(cols):
34             t = MyThread(i,j,m1_value,m2_value)
35             ThreadList.append(t)
36     for t in ThreadList:
37         t.start()
38     for t in ThreadList:
39         t.join()
40     print (res)

 

以上是关于python 多线程稀疏矩阵乘法的主要内容,如果未能解决你的问题,请参考以下文章

为什么稀疏密集乘法比密集稀疏乘法更快?

稀疏矩阵与密集矩阵乘法 C++ Tensorflow

稠密矩阵怎么转成稀疏矩阵 python

C++中的多线程矩阵乘法

Python中的稀疏3d矩阵/数组?

如何在TensorFlow中执行稀疏矩阵*稀疏矩阵乘法?