【发布时间】:2015-03-02 11:33:48
【问题描述】:
我想迭代地构建稀疏矩阵,并注意到根据 SciPy 文档有两个合适的选项:
类 scipy.sparse.lil_matrix(arg1, shape=None, dtype=None, copy=False)[source] 基于行的链表稀疏矩阵
这是构造稀疏矩阵的有效结构 逐渐增加。
类 scipy.sparse.dok_matrix(arg1, shape=None, dtype=None, copy=False)[source] 基于稀疏矩阵的键字典。
这是构造稀疏矩阵的有效结构 逐渐增加。
但是当我运行基准测试时,与构建值字典(稍后可以轻松转换为稀疏矩阵)相比,后者比使用任何稀疏矩阵快 10-20 倍型号:
from scipy.sparse import dok_matrix, lil_matrix
from timeit import timeit
from collections import defaultdict
def common_dict(rows, cols):
freqs = defaultdict(lambda: defaultdict(int))
for row, col in zip(rows, cols):
freqs[row][col] += 1
return freqs
def dok(rows, cols):
freqs = dok_matrix((1000,1000))
for row, col in zip(rows, cols):
freqs[row,col] += 1
return freqs
def lil(rows, cols):
freqs = lil_matrix((1000,1000))
for row, col in zip(rows, cols):
freqs[row,col] += 1
return freqs
def benchmark():
cols = range(1000)
rows = range(1000)
res = timeit("common_dict({},{})".format(rows, cols),
"from __main__ import common_dict",
number=100)
print("common_dict: {}".format(res))
res = timeit("dok({},{})".format(rows, cols),
"from __main__ import dok",
number=100)
print("dok: {}".format(res))
res = timeit("lil({},{})".format(rows, cols),
"from __main__ import lil",
number=100)
print("lil: {}".format(res))
结果:
benchmark()
common_dict: 0.11778324202168733
dok: 2.2927695910912007
lil: 1.3541790939634666
是什么导致了矩阵模型的这种开销,有什么方法可以加快它的速度吗?是否有使用 dok 或 lil 比普通字典更喜欢的用例?
【问题讨论】: