【问题标题】:How to calculate Mahalanobis Distance between randomly generated values?如何计算随机生成的值之间的马氏距离?
【发布时间】:2019-09-24 17:40:38
【问题描述】:

我目前正在学习马氏距离,我觉得这很困难。为了更好地理解这个想法,我生成了 2 组随机值(x 和 y)和一个随机点,其中所有 3 的平均值 = 0 和标准偏差 = 1。如何计算它们之间的马氏距离?请在下面找到我的 Python 代码 非常感谢您的帮助!

import numpy as np
from numpy import cov
from scipy.spatial import distance


generate 20 random values where mean = 0 and standard deviation = 1, assign one set to x and one to y

x = [random.normalvariate(0,1) for i in range(20)]
y = [random.normalvariate(0,1) for i in range(20)]
r_point = [random.normalvariate(0,1)] #that's my random point


sigma = cov(x, y)
print(sigma)
print("random point =", r_point)

#use the covariance to calculate the mahalanobis distance from a random point```

【问题讨论】:

  • Mahalanobis_distance 维基百科页面有一个 Python 软件实现的链接。

标签: python numpy distance mahalanobis


【解决方案1】:

这是一个示例,说明如何计算点 r_point 到某些数据的马氏距离。 Mahalanobis 距离考虑了您测量距离的数据的方差和相关性(使用其协方差矩阵的逆矩阵)。在这里,由于数据的分布(0 均值和 1 标准差),马氏距离和欧几里得距离应该非常接近。对于其他数据,它们会有所不同。

import numpy as np

N = 5000
mean = 0.0
stdDev = 1.0
data = np.random.normal(mean, stdDev, (2, N))   # 2D random points

r_point = np.random.randn(2)
cov = np.cov(data)

mahalanobis_dist = np.sqrt(r_point.T @ np.linalg.inv(cov) @ r_point)
print("Mahalanobis distance = ", mahalanobis_dist)

euclidean_dist = np.sqrt(r_point.T @ r_point)
print("Euclidean distance = ", euclidean_dist)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2015-11-01
    • 2017-11-21
    • 2015-06-25
    相关资源
    最近更新 更多