代码之家  ›  专栏  ›  技术社区  ›  Attack68

我可以将异常检测和删除添加到Scikit学习管道吗?

  •  2
  • Attack68  · 技术社区  · 7 年前

    我搜索了SE,但到处都找不到这个答案。这可能吗?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Prayson W. Daniel    6 年前

    对。对transformerMaxin进行子类化并构建一个自定义的transformer。以下是对现有异常值检测方法之一的扩展:

    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.
    
            Returns:
                object: to be used as a transformer method as part of Pipeline()
            """
    
            self.threshold = kwargs.pop('neg_conf_val', -10.0)
    
            self.kwargs = kwargs
    
        def transform(self, X, y):
            """
            Uses LocalOutlierFactor class to subselect data based on some threshold
    
            Returns:
                ndarray: subsampled data
    
            Notes:
                X should be of shape (n_samples, n_features)
            """
            X = np.asarray(X)
            y = np.asarray(y)
            lcf = LocalOutlierFactor(**self.kwargs)
            lcf.fit(X)
            return (X[lcf.negative_outlier_factor_ > self.threshold, :],
                    y[lcf.negative_outlier_factor_ > self.threshold])
    
        def fit(self, *args, **kwargs):
            return self
    

    然后将管道创建为:

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