Примечание
Перейти к концу, чтобы загрузить полный код примера. или запустить этот пример в вашем браузере через JupyterLite или Binder
Отображение конвейеров
По умолчанию для отображения конвейера в Jupyter Notebook используется 'diagram', где set_config(display='diagram'). Чтобы отключить HTML-представление, используйте set_config(display='text').
Чтобы увидеть более подробные шаги в визуализации конвейера, щелкните шаги в конвейере.
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause
Отображение конвейера с шагом предобработки и классификатором
В этом разделе создается Pipeline с шагом предобработки, StandardScaler, и классификатором, LogisticRegression, и отображается его визуальное представление.
from sklearn import set_config
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
steps = [
("preprocessing", StandardScaler()),
("classifier", LogisticRegression()),
]
pipe = Pipeline(steps)
Для визуализации диаграммы по умолчанию используется display='diagram'.
set_config(display="diagram") pipe # click on the diagram below to see the details of each step
Чтобы просмотреть текстовый конвейер, измените на display='text'.
set_config(display="text") pipe
Pipeline(steps=[('preprocessing', StandardScaler()),
('classifier', LogisticRegression())])
Вернуть отображение по умолчанию
set_config(display="diagram")
Отображение конвейера со множеством шагов предобработки и классификатором
В этом разделе создается Pipeline со множеством шагов предобработки, PolynomialFeatures и StandardScaler, и шагом классификатора, LogisticRegression, и отображается его визуальное представление.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
steps = [
("standard_scaler", StandardScaler()),
("polynomial", PolynomialFeatures(degree=3)),
("classifier", LogisticRegression(C=2.0)),
]
pipe = Pipeline(steps)
pipe # click on the diagram below to see the details of each step
Отображение конвейера, снижения размерности и классификатора
В этом разделе создается Pipeline с шагом снижения размерности, PCA, классификатором, SVC, и отображается его визуальное представление.
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
steps = [("reduce_dim", PCA(n_components=4)), ("classifier", SVC(kernel="linear"))]
pipe = Pipeline(steps)
pipe # click on the diagram below to see the details of each step
Отображение сложной цепочки конвейера с использованием Column Transformer
В этом разделе создается сложный Pipeline с ColumnTransformer и классификатором LogisticRegression, и отображается его визуальное представление.
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
numeric_preprocessor = Pipeline(
steps=[
("imputation_mean", SimpleImputer(missing_values=np.nan, strategy="mean")),
("scaler", StandardScaler()),
]
)
categorical_preprocessor = Pipeline(
steps=[
(
"imputation_constant",
SimpleImputer(fill_value="missing", strategy="constant"),
),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]
)
preprocessor = ColumnTransformer(
[
("categorical", categorical_preprocessor, ["state", "gender"]),
("numerical", numeric_preprocessor, ["age", "weight"]),
]
)
pipe = make_pipeline(preprocessor, LogisticRegression(max_iter=500))
pipe # click on the diagram below to see the details of each step
Отображение сетки поиска по конвейеру с классификатором
В этом разделе создается GridSearchCV над Pipeline с RandomForestClassifier и отображается его визуальное представление.
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
numeric_preprocessor = Pipeline(
steps=[
("imputation_mean", SimpleImputer(missing_values=np.nan, strategy="mean")),
("scaler", StandardScaler()),
]
)
categorical_preprocessor = Pipeline(
steps=[
(
"imputation_constant",
SimpleImputer(fill_value="missing", strategy="constant"),
),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]
)
preprocessor = ColumnTransformer(
[
("categorical", categorical_preprocessor, ["state", "gender"]),
("numerical", numeric_preprocessor, ["age", "weight"]),
]
)
pipe = Pipeline(
steps=[("preprocessor", preprocessor), ("classifier", RandomForestClassifier())]
)
param_grid = {
"classifier__n_estimators": [200, 500],
"classifier__max_features": ["auto", "sqrt", "log2"],
"classifier__max_depth": [4, 5, 6, 7, 8],
"classifier__criterion": ["gini", "entropy"],
}
grid_search = GridSearchCV(pipe, param_grid=param_grid, n_jobs=1)
grid_search # click on the diagram below to see the details of each step
© 2007–2025 The scikit-learn developers
Licensed under the 3-clause BSD License.
https://scikit-learn.org/1.6/auto_examples/miscellaneous/plot_pipeline_display.html