Sub topic 7
When FunctionTransformer Is Enough
This chapter assumes you can write a scikit-learn Pipeline, you know what fit and transform do, and you have read the chapters on BaseEstimator and the constructor rules. Here you will learn when a plain function can replace a custom transformer class. You will also learn how to wrap it correctly and where the shortcut stops working.
What FunctionTransformer does
FunctionTransformer turns a Python function into a pipeline step. Its fit method learns nothing. Its transform method calls your function on the input. That is the whole contract.
A custom class like QuantileClipper is needed when fit must learn something from the training data, such as quantiles, means, or vocabularies. If the same function should run in the same way on training and test data, a class adds code without adding behavior.
These are typical stateless steps:
np.log1p,np.sqrt, ornp.absapplied to every column.- Clipping to fixed, known limits.
- Adding a column computed from other columns of the same row, such as a ratio.
- Selecting or reordering columns by position.
The parameters you will use most are listed here.
| Parameter | Default | Purpose |
|---|---|---|
| `func` | `None` | The function applied in `transform`. `None` means identity. |
| `inverse_func` | `None` | The function applied in `inverse_transform`. |
| `validate` | `False` | If `True`, converts input to a 2D numeric array first. |
| `check_inverse` | `True` | At `fit`, checks that `inverse_func(func(X))` is close to `X`, and warns if not. |
| `feature_names_out` | `None` | Enables `get_feature_names_out`. Use `"one-to-one"` or a callable. |
| `kw_args` | `None` | A dict of extra keyword arguments passed to `func`. |
A first example
The step below applies log1p and can be undone with expm1. Setting feature_names_out="one-to-one" says that output columns keep the input names.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
X = np.array([[0.0, 1.0], [3.0, 10.0], [15.0, 100.0]])
log_step = FunctionTransformer(
np.log1p,
inverse_func=np.expm1,
feature_names_out="one-to-one",
)
Xt = log_step.fit_transform(X)
print(np.round(Xt, 3))
print(np.allclose(log_step.inverse_transform(Xt), X))
print(log_step.get_feature_names_out(["a", "b"]))The first print shows rows such as 0.0, 0.693 and 2.773, 4.615. The second prints True. The third prints the names a and b.
You can use the same object inside a pipeline. The next example fits a ridge regression on skewed features and scores it with cross-validation.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
rng = np.random.default_rng(0)
X = rng.lognormal(mean=1.0, sigma=1.0, size=(200, 3))
y = np.log1p(X).sum(axis=1) + rng.normal(scale=0.1, size=200)
log_step = FunctionTransformer(
np.log1p, inverse_func=np.expm1, feature_names_out="one-to-one"
)
model = make_pipeline(log_step, StandardScaler(), Ridge())
print(cross_val_score(model, X, y, cv=5).mean())The mean R² score is close to 1.0, because the target is linear in the logged features. Cross-validation clones the pipeline for each fold. FunctionTransformer clones without trouble because it follows the constructor rules: it stores its arguments unchanged.
Passing arguments with kw_args
A function often needs settings. Do not hard-code them with a lambda. Write a named function and pass the settings through kw_args.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
def clip_to(X, low, high):
return np.clip(X, low, high)
clip_step = FunctionTransformer(
clip_to,
kw_args={"low": 0.0, "high": 10.0},
feature_names_out="one-to-one",
)
print(clip_step.fit_transform(np.array([[-5.0, 3.0], [12.0, 7.0]])))The output is [[0. 3.] [10. 7.]]. The dict is stored unchanged, so get_params and set_params can see it.
kw_args is one parameter, not one parameter per key. In a grid search you replace the whole dict:
param_grid = {
"clip__kw_args": [
{"low": 0.0, "high": 5.0},
{"low": 0.0, "high": 10.0},
]
}The name clip__low does not exist for a FunctionTransformer. If you want that syntax, write a class, as in the QuantileClipper example.
Feature names
By default feature_names_out is None. Then get_feature_names_out raises an error, and so does anything that asks for names later, such as pipeline[:-1].get_feature_names_out(). Choose one of two options:
"one-to-one"when the output has the same columns as the input.- A callable
f(transformer, input_features)that returns the output names, when the function changes the number of columns.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
def add_ratio(X):
X = np.asarray(X, dtype=float)
return np.column_stack([X, X[:, 0] / X[:, 1]])
def ratio_names(transformer, input_features):
return np.append(np.asarray(input_features, dtype=object), "ratio")
ratio_step = FunctionTransformer(add_ratio, feature_names_out=ratio_names)
ratio_step.fit(np.array([[1.0, 2.0], [3.0, 4.0]]))
print(ratio_step.get_feature_names_out(["width", "height"]))The result lists width, height, and ratio. With set_output(transform="pandas") the output DataFrame uses these names. Without feature_names_out, the pandas option cannot name the columns.
The statelessness rule
FunctionTransformer has no memory. Each call to transform sees only the data you give it. Any statistic you compute inside the function is computed again on every batch. This is the most common misuse of the class.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
center_batch = FunctionTransformer(lambda X: X - X.mean(axis=0))
train = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
test = np.array([[7.0, 8.0]])
print(center_batch.fit_transform(train))
print(center_batch.transform(test))The test row comes out as [[0. 0.]], because it was centered on its own mean. It should have been centered on the training mean. Predictions would then depend on which rows share a batch with the row you are scoring. In cross-validation, each test fold would also be centered on its own mean, which leaks information about the test fold into its features.
The rule is simple. If the function needs a number computed from training data, that number must be learned in fit and stored in an attribute that ends in an underscore. That requires a class. For centering, use StandardScaler(with_std=False).
Choosing between a function and a class
Gotchas
Lambdas and saving models
A lambda has no importable name, so pickle cannot save it. A pipeline holding a lambda step fails in pickle.dump or joblib.dump. Parallel backends that use cloudpickle may hide the problem during a grid search, and it appears later when you try to save the model. Define the function with def at module level. The function must also be importable in the process that loads the model.
check_inverse
When both func and inverse_func are given, fit checks on the training data that the round trip returns the input. If it does not, you get a UserWarning. A lossy pair such as np.abs and np.abs, or clipping and its identity inverse, triggers it. Pass check_inverse=False once you know the pair is only approximately invertible.
validate and DataFrames
With validate=False, the function receives exactly what the pipeline passes in. That may be a DataFrame, and a function written for arrays can then behave differently. With validate=True, the input is converted to a 2D numeric array. Missing values or strings then raise errors, and DataFrame column names are lost unless scikit-learn can keep them. Make the function work on one type, or convert at the top with np.asarray as add_ratio does.
Mutating input
func receives the caller's data. Writing X[:, 0] = ... changes the user's array in place. Return a new array, as np.clip and np.column_stack do.
Use in ColumnTransformer
A FunctionTransformer works as a step in a ColumnTransformer, and each branch sees only its own columns. Give the step feature_names_out so that the combined get_feature_names_out works.
Exercise
A colleague writes FunctionTransformer(lambda X: X / X.max(axis=0)) to scale features to at most 1. Training accuracy looks fine, but predictions for single rows are wrong. Why, and what is the fix?
Show answer
The maximum is computed on whatever batch is passed to transform. A single row is divided by itself, so every value becomes 1, and each cross-validation test fold is scaled by its own maximum. The step needs to learn the maximum from the training data in fit and store it in an attribute ending in an underscore, such as max_. That makes it a custom transformer class, or you can use MaxAbsScaler, which already does this.
Exercise
Write a FunctionTransformer that clips each value to the range 0 to 100 using a named function and kwargs. Then write a paramgrid for a Pipeline step named "clip" that tries upper limits of 50 and 100.
Show answer
def clipto(X, low, high): return np.clip(X, low, high) clip = FunctionTransformer(clipto, kwargs={"low": 0, "high": 100}, featurenamesout="one-to-one") paramgrid = {"clip_kwargs": [{"low": 0, "high": 50}, {"low": 0, "high": 100}]} kwargs is a single parameter, so each grid value is a complete dict. A name like clip_high does not exist.