gpt4 book ai didi

python - 增量求和的正确 SciPy 稀疏矩阵格式是什么

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:25 24 4
gpt4 key购买 nike

在我的代码中,我目前正在迭代并创建三个列表:

数据,行,列

(row, col) 对的重复率很高,在我最终的稀疏矩阵 M 中,我想要 M[row, col]data 中所有对应元素的总和。通过阅读文档,coo_matrix格式看起来很完美,对于小例子来说它工作得很好。

我遇到的问题是,当我扩大我的问题规模时,看起来中间列表 data, row, col 正在用尽我所有的 (8gb) 内存和交换空间和我的脚本被自动杀死。

所以我的问题是:

是否有适当的格式或有效的方式来逐步构建求和矩阵,这样我就不必存储完整的中间列表/numpy 数组?

我的程序在网格上循环,在每个点创建 local_data、local_row、local_col 列表,然后将其元素附加到 data、row、col,所以能够根据稀疏矩阵构造函数使用列表更新稀疏矩阵将是理想的情况。

最佳答案

有两件事可能会让您丧命:重复项或列表对数组的开销。在任何一种情况下,可能正确的做法是在将列表转储到 coo_matrix 并将其添加到总数之前将列表增加到如此大。我花了几个时间:

rows = list(np.random.randint(100, size=(10000,)))
cols = list(np.random.randint(100, size=(10000,)))
values = list(np.random.rand(10000))

%timeit sps.coo_matrix((values, (rows, cols)))
100 loops, best of 3: 4.03 ms per loop

%timeit (sps.coo_matrix((values[:5000], (rows[:5000], cols[:5000]))) +
sps.coo_matrix((values[5000:], (rows[5000:], cols[5000:]))))
100 loops, best of 3: 5.24 ms per loop

%timeit sps.coo_matrix((values[:5000], (rows[:5000], cols[:5000])))
100 loops, best of 3: 2.16 ms per loop

因此,将列表一分为二,将每个列表转换为 coo_matrix,然后将它们相加,大约有 25% 的开销。如果你做更多的拆分,它似乎并没有那么糟糕:

%timeit (sps.coo_matrix((values[:2500], (rows[:2500], cols[:2500]))) +   
sps.coo_matrix((values[2500:5000], (rows[2500:5000], cols[2500:5000]))) +
sps.coo_matrix((values[5000:7500], (rows[5000:7500], cols[5000:7500]))) +
sps.coo_matrix((values[7500:], (rows[7500:], cols[7500:]))))
100 loops, best of 3: 5.76 ms per loop

关于python - 增量求和的正确 SciPy 稀疏矩阵格式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962993/

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