所有中间步骤都应该是transformers并实现fit和transform

2024-06-01 12:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用重要的特征选择来实现流水线,然后使用相同的特征来训练我的随机森林分类器。下面是我的代码。

m = ExtraTreesClassifier(n_estimators = 10)
m.fit(train_cv_x,train_cv_y)
sel = SelectFromModel(m, prefit=True)
X_new = sel.transform(train_cv_x)
clf = RandomForestClassifier(5000)

model = Pipeline([('m', m),('sel', sel),('X_new', X_new),('clf', clf),])
params = {'clf__max_features': ['auto', 'sqrt', 'log2']}

gs = GridSearchCV(model, params)
gs.fit(train_cv_x,train_cv_y)

因此,X_new是通过SelectFromModelsel.transform选择的新功能。然后我想训练我的射频使用新的功能选择。

我得到以下错误:

All intermediate steps should be transformers and implement fit and transform, ExtraTreesClassifier ...


Tags: and功能gsnewmodeltransformtrainparams
1条回答
网友
1楼 · 发布于 2024-06-01 12:40:00

正如回溯所说:管道中的每个步骤都需要有一个fit()transform()方法(除了最后一个,它只需要fit())。这是因为管道在每一步都将数据的转换链接在一起。

sel.transform(train_cv_x)不是估计量,不符合此标准。

事实上,看起来基于你的努力,你可以离开这一步。在内部,('sel', sel)已经完成了这个转换——这就是为什么它包含在管道中。

其次,ExtraTreesClassifier(管道中的第一步)也没有transform()方法。您可以在docstring类中验证here。有监督的学习模型不是用来转换数据的,而是用来对数据进行拟合和预测的。

什么类型的类能够进行转换?

不必太多地阅读字里行间的内容,这对你来说是可行的:

  1. 首先使用train_test_split拆分x和y。由此产生的测试数据集被保留用于最终测试,并且GridSearchCV交叉验证中的列车数据集将进一步分解为更小的列车和验证集。
  2. 建立一个满足你的回溯试图告诉你的管道。
  3. 将该管道传递到GridSearchCV.fit()该网格搜索在X~u train/y~u train上,然后.score()在X~u test/y~u test上。

大致上,应该是这样的:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=444)

sel = SelectFromModel(ExtraTreesClassifier(n_estimators=10, random_state=444), 
                      threshold='mean')
clf = RandomForestClassifier(n_estimators=5000, random_state=444)

model = Pipeline([('sel', sel), ('clf', clf)])
params = {'clf__max_features': ['auto', 'sqrt', 'log2']}

gs = GridSearchCV(model, params)
gs.fit(X_train, y_train)

# How well do your hyperparameter optimizations generalize
# to unseen test data?
gs.score(X_test, y_test)

两个例子供进一步阅读:

相关问题 更多 >