python distance_to_python - How to use mahalanobis distance in sklearn DistanceMetrics?

answer 1

MahalanobisDistance is expecting a parameter V which is the covariance matrix, and optionally another parameter VI which is the inverse of the covariance matrix. Furthermore, both of these parameters are named and not positional.

Also check the docstring for the class MahalanobisDistance in the file scikit-learn/sklearn/neighbors/dist_metrics.pyx in the sklearn repo.

Example:

In [18]: import numpy as np

In [19]: from sklearn.datasets import make_classification

In [20]: from sklearn.neighbors import DistanceMetric

In [21]: X, y = make_classification()

In [22]: DistanceMetric.get_metric('mahalanobis', V=np.cov(X))

Out[22]:

Edit:

For some reasons (bug?), you can't pass the distance object to the NearestNeighbor constructor, but need to use the name of the distance metric. Also, setting algorithm='auto' (which defaults to 'ball_tree') doesn't seem to work; so given X from the code above you can do:

In [23]: nn = NearestNeighbors(algorithm='brute',

metric='mahalanobis',

metric_params={'V': np.cov(X)})

# returns the 5 nearest neighbors of that sample

In [24]: nn.fit(X).kneighbors(X[0, :])

Out[24]: (array([[ 0., 3.21120892, 3.81840748, 4.18195987, 4.21977517]]),

array([[ 0, 36, 46, 5, 17]]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值