gpt4 book ai didi

python - 将 CSR 矩阵乘以向量

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:41 25 4
gpt4 key购买 nike

我正在关注这个 stackoverflow 帖子 on csr matrix multiplication to a vector并在 python 中实现它并得到列表超出范围错误。

这是我的代码:

def MatrixMultiplication(data,row_ptr,col_ptr,vec):
ResultMatrix =[]
vec_len = len(vec)
for i in range(0,vec_len):
ResultMatrix.insert(i,0)
for i in range(0,vec_len):
start, end = row_ptr[i], row_ptr[i + 1]
for k in range(start, end):
ResultMatrix[i] = ResultMatrix[i]+data[k]*vec[col_ptr[k]]
return ResultMatrix

data = [2, 4, 7, 1, 3, 2]
row_ptr = [2,3 ,5, 5 ,6]
col_ptr = [1 ,3, 4, 0, 3, 3]
vec = [2,3, 5, 4, 2]

MatrixMultiplication(data,row_ptr,col_ptr,vec)

请帮我解决我哪里出错了。

输出应为:[ 22 14 14 0 8]

错误:

IndexError: list index out of range
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<command-338158343473691> in <module>()
----> 1 MatrixMultiplication(data,row_ptr,col_ptr,vec)

<command-3658506804172571> in MatrixMultiplication(data, row_ptr, col_ptr, vec)
5 ResultMatrix.insert(i,0)
6 for i in range(0,vec_len):
----> 7 start, end = row_ptr[i], row_ptr[i + 1]
8 for k in range(start, end):
9 ResultMatrix[i] = ResultMatrix[i]+data[k]*vec[col_ptr[k]]

IndexError: list index out of range

仅供引用:

row_ptr 的最后一个元素将是数据列表的大小

最佳答案

错误消息非常不言自明:您尝试在 for 循环中访问 row_ptr[i + 1],该循环一直到 vec_len,即你的 list 的长度。当您到达 for 循环的最后一次迭代并且 i = vec_len - 1 时,i + 1 = vec_len 超出了列表的范围(请记住,Python 列表是从 0 初始化的)。

为了防止出现此错误,第二个 for 循环中的范围只能达到 vec_len - 1

关于python - 将 CSR 矩阵乘以向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com