### 欧式距离与马氏距离的概念
#### 欧式距离
欧式距离是最常见的两点间直线距离,在n维空间中,如果存在两个点 \( A(x_1, y_1,...,z_1) \) 和 \( B(x_2,y_2,...,z_2) \),那么它们之间的欧几里得距离可以通过下面的公式计算:
\[ d_{Euclidean}(A,B)=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2+...+(z_2-z_1)^2} \]
该度量方法简单直观,适用于各维度相互独立的情况。
#### 马氏距离
相比之下,马氏距离考虑到了各个变量间的协方差影响。设有一个随机向量X=[\( X_1,X_2,\ldots ,X_p \)]T服从多元正态分布N(μ,Σ),则任意一点P到均值μ的马哈拉诺比斯距离定义为:
\[ D_M(P)=(X-\mu )^{T}\Sigma ^{-1}(X-\mu ). \]
这里Σ表示协方差矩阵[^1]。
### 应用场景对比
- **欧式距离的应用**
- 当数据集中各属性之间不存在线性相关性或者关联较弱时适用;
- 计算简便快速,适合大规模数据分析;
- **马氏距离的优势**
- 能够处理具有不同尺度以及可能存在相关性的多维特征;
- 对于受噪声干扰较大的情况更为稳健;
- 常用于模式识别领域内的分类器设计当中,尤其是在生物统计学等领域有着广泛的应用价值。
综上所述,选择何种距离测度取决于具体问题背景下的特性需求。当面对复杂结构化数据集时,考虑到其内部可能存在的依赖关系,通常推荐优先尝试使用马氏距离进行建模分析。
```python
import numpy as np
from scipy.spatial.distance import mahalanobis, euclidean
def calculate_distances(point_a, point_b, cov_matrix=None):
"""
Calculate both Euclidean and Mahalanobis distances between two points.
Parameters:
point_a (array-like): First data point of shape (n_features,)
point_b (array-like): Second data point of same shape as `point_a`
cov_matrix (ndarray or NoneType): Covariance matrix used for calculating the Mahalanobis distance
Returns:
tuple: Pair containing float values representing respectively the Euclidean and Mahalanobis distances
"""
euc_dist = euclidean(point_a, point_b)
if cov_matrix is not None:
inv_covmat = np.linalg.inv(cov_matrix)
maha_dist = mahalanobis(point_a, point_b, inv_covmat)
else:
maha_dist = None
return euc_dist, maha_dist
# Example usage with random data generation
np.random.seed(42)
data_points = np.random.multivariate_normal([0, 0], [[1, .8], [.8, 1]], size=100).T
cov_mat = np.corrcoef(data_points)
example_point_pair = ([.5,.6],[-.3,-.9])
eudist,mahdist = calculate_distances(*example_point_pair,cov_mat)
print(f'Euclidean Distance:{eudist:.3f}')
if mahdist is not None:
print(f'Mahalanobis Distance:{mahdist:.3f}')
```