Perhaps this is elementary, but I cannot find a good example of using mahalanobis
distance in sklearn
.
I can't even get the metric like this:
from sklearn.neighbors import DistanceMetric
DistanceMetric.get_metric('mahalanobis')
This throws an error: TypeError: 0-dimensional array given. Array must be at least two-dimensional
.
But, I can't even seem to get it to take an array:
DistanceMetric.get_metric('mahalanobis', [[0.5],[0.7]])
throws:
TypeError: get_metric() takes exactly 1 positional argument (2 given)
I checked out the docs here and here. But, I don't see what types of arguments it is expecting.
Is there an example of using the Mahalanobis distance that I can see?
MahalanobisDistance
is expecting a parameterV
which is the covariance matrix, and optionally another parameterVI
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 filescikit-learn/sklearn/neighbors/dist_metrics.pyx
in the sklearn repo.Example:
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, settingalgorithm='auto'
(which defaults to'ball_tree'
) doesn't seem to work; so givenX
from the code above you can do: