Sub topic 11
Feature names and set_output
This chapter assumes you can write a transformer with BaseEstimator and TransformerMixin, and that you know how Pipeline and ColumnTransformer chain steps. It covers how a custom transformer reports the names of its output columns, and how users can get a pandas DataFrame back from transform instead of a NumPy array.
Why feature names matter
Most scikit-learn transformers return NumPy arrays, which have no column labels. After a few pipeline steps, you no longer know what column 7 means. Two features fix this:
feature_names_in_is a fitted attribute that records the column names of the DataFrame you passed tofit.get_feature_names_out()is a method that returns the names of the columnstransformproduces.
set_output(transform="pandas") builds on both. It makes transform return a DataFrame whose columns come from get_feature_names_out() and whose index comes from the input.
Recording input names
The check_array function used in earlier chapters does not record column names. For that you need validate_data, which also sets n_features_in_. It exists in sklearn.utils.validation from scikit-learn 1.6. On older versions, call self._validate_data(X, reset=True) instead.
Use reset=True in fit, which stores n_features_in_ and, when X is a DataFrame with all-string column names, feature_names_in_. Use reset=False in transform, which checks the new data against what fit saw. A different column count or different names raises a ValueError.
One-to-one transformers: OneToOneFeatureMixin
If your transformer produces exactly one output column per input column, in the same order, you don't have to write get_feature_names_out. Add OneToOneFeatureMixin, which returns the input names unchanged.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.utils.validation import check_is_fitted, validate_data
class QuantileClipper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
def __init__(self, lower=0.01, upper=0.99):
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
X = validate_data(self, X, reset=True)
self.lower_ = np.quantile(X, self.lower, axis=0)
self.upper_ = np.quantile(X, self.upper, axis=0)
return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, reset=False)
return np.clip(X, self.lower_, self.upper_)
df = pd.DataFrame(
{"age": [21, 35, 44, 29, 90], "income": [30, 52, 61, 45, 400]},
index=["a", "b", "c", "d", "e"],
)
clipper = QuantileClipper(lower=0.1, upper=0.9).set_output(transform="pandas")
out = clipper.fit_transform(df)
print(type(out).__name__)
print(list(out.columns))
print(list(out.index))
print(clipper.feature_names_in_)
print(clipper.get_feature_names_out())This prints DataFrame, then ['age', 'income'], then ['a', 'b', 'c', 'd', 'e'], followed by the two name arrays. The index survives because the wrapper copies it from the input DataFrame.
Put mixins before BaseEstimator in the base class list. BaseEstimator should come last so the mixins can override its defaults.
How set_output works internally
You never wrote a set_output method. TransformerMixin provides it, and it works through a hook that runs when your class is defined:
- When Python creates a subclass of
TransformerMixin, the mixin's__init_subclass__checks whether the class definesget_feature_names_out.OneToOneFeatureMixincounts, because it defines the method. - If it does,
transformandfit_transformare wrapped. - At call time, the wrapper reads the output configuration. If it is
"pandas", the wrapper converts your returned array to a DataFrame, usingget_feature_names_out()for the columns and the input's index for the rows. - If the configuration is
"default", the wrapper returns your result unchanged.
The consequence is that set_output only exists on classes that define get_feature_names_out. Without that method, calling set_output(transform="pandas") raises an AttributeError.
Transformers that change the columns
When the output columns differ from the input columns, write get_feature_names_out yourself. The transformer below appends one column holding the ratio of two input columns.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.utils.validation import check_is_fitted, validate_data
class AddRatio(TransformerMixin, BaseEstimator):
def __init__(self, numerator=0, denominator=1):
self.numerator = numerator
self.denominator = denominator
def fit(self, X, y=None):
validate_data(self, X, reset=True)
return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, reset=False)
ratio = X[:, self.numerator] / X[:, self.denominator]
return np.column_stack([X, ratio])
def get_feature_names_out(self, input_features=None):
check_is_fitted(self)
if input_features is None:
input_features = getattr(
self,
"feature_names_in_",
[f"x{i}" for i in range(self.n_features_in_)],
)
return np.asarray([*input_features, "ratio"], dtype=object)
df = pd.DataFrame({"width": [2.0, 4.0, 6.0, 8.0], "height": [1.0, 2.0, 5.0, 4.0]})
pipe = Pipeline([("ratio", AddRatio()), ("scale", StandardScaler())])
pipe.set_output(transform="pandas")
out = pipe.fit_transform(df)
print(list(out.columns))
print(pipe.get_feature_names_out())Both lines print width, height and ratio. Pipeline.set_output applies the setting to every step, and Pipeline.get_feature_names_out asks each step in turn, passing the previous step's output names as input_features.
Follow these rules when you write the method:
- Accept
input_features=Noneas the only argument. Pipelines pass names positionally. - Return a one-dimensional NumPy array of strings (object dtype is fine).
- Return exactly as many names as
transformreturns columns, in the same order. A mismatch produces a confusing shape error inside the wrapper. - Call
check_is_fittedfirst, because the names usually depend on fitted state. - Make names unique. Duplicate names break
ColumnTransformer.
If the number or names of output columns depend on a fitted attribute, such as the categories seen in fit, compute them from that attribute (for example self.classes_), not from the data.
FunctionTransformer and feature names
FunctionTransformer takes a feature_names_out argument. Without it, the transformer has no get_feature_names_out and cannot produce pandas output.
| Value | Meaning |
|---|---|
| `None` (default) | No `get_feature_names_out` is available |
| `"one-to-one"` | Output names equal input names |
| A callable | Called as `func(transformer, input_features)` and must return the names |
import numpy as np
import pandas as pd
from sklearn.preprocessing import FunctionTransformer
def sum_and_diff(X):
X = np.asarray(X)
return np.column_stack([X[:, 0] + X[:, 1], X[:, 0] - X[:, 1]])
def names_out(transformer, input_features):
return np.asarray(["sum", "diff"], dtype=object)
ft = FunctionTransformer(sum_and_diff, feature_names_out=names_out)
ft.set_output(transform="pandas")
out = ft.fit_transform(pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}))
print(list(out.columns))This prints ['sum', 'diff'].
ColumnTransformer and name prefixes
ColumnTransformer concatenates the output names of its transformers. By default it prefixes each name with the transformer's label, as in clip__age. This keeps names unique when two transformers touch similarly named columns.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame(
{"age": [21, 35, 44, 29, 90], "income": [30, 52, 61, 45, 400], "score": [1, 2, 3, 4, 5]}
)
ct = ColumnTransformer(
[
("clip", QuantileClipper(lower=0.1, upper=0.9), ["age", "income"]),
("scale", StandardScaler(), ["score"]),
],
verbose_feature_names_out=False,
)
ct.set_output(transform="pandas")
print(list(ct.fit_transform(df).columns))This example reuses QuantileClipper from earlier in the chapter. With verbose_feature_names_out=False the prefixes are dropped, giving ['age', 'income', 'score']. That option raises an error if two transformers would produce the same name. Leave it at the default True if you can't guarantee unique names.
Setting the output format
| Method | Scope |
|---|---|
| `est.set_output(transform="pandas")` | One estimator, or all steps of a pipeline or column transformer |
| `sklearn.set_config(transform_output="pandas")` | Every estimator in the process |
| `sklearn.config_context(transform_output="pandas")` | Every estimator inside a `with` block |
| `est.set_output(transform="default")` | Return to NumPy output |
An estimator-level setting takes priority over the global one. Recent versions also accept "polars" for DataFrame output.
Common pitfalls
- Names only exist for string columns. If a DataFrame has integer column labels,
feature_names_in_is not set, and your fallback names (x0,x1, and so on) are used. Mixed string and non-string labels raise an error at validation time. - Different names at transform time.
validate_data(..., reset=False)raises aValueErrorif the columns differ from those seen duringfit. This is useful, so keep it. - Sparse output. Pandas output does not support sparse matrices. A transformer that returns sparse data fails with pandas output configured.
- Wrong length.
get_feature_names_outmust match the number of columnstransformreturns. Test it on a fitted instance withlen(est.get_feature_names_out()) == est.transform(X).shape[1]. - Opting out. To disable auto-wrapping for a class, pass
auto_wrap_output_keys=Nonein the class statement:class MyTransformer(TransformerMixin, BaseEstimator, auto_wrap_output_keys=None). - Hand-written wrapping. Don't build a DataFrame inside
transformyourself. Return the array and let the wrapper decide, so users keep control throughset_output.
Exercise
You wrote a transformer that defines fit and transform but no getfeaturenamesout. A user calls `MyTransformer().setoutput(transform="pandas")`. What happens, and what is the smallest change that fixes it?
Show answer
It raises an AttributeError, because setoutput is only available on transformer classes that define getfeaturenamesout when the class is created. The smallest fix is to add the method, or to inherit OneToOneFeatureMixin if the output has one column per input column, in the same order.
Exercise
A ColumnTransformer has a QuantileClipper step labelled "clip" on the columns ["age", "income"] and a StandardScaler step labelled "scale" on ["score"]. With default settings, which output column names does getfeaturenames_out return?
Show answer
With verbosefeaturenamesout left at True, each name gets the step label as a prefix: clipage, clipincome and scale_score.
Exercise
Your transformer returns np.column_stack([X, X ** 2]) for an input with n columns. Write the body of getfeaturenames_out so that pandas output works, assuming input names are in a list called names.
Show answer
Return np.asarray([*names, *[f"{n}^2" for n in names]], dtype=object). This gives 2n unique names in the same order as the columns produced by column_stack, with the originals first and the squares after.