Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么scipy.linalg.lu()在这段代码中返回了错误的平方矩阵B的分解矩阵?_Python_Numpy_Scipy_Matrix Decomposition - Fatal编程技术网

Python 为什么scipy.linalg.lu()在这段代码中返回了错误的平方矩阵B的分解矩阵?

Python 为什么scipy.linalg.lu()在这段代码中返回了错误的平方矩阵B的分解矩阵?,python,numpy,scipy,matrix-decomposition,Python,Numpy,Scipy,Matrix Decomposition,我有以下代码,其结果非常混乱: import numpy as np import scipy.linalg B = np.array([[2,-1,-2],[-4,6,3],[-4,-2,8]]) P,L,U = scipy.linalg.lu(B) print(L) 返回以下内容: [[1.0.0] [ 1. 1. 0. ] [-0.5-0.25 1.] 但这不是B的LU分解中正确的L矩阵。据我所知,命令scipy.linalg.LU(matrix)只是计算你放入的任何矩阵的

我有以下代码,其结果非常混乱:

import numpy as np
import scipy.linalg
B = np.array([[2,-1,-2],[-4,6,3],[-4,-2,8]])
P,L,U = scipy.linalg.lu(B)
print(L)
返回以下内容:

[[1.0.0]
[ 1.    1.    0.  ]
[-0.5-0.25 1.]


但这不是B的LU分解中正确的L矩阵。据我所知,命令scipy.linalg.LU(matrix)只是计算你放入的任何矩阵的LU分解矩阵。然而,在这种情况下,L矩阵是不正确的。这是怎么回事?非常感谢您的帮助。

我想您可能误解了分解应该做什么。”因为在我看来它是正确的。。。让我们看一下您的示例结果,并附上一些额外的细节和注释:

import numpy as np
import scipy.linalg
B = np.array([[2,-1,-2],[-4,6,3],[-4,-2,8]])
P,L,U = scipy.linalg.lu(B)  

# Now let's see if P is a permutation matrix (a single 1 in each row and column, all the rest should be zero):
print(P)  
>> [[ 0.  0.  1.]
   [ 1.  0.  0.]
   [ 0.  1.  0.]]
# Yup! That's a successful permutation matrix  

# Now let's see if L is a lower triangular matrix (anything above the main diagonal should be zero):
print(L)
>> [[ 1.    0.    0.  ]
   [ 1.    1.    0.  ]
   [-0.5  -0.25  1.  ]]
# Yup! still doing good.  

# Now let's see if U is a upper triangular matrix (anything below the main diagonal should be zero):
print(U)
>> [[-4.    6.    3.  ]
   [ 0.   -8.    5.  ]
   [ 0.    0.    0.75]]

# And last but not least, let's see if this works as a decomposition of B (i.e. PLU==B):  
print(np.matmul(P, np.matmul(L, U)))
>> [[ 2. -1. -2.]
   [-4.  6.  3.]
   [-4. -2.  8.]]

# :-)  
我希望这能澄清一些事情。如果您仍然不确定,那么可以重新阅读、和密切相关的主题。
祝你好运


似乎已经有了澄清:
LU分解在一般情况下不一定是唯一的。
如果您想了解以上维基百科链接中的详细信息,我建议您提供有关堆栈交换问题的第一个和第三个答案。

因此,如果您碰巧从不同的实现或方法中得到两个不同的答案,这并不意味着其中一个是错误的。如果你有一个置换矩阵P(即使它是平凡的单位矩阵),一个下矩阵L,一个上矩阵U,它们分解了你的矩阵,那么你得到了你自己的分解。希望能把事情弄清楚

为什么这不是分解中正确的下矩阵?您认为正确的矩阵是什么?“…命令scipy.linalg.lu(matrix)只计算lu分解…”更准确地说,它计算因子分解P@L@U、 其中P是置换矩阵,L是下三角体,U是上三角体。在评估结果的正确性时,您是否考虑了P?@ShlomiF我认为使用在线LU分解工具的正确矩阵如下:([[1,0,0],-2,1,0],-2,-1-,1]])。这不是我的代码返回的L矩阵,因此我感到困惑。但为什么它返回的L矩阵不是使用在线LU分解工具(如:)时看到的L矩阵?该工具和手工计算返回矩阵([[1,0,0],-2,1,0],-2,-1,1]])。我如何使用scipy.linalg.lu返回的矩阵获得这个L矩阵?我不是100%确定,但我知道lu分解不是唯一的,排列矩阵用于使算法更高效地运行,所以我猜不同之处在于您使用的站点&手工练习是很长的一段路,但为了提高效率,scipy函数合并了置换矩阵,从而提取了另一种可能的LU分解。如果我在这里弄错了,我很乐意被纠正。