我想要同时使用sklearn的流水线(pipeline)进行特征转换(例如多项式),并应用一个回归器(例如ExtraTrees),以及对样本进行加权。
在下面的两个示例中,我将使用以下软件包:
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 个。在这个简单的例子中,修改代码没有问题,但是当我想在我的真实代码中对几个不同的测试运行时,使用管道和样本权重非常重要。