【发布时间】:2021-10-11 07:20:40
【问题描述】:
我想创建一个包含所有必要(预处理)步骤的管道。在我的情况下,这是估算、X 和 y 的编码、缩放、特征选择和估计器。
我编写了以下代码,但它给了我一个错误ValueError: too many values to unpack (expected 2)。
# Creating a scikit learn pipeline for preprocessing
## Selecting categorical and numeric features
numerical_ix = X.select_dtypes(include=np.number).columns
categorical_ix = X.select_dtypes(exclude=np.number).columns
## Create preprocessing pipelines for each datatype
numerical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())])
categorical_transformer = Pipeline(steps=[
('encoder', OrdinalEncoder()),
('scaler', StandardScaler())])
## Putting the preprocessing steps together
preprocessor = ColumnTransformer([
('numerical', numerical_transformer, numerical_ix),
('categorical', categorical_transformer, categorical_ix)],
remainder='passthrough')
## Create example pipeline with kNN as estimator
example_pipe = Pipeline(steps=[
('preprocessor', preprocessor),
('label', LabelEncoder(), y),
('selector', SelectKBest(k=len(X.columns))), # keep the same amount of columns for now
('classifier', KNeighborsClassifier())
])
## Test pipeline
example_pipe.fit_transform(X_train, y_train)
example_pipe.score(X_test, y_test)
我读过一些关于这个话题的文章,似乎LabelEncoder() 只收到 1 个参数。这就是为什么我试图指定它应该只在创建y 时处理example_pipe。
有没有办法在管道中包含标签编码,还是必须事先完成(例如使用 pandas)?如果可能,我如何在管道中包含标签编码?
【问题讨论】:
标签: python scikit-learn pipeline