在scikit-learn中重复FeatureUnion

时间:2018-08-05 22:11:42

标签: python scikit-learn pipeline

我正在scikit-learn中学习管道和FeatureUnions,因此想知道是否可以在类上重复应用'make_union'吗?

考虑以下代码:

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.linear_model import LogisticRegression
import sklearn.datasets as d

class IrisDataManupulation(BaseEstimator, TransformerMixin):
    """
       Raise the matrix of feature in power
    """
    def __init__(self, power=2):
        self.power = power

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        return np.power(X, self.power)

iris_data = d.load_iris()

X, y = iris_data.data, iris_data.target


# feature union:
fu = FeatureUnion(transformer_list=[('squared', IrisDataManupulation(power=2)),
                               ('third', IrisDataManupulation(power=3))])

问题 有什么精巧的方法来创建FeatureUnion,而无需重复相同的转换器,而是传递参数列表?

例如:

fu_new = FeatureUnion(transformer_list=[('raise_power', IrisDataManupulation(), 
                      param_grid = {'raise_power__power':[2,3]})

1 个答案:

答案 0 :(得分:2)

您可以在一个自定义变形金刚中移动所有力量。我们可以更改您的IrisDataManupulation来处理其中的权力列表:

class IrisDataManupulation(BaseEstimator, TransformerMixin):

    def __init__(self, powers=[2]):
        self.powers = powers

    def transform(self, X):
        powered_arrays = []
        for power in self.powers:
            powered_arrays.append(np.power(X, power))

        return np.hstack(powered_arrays)

然后,您可以使用此新转换器代替FeatureUnion:

fu = IrisDataManupulation(powers=[2,3])

注意:如果要从原始特征生成多项式特征,我建议see PolynomialFeatures,它除了可以生成特征之间的其他相互作用之外,还可以生成所需的幂。