python - sklearn 管道 - 在管道中应用多项式特征变换后应用样本权重

标签 python python-2.7 scikit-learn pipeline

我想应用样本权重,同时使用 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() takes at most 3 arguments (4 given) 在这个简单的例子中,修改代码没有问题,但是当我想在我的真实代码中对我的真实数据运行几个不同的测试时,能够使用管道和样本权重

最佳答案

Pipelinefit方法中提到了**fit_params文档。您必须指定要将参数应用到管道的哪个步骤。您可以按照文档中的命名规则来实现:

For this, it enables setting parameters of the various steps using their names and the parameter name separated by a ‘__’, as in the example below.

综上所述,尝试将最后一行更改为:

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

This is a good example如何在管道中使用参数。

关于python - sklearn 管道 - 在管道中应用多项式特征变换后应用样本权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36205850/

相关文章:

python - 使用参数 stop_words 时 scikit 学习 TfidfVectorizer 时出错

python - 将多类分类器转换为分层多类分类器

python - 如何将多个 Python 源文件连接成一个文件?

python - 如何使用 Gekko 估计 FOPDT 方程中的 theta 值?

django - 如何在 AWS Beanstalk 上安装 cffi 包

python - 如何修改csv文件中的重复字段?

scikit-learn - 使用随机森林时在 scikit-learn 中表示因子变量的方法是什么?

python - PyGame 窗口中未显示矩形

python - 使用 Python 在 MySQL 表中插入值

python - 如何在 C 和 Python 中从字节中提取 LSB?