我有两个方阵A和B
我必须将B转换为CSR Format并确定产品C
A * B_csr = C我在网上找到了很多关于CSR Matrix - Vector multiplication的信息。算法是:
for (k = 0; k < N; k = k + 1)
result[i] = 0;
for (i = 0; i < N; i = i + 1)
{
for (k = RowPtr[i]; k < RowPtr[i+1]; k = k + 1)
{
result[i] = result[i] + Val[k]*d[Col[k]];
}
}但是,我需要Matrix - Matrix乘法。
此外,似乎大多数算法都会在我需要A * B_csr的地方应用A_csr - vector乘法。我的解决方案是在转换之前转置两个矩阵,然后转置最终的乘积。
有人能解释一下如何计算Matrix - CSR Matrix产品和/或CSR Matrix - Matrix产品吗?
发布于 2015-04-22 23:46:47
这是一个简单的Dense Matrix X CSR Matrix的Python语言解决方案。它应该是不言自明的。
def main():
# 4 x 4 csr matrix
# [1, 0, 0, 0],
# [2, 0, 3, 0],
# [0, 0, 0, 0],
# [0, 4, 0, 0],
csr_values = [1, 2, 3, 4]
col_idx = [0, 0, 2, 1]
row_ptr = [0, 1, 3, 3, 4]
csr_matrix = [
csr_values,
col_idx,
row_ptr
]
dense_matrix = [
[1, 3, 3, 4],
[1, 2, 3, 4],
[1, 4, 3, 4],
[1, 2, 3, 5],
]
res = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
]
# matrix order, assumes both matrices are square
n = len(dense_matrix)
# res = dense X csr
csr_row = 0 # Current row in CSR matrix
for i in range(n):
start, end = row_ptr[i], row_ptr[i + 1]
for j in range(start, end):
col, csr_value = col_idx[j], csr_values[j]
for k in range(n):
dense_value = dense_matrix[k][csr_row]
res[k][col] += csr_value * dense_value
csr_row += 1
print res
if __name__ == '__main__':
main()CSR Matrix X Dense Matrix实际上是稠密矩阵的每一行的CSR Matrix X Vector乘积的序列,对吗?因此,扩展上面显示的代码应该很容易做到这一点。
接下来,我建议您不要自己编写这些例程。如果你使用的是C++ (基于标签),那么你可以看看Boost ublas,或者Eigen。API乍一看可能有点神秘,但从长远来看,这是非常值得的。首先,您可以访问更多的功能,这些功能在将来可能会用到。其次,这些实现将得到更好的优化。
https://stackoverflow.com/questions/29598299
复制相似问题