【问题标题】:sklearn pipeline - Applying sample weights after applying a polynomial feature transformation in a pipelinesklearn 管道 - 在管道中应用多项式特征变换后应用样本权重
【发布时间】:2016-07-12 09:04:03
【问题描述】:

我想应用样本权重,同时使用来自 sklearn 的管道,它应该进行特征转换,例如多项式,然后应用回归量,例如额外树。

我在下面的两个示例中使用了以下包:

from sklearn.ensemble import ExtraTreesRegressor
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures

只要我分别转换特征并在之后生成和训练模型,一切都会很好:

#Feature generation
X = np.random.rand(200,4)
Y = np.random.rand(200)

#Feature transformation
poly = PolynomialFeatures(degree=2)
poly.fit_transform(X)

#Model generation and fit
clf = ExtraTreesRegressor(n_estimators=5, max_depth = 3)
weights = [1]*100 + [2]*100
clf.fit(X,Y, weights)

但是在管道中这样做是行不通的:

#Pipeline generation
pipe = Pipeline([('poly2', PolynomialFeatures(degree=2)), ('ExtraTrees', ExtraTreesRegressor(n_estimators=5, max_depth = 3))])

#Feature generation
X = np.random.rand(200,4)
Y = np.random.rand(200)

#Fitting model
clf = pipe
weights = [1]*100 + [2]*100
clf.fit(X,Y, weights)

我收到以下错误:TypeError: fit() 最多接受 3 个参数(给定 4 个) 在这个简单的例子中,修改代码是没有问题的,但是当我想在我的真实代码中对我的真实数据运行几个不同的测试时,能够使用管道和样本权重

【问题讨论】:

    标签: python python-2.7 scikit-learn pipeline


    【解决方案1】:

    Pipeline 文档的fit 方法中提到了**fit_params。您必须指定要将参数应用到管道的哪个步骤。您可以通过遵循文档中的命名规则来实现这一点:

    为此,它可以使用它们的名称和由“__”分隔的参数名称来设置各个步骤的参数,如下例所示。

    说了这么多,试着把最后一行改成:

    clf.fit(X,Y, **{'ExtraTrees__sample_weight': weights})
    

    This is a good example 了解如何使用管道中的参数。

    【讨论】:

    • 谢谢,凯文!这解决了问题,这个例子很好地了解了参数在管道中是如何工作的!
    猜你喜欢
    • 2018-01-09
    • 1970-01-01
    • 2017-12-23
    • 2016-03-26
    • 2016-12-11
    • 2016-07-06
    • 2019-08-10
    • 2019-05-02
    • 2014-11-07
    相关资源
    最近更新 更多