gpt4 book ai didi

python - Numpy 高效构造稀疏 coo_matrix 或更快的列表扩展

转载 作者:行者123 更新时间:2023-11-28 17:42:11 30 4
gpt4 key购买 nike

我有一个包含 10 万个项目的列表,每个项目都有一个索引列表。我试图将其放入一个用于向量乘法的 bool 稀疏矩阵。我的代码运行速度没有我希望的那么快,因此我正在寻找性能提示或者可能是将这些数据放入矩阵的替代方法。

rows = []
cols = []
for i, item in enumerate(items):
indices = item.getIndices()
rows += [i]*len(indices)
cols += indices

data = np.ones(len(rows), dtype='?')
mat = coo_matrix(data,(rows,cols)),shape=(len(items),totalIndices),dtype='?')
mat = mat.tocsr()

最后,行/列列表中有 80 万个项目,仅扩展这些列表似乎就占用了构建时间的 16% 和 13%。然后转换为 coo_matrix 占 12%。枚举占13%。我从 line_profiler 获得了这些统计数据,我使用的是 python 3.3。

最佳答案

我能做的最好的是:

def foo3(items,totalIndices):
N = len(items)
cols=[]
cnts=[]
for item in items:
indices = getIndices(item)
cols += indices
cnts.append(len(indices))
rows = np.arange(N).repeat(cnts) # main change
data = np.ones(rows.shape, dtype=bool)
mat = sparse.coo_matrix((data,(rows,cols)),shape=(N,totalIndices))
mat = mat.tocsr()
return mat

对于 100000 项,速度仅提高了 50%。

关于python - Numpy 高效构造稀疏 coo_matrix 或更快的列表扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22695205/

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