Skip to content

Instantly share code, notes, and snippets.

@tam17aki
Last active September 15, 2022 16:25
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/f05f6c2d7bca67c106d2a43ea83c94af to your computer and use it in GitHub Desktop.
Save tam17aki/f05f6c2d7bca67c106d2a43ea83c94af to your computer and use it in GitHub Desktop.
Unsupervised Outlier Detection based on Random Projection Outlyingness (RPO).
# -*- coding: utf-8 -*-
"""Unsupervised Outlier Detection based on Random Projection Outlyingness (RPO).
"""
# Author: Akira Tamamori <tamamori5917@gmail.com>
# License: BSD 2 clause
from __future__ import division, print_function
import numpy as np
from pyod.models.base import BaseDetector
from scipy import stats
from sklearn.preprocessing import normalize
from sklearn.utils import check_array, check_random_state
from sklearn.utils.validation import check_is_fitted
class RPO(BaseDetector):
"""RPO class for outlier detection.
Random Projection Outlyingness (RPO) is a measure of outlyingness of data point.
In one-dimensional case, outlyingness from the center of the data distribution
can be evaluated by using the median and the median absolute deviation.
They are known to be less sensitive to outliers.
The definition can be extended so that the outlyingness calculated for
one-dimensional data can also be calculated for d-dimensional data.
The d-dimensional projection axis is randomly sampled from the d-dimensional unit
hypersphere, and the entire dataset is projected onto one-dimensional space.
The outlyingness is then calculated over a one-dimensional dataset.
Donoho, D. L., Gasko, M., et al. Breakdown properties of
location estimates based on halfspace depth and projected
outlyingness. The Annals of Statistics, 20(4):1803–1827, 1992.
Parameters
----------
n_projections : int (0, n_samples), optional (default=100)
The number of random projection axes.
contamination : float in (0., 0.5), optional (default=0.1)
The amount of contamination of the data set,
i.e. the proportion of outliers in the data set. Used when fitting to
define the threshold on the decision function.
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.
Attributes
----------
decision_scores_ : numpy array of shape (n_samples,)
The outlier scores of the training data.
The higher, the more abnormal. Outliers tend to have higher
scores. This value is available once the detector is
fitted.
threshold_ : float
The threshold is based on ``contamination``. It is the
``n_samples * contamination`` most abnormal samples in
``decision_scores_``. The threshold is calculated for generating
binary outlier labels.
labels_ : int, either 0 or 1
The binary labels of the training data. 0 stands for inliers
and 1 for outliers/anomalies. It is generated by applying
``threshold_`` on ``decision_scores_``.
"""
def __init__(self, contamination=0.1, n_projections=100, random_state=None):
super().__init__(contamination=contamination)
self.n_projections = n_projections
self.random_state = check_random_state(random_state)
self.decision_scores_ = None
self.proj_axes = None
self.median = None
self.median_dev = None
def fit(self, X, y=None):
"""Fit detector. y is ignored in unsupervised methods.
Parameters
----------
X : numpy array of shape (n_samples, n_features)
The input samples.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Fitted estimator.
"""
# validate inputs X and y (optional)
X = check_array(X)
self._set_n_classes(y)
# draw random axes on hypersphere
self.proj_axes = self.random_state.randn(X.shape[1], self.n_projections)
self.proj_axes = normalize(self.proj_axes) # normalized vectors on hypersphere
# project X onto random axis via inner product
proj_data = X.dot(self.proj_axes) # (n_samples, n_proj)
self.median = np.median(proj_data, axis=0) # (n_proj)
self.median = np.expand_dims(self.median, axis=0) # (1, n_proj)
self.median_dev = stats.median_abs_deviation(proj_data, axis=0) # (n_proj)
self.median_dev = np.expand_dims(self.median_dev, axis=0) # (1, n_proj)
# compute random projection outlyingness
self.decision_scores_ = np.max(
np.abs(proj_data - self.median) / self.median_dev, axis=1
)
self._process_decision_scores()
return self
def decision_function(self, X):
"""Predict raw anomaly score of X using the fitted detector.
The anomaly score of an input sample is computed based on different
detector algorithms. For consistency, outliers are assigned with
larger anomaly scores.
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
-------
anomaly_scores : numpy array of shape (n_samples,)
The anomaly score of the input samples.
"""
check_is_fitted(self, ["decision_scores_", "threshold_", "labels_"])
X = check_array(X)
proj_data = X.dot(self.proj_axes) # project X onto random axis
anomaly_scores = np.max(
np.abs(proj_data - self.median) / self.median_dev, axis=1
)
return anomaly_scores
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment