我正在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]
您计算并存储该相关性以及要在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]