我试图在Python 3.6中有效地解决以下线性系统:
b = A x
其中A是N×N Toeplitz矩阵(即,从左到右的对角线是常数)并且x,b是N×N矩阵。 Durbin-Levinson在Scipy中实现为scipy.linalg.solve_toeplitz应该利用A的结构有效地解决上述系统,实际上当x,b是向量时它会这样做。
但是,当x,b是 matrices 时,它比scipy.linalg.solve和numpy.linalg.solve慢得多(参见我的测试脚本的输出)
执行时间对我的申请至关重要。我有什么选择来加速这个过程并使用Toeplitz结构?
scipy.linalg.solve_toeplitz缓慢的一个可能的解释是,它使用缓慢的for循环进行矩阵输入,以解决单个线性系统x,b为向量(一次求解每列)。
"""This script serves to benchmark several methods for solving a
linear equation involving a Toeplitz matrix and determine which one is
faster.
We consider the equation: b = A x, where A is Toeplitz, b and x are matrices and we wish to
solve for x.
"""
import numpy as np
import numpy.linalg
import scipy.linalg
import time
N = 500
np.random.seed(1)
# Construct random vectors/matrices
x = np.random.rand(N, N)
c,r = np.random.rand(2, N)
A = scipy.linalg.toeplitz(c, r)
b = A.dot(x)
# Validate various solutions
x_sol = []
x_sol.append(('numpy.linalg.solve(A, b)', numpy.linalg.solve(A, b)))
x_sol.append(('scipy.linalg.solve(A, b)', scipy.linalg.solve(A, b)))
x_sol.append(('scipy.linalg.solve_toeplitz((c, r), b)', scipy.linalg.solve_toeplitz((c, r), b)))
for solution in x_sol:
print("Method: {} - error: {}".format(solution[0], numpy.linalg.norm(solution[1] - x)))
# Time the solutions
x_time = []
for solution in x_sol:
t_start = time.time()
eval(solution[0])
t_end = time.time()
x_time.append(t_end - t_start)
print("Timings:")
print(x_time)
脚本输出:
Method: numpy.linalg.solve(A, b) - error: 4.8794411236474704e-11
Method: scipy.linalg.solve(A, b) - error: 4.824494916488265e-11
Method: scipy.linalg.solve_toeplitz((c, r), b) - error: 2.7607739766053664e-08
Timings:
[0.08000469207763672, 0.03300189971923828, 0.6740384101867676]
文档:https://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.linalg.solve_toeplitz.html