Skip to content

Instantly share code, notes, and snippets.

Last active June 11, 2023 11:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Mahalanobis Depth in Python.
# -*- coding: utf-8 -*-
"""Mahalanobis Depth."""
# Author: Akira Tamamori <>
# 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.
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):
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.
X : numpy array of shape (n_samples, n_features)
The input samples.
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)
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.
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.
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