Sub topic 8
Inspecting fitted steps and feature names
A pipeline hides its steps inside one object. This chapter shows how to look inside a fitted pipeline to check what each step learned and which column names reach the model. It assumes you can build a Pipeline and a ColumnTransformer, and that you know fitted attributes in scikit-learn end with an underscore, such as coef_.
Reaching a step
A Pipeline stores its steps as a list of (name, estimator) pairs. You can reach a step in three ways:
model.named_steps["clf"]looks up a step by name.model["clf"]does the same through indexing.model[-1]ormodel[0]picks a step by position.
A slice such as model[:-1] returns a new Pipeline with the chosen steps. It does not copy the fitted steps. The new pipeline shares the same objects, so nothing is refit. Slicing off the final estimator gives you a pure preprocessor, which you can use to transform data and read output names.
Reading feature names
A ColumnTransformer can turn three input columns into four output columns, because one-hot encoding expands city. By default, each output name gets the transformer name as a prefix. The example below fits a pipeline, then pairs each name with its coefficient.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
df = pd.DataFrame({
"age": [25, 32, None, 47, 51, 38],
"income": [40000, 52000, 61000, None, 88000, 57000],
"city": ["Oslo", "Bergen", None, "Oslo", "Bergen", "Oslo"],
})
y = [0, 0, 1, 1, 1, 0]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
]).fit(df, y)
# 1. Output names of every step except the final estimator.
names = model[:-1].get_feature_names_out()
print(names)
# 2. Pair each name with the coefficient the classifier learned for it.
coefs = model.named_steps["clf"].coef_[0]
for name, value in zip(names, coefs):
print(f"{name:20s} {value:+.3f}")
# 3. Reach into nested steps to see what a scaler learned.
scaler = model.named_steps["prep"].named_transformers_["num"].named_steps["scale"]
print(scaler.mean_)The first print shows ['num__age' 'num__income' 'cat__city_Bergen' 'cat__city_Oslo']. The loop works because the classifier's coefficients line up with the columns that the preprocessor produced, in the same order.
Reading the fitted pieces
Step 3 uses named_transformers_. A ColumnTransformer keeps two versions of its transformers:
| Attribute | Contents | Available |
|---|---|---|
| `transformers` | The unfitted specification you passed in | Always |
| `transformers_` | The fitted copies, plus a `remainder` entry | After `fit` |
| `named_transformers_` | The fitted copies, looked up by name | After `fit` |
The fitted copies are clones. Calling fit on the pipeline does not fit the objects in your original transformers list. If you hold a reference to your own StandardScaler() and read mean_ from it, you will get an AttributeError. Always read the fitted copy through the pipeline.
Common errors
- Reading attributes before fitting.
named_transformers_andcoef_exist only afterfit. ANotFittedErrororAttributeErrorhere means the pipeline has not been fitted. - Inspecting a cross-validation result.
cross_val_scorefits clones inside each fold and discards them. Yourpipeis still unfitted afterward. Callpipe.fit(X_train, y_train)before inspecting it. - Inspecting a search result. After
GridSearchCVwith the defaultrefit=True, the fitted pipeline issearch.best_estimator_. Slice and inspect that object, notsearch. - Assuming the input order. Output columns follow the order of the transformers in the
ColumnTransformer, not the column order in your DataFrame. Always useget_feature_names_outinstead of guessing. - Dropped columns. Columns that no transformer lists are dropped by default (
remainder="drop"). If a column seems to be missing from the names, check this setting.
Exercise
You fitted search = GridSearchCV(pipe, grid, cv=5) on a pipeline with steps named prep and clf. Write the expression that gives the feature names after prep, and explain why search.named_steps does not work.
Show answer
Use search.best_estimator_[:-1].get_feature_names_out(). GridSearchCV is not a pipeline, so it has no named_steps. With refit=True, the pipeline refit on the full training data is stored in best_estimator_, and slicing it with [:-1] removes the final classifier so only the preprocessing names remain.