Sub topic 8
Inspecting fitted steps and feature names
A fitted pipeline is easy to use and hard to see into. You call predict and get numbers, but you can't tell which columns the model received, how a scaler shifted them, or which coefficient belongs to which feature. This chapter covers how to look inside a fitted pipeline and how to trace the output columns back to the input.
Prerequisites
This chapter assumes you can:
- Build a
Pipelineand aColumnTransformer, as in the earlier chapters. - Fit a pipeline on a pandas DataFrame.
- Read a logistic regression coefficient.
The examples need scikit-learn 1.2 or newer, because set_output appeared in that release.
Where fitted state lives
Every estimator in scikit-learn follows one convention. Constructor arguments are the settings you chose, such as C=1.0. Values learned during fit are attributes ending in an underscore, such as mean_, coef_ or categories_. A pipeline stores no learned values of its own. It holds a list of fitted steps, and each step holds its own state.
Inspecting a pipeline therefore means two things. First, reach the right step. Second, read the trailing-underscore attributes on it.
The model below nests four levels: pipeline, column transformer, inner pipeline, and transformer.
Reaching steps
A Pipeline gives you four ways to reach its steps.
| Expression | Returns | Notes |
|---|---|---|
| `pipe.steps` | List of `(name, estimator)` tuples | Ordered, so you can loop over it |
| `pipe.named_steps["clf"]` | The step called `clf` | Also works as `pipe.named_steps.clf` |
| `pipe["clf"]` or `pipe[1]` | The step by name or position | Integer indexing returns a step |
| `pipe[:-1]` | A new `Pipeline` of the selected steps | Slicing returns a pipeline, not a list |
Steps made by make_pipeline are named after their lowercased class. StandardScaler() becomes standardscaler, and two steps of the same class get suffixes -1 and -2. When you need to address steps reliably, in a parameter grid for example, name them yourself with Pipeline.
The slice pipe[:-1] is the most useful form. It drops the final estimator, so what remains is the preprocessing alone. You can call transform on it and see what the model actually receives.
A model to inspect
The model below uses the mixed-type data from the column transformer chapter. Missing city values are written as np.nan.
import numpy as np
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, np.nan, 47, 51, 38],
"income": [40000, 52000, 61000, np.nan, 88000, 57000],
"city": ["Oslo", "Bergen", np.nan, "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)
print([name for name, _ in model.steps])
# Learned state inside the nested numeric branch.
scaler = model.named_steps["prep"].named_transformers_["num"].named_steps["scale"]
print(scaler.mean_)
print(scaler.scale_)
# The imputer's fill values: medians for age and income.
imputer = model.named_steps["prep"].named_transformers_["num"].named_steps["impute"]
print(imputer.statistics_)
# Which categories the encoder learned.
encoder = model.named_steps["prep"].named_transformers_["cat"].named_steps["onehot"]
print(encoder.categories_)The scaler.mean_ array holds the mean of each numeric column after imputation. That is the number applied to every future row, so it is worth checking when predictions look odd.
Feature names after preprocessing
The classifier sees a plain matrix with four columns. To read its coefficients you need a name for each column. Transformers that know their output columns provide get_feature_names_out, and Pipeline and ColumnTransformer chain these calls for you.
names = model[:-1].get_feature_names_out()
print(names)
coefs = model.named_steps["clf"].coef_[0]
for name, coef in zip(names, coefs):
print(f"{name:20s} {coef:+.3f}")The names look like num__age, num__income, cat__city_Bergen and cat__city_Oslo. The prefix is the name of the ColumnTransformer entry that produced the column, followed by two underscores. The prefix keeps names unique when two branches emit columns with the same name. The city_ part comes from the one-hot encoder, which combines the input column name and the category.
model[:-1].get_feature_names_out() works because every step in the slice can report its output names. The call fails with an AttributeError when a step can't, and the common cause is a custom transformer. A later section fixes that.
Because the model is fitted on a DataFrame, model.feature_names_in_ and model.n_features_in_ also work. They record the input columns the pipeline expects, which is useful when you debug a schema mismatch at prediction time.
Cleaner names and DataFrame output
The prefixes are noisy. Pass verbose_feature_names_out=False to the ColumnTransformer to drop them. Scikit-learn raises an error if that would create duplicate names.
Often you want a DataFrame from transform instead of an array. set_output(transform="pandas") does that, and the column names then come along automatically.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
df = pd.DataFrame({
"age": [25, 32, 41, 47],
"city": ["Oslo", "Bergen", "Oslo", "Bergen"],
"id": [1, 2, 3, 4],
})
ct = ColumnTransformer(
[
("num", StandardScaler(), ["age"]),
("cat", OneHotEncoder(sparse_output=False), ["city"]),
],
remainder="passthrough",
verbose_feature_names_out=False,
)
ct.set_output(transform="pandas")
out = ct.fit_transform(df)
print(out.columns.tolist())
print(ct.transformers_)The output columns are age, city_Bergen, city_Oslo and id. Three details matter here:
OneHotEncoderreturns a sparse matrix by default, and pandas output can't hold one. That is why the example setssparse_output=False.remainder="passthrough"keeps the columns you didn't mention. The default,"drop", discards them without a warning.transformers_is the fitted list. Besides your entries it contains aremainderentry that shows which columns were left over, so a missing column shows up there.
Fitted attributes of the ColumnTransformer
The ColumnTransformer has a few attributes of its own that answer common questions:
named_transformers_is a dictionary-like object of the fitted transformers by name. Use it instead of thetransformersargument, which holds the unfitted originals.transformers_is the list of(name, fitted_transformer, columns)tuples, including the remainder.output_indices_maps each transformer name to the slice of output columns it produced. It lets you find the columns that came from one branch.get_feature_names_out()returns all output names in order.
A frequent error is reading preprocess.transformers[0] after fitting. That is the original object, which was cloned before fitting, so it has no mean_. Always go through named_transformers_ or transformers_ for fitted state.
Common errors
NotFittedError. You read a trailing-underscore attribute or calledtransformbeforefit. This also happens withGridSearchCV, where your original pipeline stays unfitted. Usesearch.best_estimator_to get the fitted winner.KeyErroronnamed_steps. The step name differs from what you expect, usually becausemake_pipelinegenerated it. Printpipe.stepsto see the real names.AttributeError: ... does not provide get_feature_names_out. One step can't describe its output columns. The usual causes are a custom transformer, a bareFunctionTransformerwithoutfeature_names_out, or a very old scikit-learn version.- Names and coefficients differ in length. You paired the names with coefficients from a different step, or you used the full pipeline's names when feature selection ran in between. Slice at the same point on both sides, and use
get_support()on a selector step to see what it kept. - A one-hot column is missing. The encoder only knows categories seen during
fit. Checkencoder.categories_, and remember thathandle_unknown="ignore"turns unseen values into an all-zero row rather than an error.
Giving a custom transformer feature names
The Log1pTransformer from the custom transformer chapter works in a pipeline but can't report its output names. The version below records the input names during fit and returns them from get_feature_names_out. The transform doesn't change the number of columns, so the output names equal the input names.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
class Log1pTransformer(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
self.n_features_in_ = X.shape[1]
if hasattr(X, "columns"):
self.feature_names_in_ = np.asarray(X.columns, dtype=object)
return self
def transform(self, X):
return np.log1p(X)
def get_feature_names_out(self, input_features=None):
if input_features is not None:
return np.asarray(input_features, dtype=object)
if hasattr(self, "feature_names_in_"):
return self.feature_names_in_
return np.array([f"x{i}" for i in range(self.n_features_in_)], dtype=object)
df = pd.DataFrame({"a": [0.0, 1.0, 9.0], "b": [1.0, 99.0, 3.0]})
pipe = Pipeline([("log", Log1pTransformer()), ("scale", StandardScaler())]).fit(df)
print(pipe.get_feature_names_out())The pipeline passes the names forward from step to step. If your transformer adds or removes columns, build the new names from input_features instead of returning them unchanged.
Summary
- Learned values sit on the individual steps as trailing-underscore attributes. A pipeline only holds the steps.
- Use
named_steps, indexing andnamed_transformers_to reach a step, andpipe[:-1]to get the preprocessing alone. get_feature_names_outgives the names of the columns the final estimator sees. Pair them withcoef_orfeature_importances_to read a model.set_output(transform="pandas")returns DataFrames, andverbose_feature_names_out=Falseshortens the names.- Slices share step objects with the original pipeline, so clone before you change anything.
Exercise
You fitted the chapter's model and want the standard deviation that the StandardScaler in the numeric branch uses for the income column. Write the expression, and say which column index holds income. Then explain why model.named_steps["prep"].transformers[0][1].scale_ fails.
Show answer
Use model.named_steps["prep"].named_transformers_["num"].named_steps["scale"].scale_[1]. The numeric branch was given ["age", "income"], so income is index 1 in the array. The expression with transformers[0][1] fails because transformers holds the unfitted originals. The ColumnTransformer clones them before fitting, so the original scaler has no scale_ attribute. Fitted copies are in transformers_ and named_transformers_.
Exercise
A teammate writes names = model.get_feature_names_out() and then dict(zip(names, model.named_steps["clf"].coef_[0])). The call to get_feature_names_out raises an error. What is the likely cause, and what is the fix?
Show answer
The final step is a classifier, which has no get_feature_names_out, so the pipeline can't report names for its last step. The fix is to ask for the names of the preprocessing only, with model[:-1].get_feature_names_out(). That slice ends where the classifier's input begins, so its names line up with coef_[0].