Sub topic 11
Feature names and set_output
This chapter assumes you can write a custom transformer with BaseEstimator and TransformerMixin, and that you have used a Pipeline and ColumnTransformer. It shows how to make your transformer report column names and return a pandas DataFrame on request.
Why feature names matter
A plain transformer returns a NumPy array, so column names are lost. After a few pipeline steps you cannot tell which column is which. That makes coefficients, feature importances and debugging output hard to read.
Scikit-learn 1.2 and later solves this with two pieces:
get_feature_names_out, a method that returns the output column names.set_output, a method that makestransformreturn a DataFrame instead of an array.
Implementing get_feature_names_out
TransformerMixin wraps transform and fit_transform automatically when your class defines get_feature_names_out. You get set_output with no extra code.
The transformer below subtracts each column's mean. It records input column names in fit and returns them in get_feature_names_out.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, check_is_fitted
class MeanCenterer(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
if hasattr(X, "columns"):
self.feature_names_in_ = np.asarray(X.columns, dtype=object)
X = check_array(X)
self.mean_ = X.mean(axis=0)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return X - self.mean_
def get_feature_names_out(self, input_features=None):
check_is_fitted(self)
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": [1.0, 2.0, 3.0], "b": [10.0, 20.0, 60.0]})
centerer = MeanCenterer().set_output(transform="pandas")
out = centerer.fit_transform(df)
print(out)
print(centerer.get_feature_names_out())The output is a DataFrame with columns a and b and the original index. Column a becomes -1, 0, 1 and column b becomes -20, -10, 30.
The name feature_names_in_ is a convention. Scikit-learn's own estimators set it when they are fitted on a DataFrame, and tools such as Pipeline read it.
Rules for the names
- Return a NumPy array of strings (object dtype is fine).
- Return one name per output column, in output order.
- If the transformer keeps the number and meaning of columns, return the input names.
- If it creates new columns, build names from the inputs, such as
f"{name}_squared". - Accept an
input_featuresargument. Pipelines pass the names from the previous step through it.
Names through a pipeline
Calling set_output on a Pipeline or ColumnTransformer applies the setting to every step. Names then flow from step to step.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
("center", MeanCenterer()),
("scale", StandardScaler()),
]).set_output(transform="pandas")
result = pipe.fit_transform(df)
print(result.columns.tolist())
print(pipe.get_feature_names_out())Both lines show a and b. If one step lacks get_feature_names_out, the pipeline raises an AttributeError when you ask for names.
Stateless steps
For FunctionTransformer, pass feature_names_out="one-to-one" when the function keeps columns unchanged. For a function that changes the columns, pass a callable with the signature (transformer, input_features) that returns the new names. Without this argument, FunctionTransformer cannot report names.
Common problems
| Symptom | Likely cause |
|---|---|
| `set_output` has no effect | `get_feature_names_out` is not defined |
| Column count mismatch error | The names array length differs from the output width |
| Names become `x0, x1, ...` | The transformer was fitted on an array, not a DataFrame |
| Index is lost | `transform` returned a DataFrame and dropped the original index |
Exercise
A custom transformer adds one new column, total, to the end of its input columns. What should get_feature_names_out return for inputs ["a", "b"]?
Show answer
The input names followed by the new name: ["a", "b", "total"], as a NumPy array of strings. The array must have the same length and order as the columns that transform returns.