【问题标题】:Mahalanobis Distance doesn't match between rpy2 and scipyrpy2 和 scipy 之间的 Mahalanobis 距离不匹配
【发布时间】:2013-11-11 12:38:30
【问题描述】:

我一直在使用 rpy2 来计算测试向量和先验分布之间的马氏距离。我想放弃 rpy2 并转向 scipy,但是当我测试它时,rpy2 和 scipy 不会返回相同的结果。这是我的示例代码。

import numpy as np
from scipy import linalg
from scipy.spatial.distance import mahalanobis as mahalanobis
import rpy2.robjects as robjects

# The vector to test.
test_values = [692.5816522801106, 1421.4737901031651, 6.117859, 7.259449]
test_values_r = robjects.FloatVector(test_values)
test_values_np = np.array(test_values)

# The covariance matrix from the prior distribution
covs = [15762.87, 13486.23, 34.61164, 22.15451, 
        13486.23, 36003.67, 33.8431, 30.52712, 
        34.61164, 33.8431, 0.4143354, 0.1125765, 
        22.15451, 30.52712, 0.1125765, 0.2592451]
covs_np = np.reshape(np.array(covs), (4,-1))
covs_r  = robjects.r["matrix"](robjects.FloatVector(covs), nrow = 4)

# The means of the prior distribution
centers = [808.0645, 1449.711, 4.8443, 4.95776]
centers_np = np.array(centers)
centers_r  = robjects.FloatVector(centers)

r_dist = robjects.r["mahalanobis"](test_values_r, centers_r, covs_r)
# <FloatVector - Python:0x1052275a8 / R:0x10701bfa8>
# [29.782287]

np_dist = mahalanobis(test_values_np, centers_np, linalg.inv(covs_np))
# 5.4573150053873185

我是否遗漏了一些明显的东西?

【问题讨论】:

    标签: python numpy scipy rpy2


    【解决方案1】:

    R 函数返回 平方 马氏距离(例如,参见 here)。

    因此:

    >>> r_dist[0]
    29.782287068025585
    >>> np_dist
    5.4573150053873185
    >>> np_dist**2 - r_dist[0]
    3.5527136788005009e-15
    

    【讨论】:

      猜你喜欢
      • 2013-04-22
      • 2017-10-14
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2021-06-25
      • 2018-08-08
      • 1970-01-01
      • 2014-07-09
      相关资源
      最近更新 更多