注意
转到末尾 下载完整的示例代码。或通过JupyterLite或Binder在您的浏览器中运行此示例
混合类型的列转换器#
此示例说明如何使用ColumnTransformer
将不同的预处理和特征提取管道应用于不同的特征子集。对于包含异构数据类型的数据集,这尤其方便,因为我们可能希望缩放数值特征并对类别特征进行独热编码。
在此示例中,数值数据在均值插补后进行标准缩放。类别数据通过OneHotEncoder
进行独热编码,这为缺失值创建了一个新类别。我们通过卡方检验选择类别来进一步降低维度。
此外,我们展示了两种不同的方法来将列分派到特定的预处理器:按列名和按列数据类型。
最后,预处理管道与简单的分类模型一起使用Pipeline
集成到完整的预测管道中。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.datasets import fetch_openml
from sklearn.feature_selection import SelectPercentile, chi2
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RandomizedSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
np.random.seed(0)
从https://www.openml.org/d/40945加载数据
X, y = fetch_openml("titanic", version=1, as_frame=True, return_X_y=True)
# Alternatively X and y can be obtained directly from the frame attribute:
# X = titanic.frame.drop('survived', axis=1)
# y = titanic.frame['survived']
通过选择列名使用ColumnTransformer
我们将使用以下特征训练我们的分类器
数值特征
age
:浮点数;fare
:浮点数。
类别特征
embarked
:编码为字符串{'C', 'S', 'Q'}
的类别;sex
:编码为字符串{'female', 'male'}
的类别;pclass
:序数整数{1, 2, 3}
。
我们为数值数据和类别数据创建预处理管道。请注意,pclass
可以被视为类别特征或数值特征。
numeric_features = ["age", "fare"]
numeric_transformer = Pipeline(
steps=[("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler())]
)
categorical_features = ["embarked", "sex", "pclass"]
categorical_transformer = Pipeline(
steps=[
("encoder", OneHotEncoder(handle_unknown="ignore")),
("selector", SelectPercentile(chi2, percentile=50)),
]
)
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
]
)
将分类器添加到预处理管道。现在我们有了一个完整的预测管道。
clf = Pipeline(
steps=[("preprocessor", preprocessor), ("classifier", LogisticRegression())]
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
clf.fit(X_train, y_train)
print("model score: %.3f" % clf.score(X_test, y_test))
model score: 0.798
Pipeline的HTML表示(显示图表)
当在jupyter notebook中打印出Pipeline
时,会显示估计器的HTML表示
clf
通过选择列数据类型使用ColumnTransformer
在处理清理后的数据集时,可以使用列的数据类型来决定是将列视为数值特征还是类别特征,从而实现自动预处理。sklearn.compose.make_column_selector
提供了这种可能性。首先,让我们只选择一部分列来简化我们的示例。
subset_feature = ["embarked", "sex", "pclass", "age", "fare"]
X_train, X_test = X_train[subset_feature], X_test[subset_feature]
然后,我们检查每个列数据类型的相关信息。
X_train.info()
<class 'pandas.core.frame.DataFrame'>
Index: 1047 entries, 1118 to 684
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 embarked 1045 non-null category
1 sex 1047 non-null category
2 pclass 1047 non-null int64
3 age 841 non-null float64
4 fare 1046 non-null float64
dtypes: category(2), float64(2), int64(1)
memory usage: 35.0 KB
我们可以观察到,在使用fetch_openml
加载数据时,embarked
和sex
列被标记为category
列。因此,我们可以使用此信息将类别列分派到categorical_transformer
,并将其余列分派到numerical_transformer
。
注意
在实践中,您必须自己处理列数据类型。如果您希望某些列被视为category
,则必须将其转换为类别列。如果您使用的是pandas,可以参考其关于类别数据的文档。
from sklearn.compose import make_column_selector as selector
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, selector(dtype_exclude="category")),
("cat", categorical_transformer, selector(dtype_include="category")),
]
)
clf = Pipeline(
steps=[("preprocessor", preprocessor), ("classifier", LogisticRegression())]
)
clf.fit(X_train, y_train)
print("model score: %.3f" % clf.score(X_test, y_test))
clf
model score: 0.798
最终得分与上一个管道的得分并不完全相同,因为基于dtype的选择器将pclass
列视为数值特征,而不是之前那样的类别特征。
selector(dtype_exclude="category")(X_train)
['pclass', 'age', 'fare']
selector(dtype_include="category")(X_train)
['embarked', 'sex']
在网格搜索中使用预测管道
网格搜索也可以应用于ColumnTransformer
对象中定义的不同预处理步骤,以及Pipeline
中分类器的超参数。我们将使用RandomizedSearchCV
搜索数值预处理的填充策略和逻辑回归的正则化参数。此超参数搜索会随机选择由n_iter
配置的固定数量的参数设置。或者,可以使用GridSearchCV
,但会评估参数空间的笛卡尔积。
param_grid = {
"preprocessor__num__imputer__strategy": ["mean", "median"],
"preprocessor__cat__selector__percentile": [10, 30, 50, 70],
"classifier__C": [0.1, 1.0, 10, 100],
}
search_cv = RandomizedSearchCV(clf, param_grid, n_iter=10, random_state=0)
search_cv
调用“拟合”会触发针对最佳超参数组合的交叉验证搜索
search_cv.fit(X_train, y_train)
print("Best params:")
print(search_cv.best_params_)
Best params:
{'preprocessor__num__imputer__strategy': 'mean', 'preprocessor__cat__selector__percentile': 30, 'classifier__C': 100}
这些参数获得的内部交叉验证分数为:
print(f"Internal CV score: {search_cv.best_score_:.3f}")
Internal CV score: 0.786
我们还可以将顶级网格搜索结果内省为pandas数据框
import pandas as pd
cv_results = pd.DataFrame(search_cv.cv_results_)
cv_results = cv_results.sort_values("mean_test_score", ascending=False)
cv_results[
[
"mean_test_score",
"std_test_score",
"param_preprocessor__num__imputer__strategy",
"param_preprocessor__cat__selector__percentile",
"param_classifier__C",
]
].head(5)
已使用最佳超参数在完整训练集上重新拟合最终模型。我们可以使用未用于超参数调整的保留测试数据来评估最终模型。
print(
"accuracy of the best model from randomized search: "
f"{search_cv.score(X_test, y_test):.3f}"
)
accuracy of the best model from randomized search: 0.798
脚本总运行时间:(0 分钟 1.415 秒)
相关示例