[英]CSR Matrix - Matrix multiplication
I have two square matrices A
and B
我有两个方阵矩阵
A
和B
I must convert B
to CSR Format
and determine the product C
我必须将
B
转换为CSR Format
并确定产品C
A * B_csr = C
I have found a lot of information online regarding CSR Matrix - Vector multiplication . 我在网上找到了很多关于CSR矩阵 - 矢量乘法的信息 。 The algorithm is:
算法是:
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]];
}
}
However, I require Matrix - Matrix
multiplication. 但是,我需要
Matrix - Matrix
乘法。
Further, it seems that most algorithms apply A_csr - vector
multiplication where I require A * B_csr
. 此外,似乎大多数算法都应用
A_csr - vector
乘法,其中我需要A * B_csr
。 My solution is to transpose the two matrices before converting then transpose the final product. 我的解决方案是在转换之前转置两个矩阵然后转置最终产品。
Can someone explain how to compute a Matrix - CSR Matrix
product and/or a CSR Matrix - Matrix
product? 有人可以解释如何计算
Matrix - CSR Matrix
产品和/或CSR Matrix - Matrix
产品吗?
Here is a simple solution in Python for the Dense Matrix X CSR Matrix
. 这是Python中用于
Dense Matrix X CSR Matrix
的简单解决方案。 It should be self-explanatory. 它应该是不言自明的。
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
is really just a sequence of CSR Matrix X Vector
product for each row of the dense matrix right? CSR Matrix X Dense Matrix
实际上只是CSR Matrix X Dense Matrix
每一行的CSR Matrix X Vector
产品序列对吗? So it should be really easy to extend the code you show above to do this. 因此,扩展上面显示的代码应该非常容易。
Moving forward, I suggest you don't code these routines yourself. 继续前进,我建议你不要自己编写这些例程。 If you are using C++ (based on the tag), then you could have a look at Boost ublas for example, or Eigen .
如果您正在使用C ++(基于标记),那么您可以查看Boost ublas或Eigen 。 The APIs may seem a bit cryptic at first but it's really worth it in the long term.
API起初看起来有点神秘,但从长远来看它确实值得。 First, you gain access to a lot more functionality, which you will probably require in the future.
首先,您可以访问更多功能,将来可能需要这些功能。 Second these implementations will be better optimised.
其次,这些实现将得到更好的优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.