【问题标题】:How can I solve a system of linear equations in python faster than with numpy.linalg.lstsq?如何在 python 中比使用 numpy.linalg.lstsq 更快地求解线性方程组?
【发布时间】:2018-05-22 16:06:16
【问题描述】:

我正在尝试使用 numpy.linalg.lstsq 求解一个跨越十万到二十万方程的线性系统,但花费的时间太长了。我该怎么做才能加快速度?

矩阵稀疏,包含数百列(尺寸约为 150 000 x 140),系统超定。

【问题讨论】:

  • 请添加更多信息。维度、密集与稀疏、结构......
  • 好了,搞定了。
  • 如果稀疏,try the sparse solver.

标签: python performance numpy math computer-science


【解决方案1】:

这里有一点即兴的技巧,可以大大加快对指定维度的随机数据的计算速度。

不过,我不知道这在数字上听起来有多好。

import numpy as np
from time import perf_counter

def lstsq(A, b):
    AA = A.T @ A
    bA = b @ A
    D, U = np.linalg.eigh(AA)
    Ap = (U * np.sqrt(D)).T
    bp = bA @ U / np.sqrt(D)
    return np.linalg.lstsq(Ap, bp, rcond=None)

# create random data
A = np.random.random((150_000, 140))
b = np.random.random((150_000,))

# use solver directly
t = perf_counter()
x, *info = np.linalg.lstsq(A, b, rcond=None)
s = perf_counter()
print('direct method:     ', s-t, 'seconds')
# use equivalent reduced system
t = perf_counter()
x_acc, *info_acc = lstsq(A, b)
s = perf_counter()
print('accelerated method:', s-t, 'seconds')
print('results equal:', np.allclose(x, x_acc))

示例运行:

direct method:      3.032766239999546 seconds
accelerated method: 0.20947745100056636 seconds
results equal: True

【讨论】:

    【解决方案2】:

    如果您的系数矩阵是稀疏的,请使用“scipy.sparse.linalg”中的“spsolve”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 2017-07-27
      相关资源
      最近更新 更多