Skip to content

Instantly share code, notes, and snippets.

@tam17aki
Last active June 11, 2023 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tam17aki/7f341ee231ce152b833b88439f57553f to your computer and use it in GitHub Desktop.
Save tam17aki/7f341ee231ce152b833b88439f57553f to your computer and use it in GitHub Desktop.
Mahalanobis Depth in Python.
# -*- coding: utf-8 -*-
"""Mahalanobis Depth."""
# Author: Akira Tamamori <tamamori5917@gmail.com>
# License: BSD 2 clause
from sklearn.covariance import EmpiricalCovariance, MinCovDet
from sklearn.utils import check_array, check_random_state
class MHD:
"""MHD class.
This class computes Mahalanobis depth.
Parameters
----------
cov_type: str, optional (default="emp")
Covariance estimator.
If ``cov_type'' is "emp", EmpiricalCovariance() is used;
If ``cov_type'' is "mincov", MinCovDet() is used.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance
used by np.random.
"""
def __init__(self, random_state=None):
super().__init__()
self.cov_type = "emp"
self.random_state = check_random_state(random_state)
self.depth_values = None
self.robust_cov = None
def fit(self, X):
"""Fit detector.
Parameters
----------
X : numpy array of shape (n_samples, n_features)
The input samples.
Returns
-------
self : object
Fitted estimator.
"""
if self.cov_type == "emp":
self.robust_cov = EmpiricalCovariance().fit(X)
elif self.cov_type == "mincov":
self.robust_cov = MinCovDet(random_state=self.random_state).fit(X)
else:
raise ValueError(
f"cov_type={self.cov_type} " f"must be between 'emp' or 'mincov'."
)
self.depth_values = 1 / (1 + self.robust_cov.mahalanobis(X))
return self
def depth_function(self, X):
"""Predict raw depth values of X using the fitted object.
Parameters
----------
X : numpy array of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only
if they are supported by the base estimator.
Returns
-------
depth_values : numpy array of shape (n_samples,)
The depth value of the input samples.
"""
X = check_array(X)
depth_values = 1 / (1 + self.robust_cov.mahalanobis(X))
return depth_values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment