在 numpy 中使用并行编程进行矩阵乘法 python

Matrix multiplication with parallel programming in numpy python

我是 python 的新手,但我需要使用 numpy 将普通矩阵乘法代码转换为 parallel, 我需要将此函数转换为并行方式:


def RowByColumn(A, B):
    matrix=[]
    for i in range(len(A)):
        matrix.append([])
        for j in range(len(B)):
            matrix[i].append(matrix_multiplication(getRow(A,i),getColumn(B,j)))
    return matrix


如何在 python 中应用多处理模块或其他并行处理模块,有人能帮我吗?

我不推荐多处理,因为创建进程很慢,而且通信开销也很大。您可以使用 numba,这将编译您的函数并使其非常快。该库与 numpy 配合得很好。此外,包含线程并行化非常容易:

import numpy as np
from numba import njit, prange

@njit(parallel=True)
def mat_mult(A, B):
    assert A.shape[1] == B.shape[0]
    res = np.zeros((A.shape[0], B.shape[1]), )
    for i in prange(A.shape[0]):
        for k in range(A.shape[1]):
            for j in range(B.shape[1]):
                res[i,j] += A[i,k] * B[k,j]
    return res

m, n, c = 1000, 1500, 1200
A = np.random.randint(1, 50, size = (m, n))
B = np.random.randint(1, 50, size = (n, c))

res = mat_mult(A, B)

使用prange 并行化循环。我只并行化了外循环,但您也可以将其应用于内循环。

另请注意我使用的循环顺序,这使得连续内存访问减少了缓存未命中。

在我的笔记本电脑上,并行函数执行大约需要 1.4 秒,而 numpy 的矩阵乘法 A@B 需要 4.4 秒,所以有一些改进。