Can I add outlier detection and removal to Scikit learn Pipeline?

2622 views python

I want to create a Pipeline in Scikit-Learn with a specific step being outlier detection and removal, allowing the transformed data to be passed to other transformers and estimator.

I have searched SE but can't find this answer anywhere. Is this possible?

answered question

1 Answer


Yes. Subclass the TransformerMixin and build a custom transformer. Here is an extension to one of the existing outlier detection methods:

from sklearn.pipeline import Pipeline, TransformerMixin
from sklearn.neighbors import LocalOutlierFactor

class OutlierExtractor(TransformerMixin):
    def __init__(self, **kwargs):
        Create a transformer to remove outliers. A threshold is set for selection
        criteria, and further arguments are passed to the LocalOutlierFactor class

        Keyword Args:
            neg_conf_val (float): The threshold for excluding samples with a lower
               negative outlier factor.

            object: to be used as a transformer method as part of Pipeline()
            self.threshold = kwargs.pop('neg_conf_val')
        except KeyError:
            self.threshold = -10.0
        self.kwargs = kwargs

    def transform(self, X):
        Uses LocalOutlierFactor class to subselect data based on some threshold

            ndarray: subsampled data

            X should be of shape (n_samples, n_features)
        x = np.asarray(X)
        lcf = LocalOutlierFactor(**self.kwargs)
        return x[lcf.negative_outlier_factor_ > self.threshold, :]

    def fit(self, *args, **kwargs):
        return self

Then create a pipeline as:

pipe = Pipeline([('outliers', OutlierExtraction()), ...])

posted this

Have an answer?


Please login first before posting an answer.