Python 如何计算非方矩阵的Cholesky分解,以便用'numpy'计算马氏距离?

Python 如何计算非方矩阵的Cholesky分解,以便用'numpy'计算马氏距离?,python,numpy,Python,Numpy,如何计算非方矩阵的Cholesky分解,以便使用numpy计算马氏距离 def get_fitting_function(G): print(G.shape) #(14L, 11L) --> 14 samples of dimension 11 g_mu = G.mean(axis=0) #Cholesky decomposition uses half of the operations as LU #and is numerically more st

如何计算非方矩阵的Cholesky分解,以便使用
numpy
计算马氏距离

def get_fitting_function(G):
    print(G.shape) #(14L, 11L) --> 14 samples of dimension 11
    g_mu = G.mean(axis=0) 
    #Cholesky decomposition uses half of the operations as LU
    #and is numerically more stable.
    L = np.linalg.cholesky(G)

    def fitting_function(g):
        x = g - g_mu
        z = np.linalg.solve(L, x)
        #Mahalanobis Distance 
        MD = z.T*z
        return math.sqrt(MD)
    return fitting_function  


C:\Users\Matthias\CV\src\fitting_function.py in get_fitting_function(G)
     22     #Cholesky decomposition uses half of the operations as LU
     23     #and is numerically more stable.
---> 24     L = np.linalg.cholesky(G)
     25 
     26     def fitting_function(g):

C:\Users\Matthias\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\linalg\linalg.pyc in cholesky(a)
    598     a, wrap = _makearray(a)
    599     _assertRankAtLeast2(a)
--> 600     _assertNdSquareness(a)
    601     t, result_t = _commonType(a)
    602     signature = 'D->D' if isComplexType(t) else 'd->d'

C:\Users\Matthias\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\linalg\linalg.pyc in _assertNdSquareness(*arrays)
    210     for a in arrays:
    211         if max(a.shape[-2:]) != min(a.shape[-2:]):
--> 212             raise LinAlgError('Last 2 dimensions of the array must be square')
    213 
    214 def _assertFinite(*arrays):

LinAlgError: Last 2 dimensions of the array must be square 


    LinAlgError: Last 2 dimensions of the array must be square 
基于Matlab实现的:

编辑:
chol(a)
=
linalg.cholesky(a).T
矩阵的cholesky分解(
chol(a)
在matlab中返回上三角矩阵,但
linalg.cholesky(a)
返回下三角矩阵)(来源:)

编辑2:

G -= G.mean(axis=0)[None, :]
C = (np.dot(G, G.T) / float(G.shape[0]))
#Cholesky decomposition uses half of the operations as LU
#and is numerically more stable.
L = np.linalg.cholesky(C).T

所以如果D=x^t.S^-1.x=x^t.(L.L^t)^-1.x=x^t.L.L^t.x=z^t.z

我相信你做不到。Cholesky分解不仅需要一个方阵,而且需要一个厄米矩阵,并且需要一个正定矩阵来唯一。它基本上是一个LU分解,附带条件是L=U'。事实上,该算法经常被用作数值检查给定矩阵是否正定的一种方法。看

也就是说,协方差矩阵根据定义是对称正半定的,所以你们应该能够在它上面做cholesky


编辑:当你计算它时,你的矩阵
C=np.dot(G,G.T)
应该是对称的,但可能有什么地方不对。您可以尝试强制对称化它
C=(C+C.T)/2.0
,然后再次尝试
chol(C)

为什么不使用?2。)我非常确定所有分解都需要平方矩阵(通常需要厄米矩阵或酉矩阵,它们是平方的)。Numpy显然在抱怨矩阵的平方度。你不应该计算数组中每对14个向量之间的距离吗?每对的协方差矩阵是平方的。Wikipedia:Cholesky分解适用于:平方、对称、正定矩阵A;你真的right@larsmans我不想直接调用一个命令来计算作为输入参数所需的倒数。re:第二次编辑时,不需要Python循环-您可以使用广播一次将所有行居中:
G-=G.mean(0)[None,:]