![](/img/trans.png)
[英]How can I solve a system of linear equations in python faster than with numpy.linalg.lstsq?
[英]Solve non square matrix with python: How to use numpy.linalg.lstsq()?
要求的行为
我想用python解决一个非平方矩阵。 矩阵具有两个线性相关向量。
当前状态
我尝试首先使用numpy.linalg.solve()
,但这仅适用于平方矩阵。 建议使用numpy.linalg.lstsq()
其他StackOverflow发布。
问题
但是,我不明白如何正确实现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)
这是一个欠定的方程组。 这意味着有很多解决方案,而没有“ the”解决方案。 高斯消除和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.