【问题标题】:Custom Transformer in sklearnsklearn中的自定义变压器
【发布时间】:2019-07-09 03:55:36
【问题描述】:

我正在 sklearn 中构建一个转换器,它会丢弃相关系数低于指定阈值的特征。

它适用于训练集。但是,当我转换测试集时。测试集上的所有特征都消失了。我假设转换器正在计算测试数据和训练标签之间的相关性,并且由于这些都很低,它正在丢弃所有特征。如何让它只计算训练集的相关性,并从变换的测试集中删除这些特征?

class CorrelatedFeatures(BaseEstimator, TransformerMixin): #Selects only features that have a correlation coefficient higher than threshold with the response label
    def __init__(self, response, threshold=0.1):
        self.threshold = threshold
        self.response = response
    def fit(self, X, y=None):
        return self
    def transform(self, X, y=None):
        df = pd.concat([X, self.response], axis=1)
        cols = df.columns[abs(df.corr()[df.columns[-1]]) > self.threshold].drop(self.response.columns)
        return X[cols]

【问题讨论】:

    标签: python machine-learning scikit-learn data-science transformer


    【解决方案1】:

    您计算并存储该相关性以及要在fit() 中删除的列,而在transform() 中只需转换这些列。

    类似这样的:

    ....
    ....
    
    def fit(self, X, y=None):
        df = pd.concat([X, self.response], axis=1)
        self.cols = df.columns[abs(df.corr()[df.columns[-1]]) > self.threshold].drop(self.response.columns)
        return self
    def transform(self, X, y=None):
        return X[self.cols]
    

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 1970-01-01
      • 2018-02-15
      • 2018-01-02
      • 2019-08-04
      • 2014-11-06
      • 2020-01-13
      • 2023-03-18
      相关资源
      最近更新 更多