【发布时间】:2025-12-04 00:25:02
【问题描述】:
所以我试图在scikit-learn 中使用make_pipeline 来清理我的数据(替换缺失值,然后清理异常值,将编码函数应用于分类变量,然后最后通过RandomForestRegressor 添加随机森林回归器. 输入是DataFrame。最终我想通过GridSearchCV 搜索回归器的最佳超参数。
为了做到这一点,我按照here 的建议构建了一些继承TransformerMixin 类的自定义类。这是我到目前为止所拥有的
from sklearn.pipeline import make_pipeline
from sklearn.base import TransformerMixin
import pandas as pd
class Cleaning(TransformerMixin):
def __init__(self, column_labels):
self.column_labels = column_labels
def fit(self, X, y=None):
return self
def transform(self, X):
"""Given a dataframe X with predictors, clean it."""
X_imputed, medians_X = median_imputer(X) # impute all missing numeric data with median
quantiles_X = get_quantiles(X_imputed, self.column_labels)
X_nooutliers, _ = replace_outliers(X_imputed, self.column_labels, medians_X, quantiles_X)
return X_nooutliers
class Encoding(TransformerMixin):
def __init__(self, encoder_list):
self.encoder_list = encoder_list
def fit(self, X, y=None):
return self
def transform(self, X):
"""Takes in dataframe X and applies encoding transformation to them"""
return encode_data(self.encoder_list, X)
但是,当我运行以下代码行时出现错误:
import category_encoders as ce
pipeline_cleaning = Cleaning(column_labels = train_labels)
OneHot_binary = ce.OneHotEncoder(cols = ['new_store'])
OneHot = ce.OneHotEncoder(cols= ['transport_availability'])
Count = ce.CountEncoder(cols = ['county'])
pipeline_encoding = Encoding([OneHot_binary, OneHot, Count])
baseline = RandomForestRegressor(n_estimators=500, random_state=12)
make_pipeline([pipeline_cleaning, pipeline_encoding,baseline])
错误是Last step of Pipeline should implement fit or be the string 'passthrough'。我不明白为什么?
编辑:最后一行有轻微错字,正确。传递给make_pipeline 的列表中的第三个元素是回归量
【问题讨论】:
标签: python scikit-learn pipeline random-forest cross-validation