Python 更改单个操作的稀疏结构
我有一个Python 更改单个操作的稀疏结构,python,scipy,sparse-matrix,Python,Scipy,Sparse Matrix,我有一个coo格式的矩阵a(它是从scipy.sparse.bmat创建的): 但我会得到一个 SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient. SparseEfficiencyWarning) 现在,据我所知,lil_矩阵在求解线性代数时效率低下-因此,即使我将稀疏结构更改为lil,我也会/应该在之后更改回
coo
格式的矩阵a
(它是从scipy.sparse.bmat
创建的):
但我会得到一个
SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
SparseEfficiencyWarning)
现在,据我所知,lil_矩阵
在求解线性代数时效率低下-因此,即使我将稀疏结构更改为lil
,我也会/应该在之后更改回csr
或csc
总的来说,这值得吗?我不想对我在这里做的每一个操作都进行速度测试:是否存在“改变稀疏性”与“行切片”与“算术运算”的成本有多高的经验法则?程序员通常是如何处理此类问题的?尽管有警告,一次性更改为
csr
比往返lil
要好:
In [137]: %%timeit M = sparse.random(10,10,.2,format='csr')
...: M[-1,:] = np.arange(10)
...:
SparseEfficiencyWarning)
204 µs ± 5.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [139]: %%timeit M = sparse.random(10,10,.2,format='csr')
...: M1=M.tolil(); M1[-1,:] = np.arange(10); M = M1.tocsr()
444 µs ± 9.91 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [141]: %%timeit M = sparse.random(10,10,.2,format='lil')
...: M[-1,:] = np.arange(10)
162 µs ± 84.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
你总是可以自己计时。根据我的经验,“效率警告”主要是为了防止你在循环中这样做。有一次,像这样的改变,忽略它。转换为
lil
是不值得的。
SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
SparseEfficiencyWarning)
In [137]: %%timeit M = sparse.random(10,10,.2,format='csr')
...: M[-1,:] = np.arange(10)
...:
SparseEfficiencyWarning)
204 µs ± 5.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [139]: %%timeit M = sparse.random(10,10,.2,format='csr')
...: M1=M.tolil(); M1[-1,:] = np.arange(10); M = M1.tocsr()
444 µs ± 9.91 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [141]: %%timeit M = sparse.random(10,10,.2,format='lil')
...: M[-1,:] = np.arange(10)
162 µs ± 84.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)