【发布时间】:2021-09-25 17:40:28
【问题描述】:
我正在尝试构建一个转换器,它允许我指定一个特征,然后过滤掉这个特征的任何异常值。异常值是指特征值偏离中位数超过分布宽度 2 倍的观测值。
以下是我目前拥有的代码。有 3 行代码我不确定它们是否正确。请让我知道我是否做错了以及如何纠正它们。谢谢!
import numpy as np
class FilterOutliersTransformer(base.BaseEstimator, base.TransformerMixin):
def __init__(self, feature):
self.feature = feature
def fit(self, X, y=None):
Q1 = np.percentile(X.loc[:, self.feature], 25)
Q3 = np.percentile(X.loc[:, self.feature], 75)
deviation_allowed = 1.5*(Q3 - Q1)
lower_bound = Q1 - deviation_allowed
upper_bound = Q3 + deviation_allowed
# not sure here 1
self.params_ = [lower_bound, upper_bound]
# not sure here 2
return self
def transform(self, X, y=None):
X_transformed = X[(X[self.feature] > self.params_[0]) & (X[self.feature] < self.params_[1])]
# not sure here 3
return X_transformed
【问题讨论】:
-
您几乎可以肯定调用父类的构造函数,例如通过在构造函数中添加一行
super().__init__()。此外,您标记为“不确定”的三行中有两行是简单的返回语句;在成为错误的意义上,它们不能是“不正确的”。这取决于您希望如何在程序的其余部分中使用这些功能。而return self很少有用,因为调用代码必须已经引用了self才能调用函数。
标签: python scikit-learn transformer