【发布时间】:2014-09-22 14:06:45
【问题描述】:
我正在尝试将矩阵的每一列乘以向量元素。
我有一个可以正常工作的串行解决方案。
for i in range(0,temp.shape[0]):
for j in range(0,temp.shape[1]):
temp[i,j] = temp[i,j] * h[i,0]
以下是适用于我正在尝试做的事情的并行解决方案,但不会返回与上述代码相同的矩阵。
def mv_mult(start_col,end_col,M,V):
for i in range(0,M.shape[0]):
for j in range(start_col,end_col):
M[i,j] = M[i,j] * V[i,0]
num_threads = multiprocessing.cpu_count()
threads = []
extra = temp.shape[1] % num_threads
start_col = 0
jump = temp.shape[1] / num_threads
for i in range(0,num_threads):
print 'starting thread ', i
if (i < extra)
args = start_col, start_col+jump+1,temp,h
p = multiprocessing.Process(target=mv_mult,args=args)
p.start()
threads.append(p)
start_col += jump+1
else:
args = start_col, start_col+jump,temp,h
p = multiprocessing.Process(target=mv_mult,args=args)
p.start()
threads.append(p)
start_col += jump
for i in threads:
i.join()
我对 Python 比较陌生,但据我所知,一切都是通过引用传递的,所以传递给每个新进程的临时矩阵是同一个对象,所以它应该与串行解决方案一样工作,减去事实它是按列拆分的。
关于它为什么不起作用的任何想法?
【问题讨论】:
-
目前最好使用 numpy 执行此操作,并确保您的 numpy 与线程 BLAS(Atlas、OpenBLAS)链接。您不想编写自己的线性代数例程。
标签: python matrix multiprocessing matrix-multiplication