加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何计算非方矩阵的Cholesky分解,以便用’numpy’计算

发布时间:2020-12-20 13:42:33 所属栏目:Python 来源:网络整理
导读:如何计算非正方矩阵的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
如何计算非正方矩阵的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:UsersMatthiasCVsrcfitting_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:UsersMatthiasAppDataLocalEnthoughtCanopyUserlibsite-packagesnumpylinalglinalg.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:UsersMatthiasAppDataLocalEnthoughtCanopyUserlibsite-packagesnumpylinalglinalg.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实现:Mahalanobis distance inverting the covariance matrix

编辑:chol(a)= linalg.cholesky(a).T
矩阵的cholesky分解(matlab中的chol(a)返回一个上三角矩阵,但linalg.cholesky(a)返回一个下三角矩阵)(来源:http://wiki.scipy.org/NumPy_for_Matlab_Users)

EDIT2:

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分解不仅需要一个方阵,而且需要一个Hermitian矩阵和一个唯一性的正定矩阵.它基本上是LU分解,条件是L = U’.事实上,该算法经常被用作数字检查给定矩阵是正定的方法.见 Wikipedia.

也就是说,根据定义,协方差矩阵是对称的正半定,所以你应该能够对它进行cholesky.

编辑:当你计算它时,你的矩阵C = np.dot(G,G.T)应该是对称的,但也许是错误的.您可以尝试强制对称它C =(C C.T)/2.0,并再次尝试chol(C).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读