首页 > 解决方案 > 用python求解非方阵:如何使用numpy.linalg.lstsq()?

问题描述

请求的行为
我想用 python 解决一个非方阵。该矩阵有两个线性相关的向量。


我尝试首先使用的当前状态numpy.linalg.solve(),但这仅适用于方阵。其他 StackOverflow 帖子推荐使用numpy.linalg.lstsq().

问题
但是,我不明白如何numpy.linalg.lstsq()正确实施。该函数正确求解最后一个参数,但不能正确求解其他参数。一篇文章推荐了这个我也不明白的解决方案。

我是否必须以某种方式实现循环?

有人可以为我提供一个代码示例吗?如何使用python解决这个矩阵问题?

我当前的代码

import numpy as np

# defining a linear equation system E=F with
#   | -2 * x1 - 4 * x2 + 1 * x3 -  9 * x4 + 0 * x5 =  +5  |
#   |  3 * x1 + 6 * x2 + 0 * x3 + 12 * x4 + 3 * x5 = +15  |
#   |  1 * x1 + 2 * x2 + 1 * x3 +  3 * x4 + 1 * x5 = -17  |
#   | -5 * x1 - 4 * x2 + 1 * x3 -  9 * x4 + 0 * x5 = +14  |


E=np.array(
    [
        [-2,-4,1,-9,0],
        [3,6,0,12,3],
        [1,2,1,3,1],
        [-5,-10,3,-23,1]
    ]
)

F=np.array(
    [3,15,-17,14]
)

solutionNonSquare = np.linalg.lstsq(E, F)
print('the solution vector is: {x1, x2, x3, x4, x5}=')
print(solutionNonSquare)

书面矩阵解决方案 在此处输入图像描述

标签: pythonnumpymatrixlinear-algebra

解决方案


这是一个欠定方程组。这意味着有很多解决方案,并且没有“解决方案”之类的东西。高斯消除并lstsq给出不同解决方案的事实并不意味着有任何问题。

让我们生成并检查各种解决方案:

import scipy.linalg as sla

E_null = sla.null_space(E)

def check_solution(coeffs):
    x = solutionNonSquare[0] + E_null @ coeffs
    check = E @ x - F
    with np.printoptions(precision=2, suppress=True):
        print('x = {}'.format(x))
    with np.printoptions(precision=5, suppress=True):
        print('E . x - F = {}'.format(check))
    print('|x| = {}'.format(np.linalg.norm(x)))

我们可以检查由 产生的最小范数解lstsq

>>> check_solution([0, 0])
x = [ -4.35  -8.69 -19.69   2.31  17.5 ]
E . x - F = [ 0. -0. -0.  0.]
|x| = 28.174593028253167

我们可以生成和测试许多其他解决方案

>>> check_solution(100 * np.random.randn(2))
x = [ -88.93 -139.06   66.64   88.64   17.5 ]
E . x - F = [ 0.  0. -0.  0.]
|x| = 199.62363490542995
>>> check_solution(100 * np.random.randn(2))
x = [-25.2  -26.99  -5.33  16.67  17.5 ]
E . x - F = [ 0. -0. -0.  0.]
|x| = 44.455362582961335
>>> check_solution(100 * np.random.randn(2))
x = [ 93.34  14.57 -55.74 -33.74  17.5 ]
E . x - F = [ 0. -0. -0. -0.]
|x| = 116.09338153741933

我们甚至可以查看您的解决方案:

>>> my_favourite_solution = np.array([-12.5, 0, -22, 0, 17.5 ])
>>> my_favourite_coeffs = my_favourite_solution @ E_null
>>> check_solution(my_favourite_coeffs)
x = [-12.5   0.  -22.   -0.   17.5]
E . x - F = [ 0. -0. -0.  0.]
|x| = 30.765240125830324

推荐阅读