用pysp并行实现scipy-csr稀疏矩阵的大矩阵乘法

2024-10-01 02:21:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在计算两大组向量(具有相同特征)之间的余弦相似性。每组向量表示为一个scipy CSR稀疏矩阵a和B。我想计算一个x B^T,它不是稀疏的。但是,我只需要跟踪超过某个阈值的值,例如0.8。我正试图用vanillardds在Pyspark中实现这一点,其思想是使用为scipycrs矩阵实现的快速向量操作。你知道吗

A和B的行是标准化的,所以为了计算余弦相似性,我只需要找到A的每一行与B的每一行的点积。 A的尺寸为5000000 x 5000。 B的尺寸为2000000 x 5000。你知道吗

假设A和B太大,无法作为广播变量放入工作节点上的内存。我应该如何以最佳方式并行化A和B?你知道吗

编辑 发布解决方案后,我一直在探索其他更清晰、更优化的方法,特别是为Spark MLlib IndexedRowMatrix对象实现的columnComparison()函数。(Which pyspark abstraction is appropriate for my large matrix multiplication?


Tags: 内存节点尺寸矩阵阈值scipy特征相似性
1条回答
网友
1楼 · 发布于 2024-10-01 02:21:18

我能够在这个框架中实现一个解决方案。
欢迎深入了解为什么这个解决方案很慢是因为自定义序列化吗?你知道吗

def csr_mult_helper(pair):
    threshold=0.8
    A_row = pair[0][0]  # keep track of the row offset
    B_col = pair[1][0]   # offset for B (this will be a column index, after the transpose op)
    A = sparse.csr_matrix(pair[0][1], pair[0][2])  # non-zero entires, size data
    B = sparse.csr_matrix(pair[1][1], pair[1][2])

    C = A * B.T  # scipy sparse mat mul

    for row_idx, row in enumerate(C):  # I think it would be better to use a filter Transformation instead
        col_indices = row.indices      #  but I had trouble with the row and column index book keeping
        col_values = row.data

        for col_idx, val in zip(col_indices, col_values):
            if val > threshold:
                yield (A_row + row_idx, B_col + col_idx, val)  # source vector, target vector, cosine score            

def parallelize_sparse_csr(M, rows_per_chunk=1):
    [rows, cols] = M.shape
    i_row = 0
    submatrices = []
    while i_row < rows:
        current_chunk_size = min(rows_per_chunk, rows - i_row)
        submat = M[i_row:(i_row + current_chunk_size)]
        submatrices.append(   (i_row,                                #  offset
                              (submat.data, submat.indices, submat.indptr),  # sparse matrix data
                              (current_chunk_size, cols)) )      # sparse matrix shape
        i_row += current_chunk_size
    return sc.parallelize(submatrices)

########## generate test data ###########
K,L,M,N = 5,2000,3,2000  # matrix dimensions (toy example)
A_ = sparse.rand(K,L, density=0.1, format='csr')
B_ = sparse.rand(M,N, density=0.1, format='csr')
print("benchmark: {} \n".format((A_ * B_.T).todense()))  # benchmark solution for comparison

########## parallelize, multiply, and filter #########
t_start = time.time()
A = parallelize_sparse_csr(A_, rows_per_chunk=10)
B = parallelize_sparse_csr(B_, rows_per_chunk=10) # number of elements per partition, from B
            # warning: this code breaks if the B_ matrix rows_per_chunk parameter != 1
            # although I don't understand why yet

print("custom pyspark solution: ")
result = A.cartesian(B).flatMap(csr_mult_helper).collect()
print(results)

print("\n {} s elapsed".format(time.time() - t_start))

相关问题 更多 >