Sub topic 7
When FunctionTransformer is enough
This chapter assumes you know how to use a Pipeline, and that you have seen the fit and transform contract. It also assumes you can write a small Python function. You do not need to have written a custom class yet.
The case for skipping the class
A custom transformer needs a constructor, fit, transform, and validation. If a step learns nothing from the data, most of that code does nothing. A log transform is an example. It applies the same function to every column and keeps no state between calls.
FunctionTransformer wraps a plain function as a pipeline step. Its fit learns nothing, and its transform calls your function.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
log_step = FunctionTransformer(
np.log1p,
inverse_func=np.expm1,
feature_names_out="one-to-one",
)Here is what each argument does:
funcis the first argument. It is the function applied intransform.inverse_funcis optional. It is used byinverse_transform.feature_names_out="one-to-one"says each output column keeps the name of its input column. Without it,get_feature_names_outis unavailable on this step.
Using it in a pipeline
The wrapper behaves like any other transformer.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
X = np.array([[1.0], [10.0], [100.0], [1000.0]])
y = np.array([0.7, 2.4, 4.6, 6.9])
model = make_pipeline(
FunctionTransformer(np.log1p, inverse_func=np.expm1),
LinearRegression(),
)
model.fit(X, y)
print(model.predict([[50.0]]))The linear model sees log1p(X), so it can fit a relationship that grows slowly with the raw value.
Passing extra arguments
If your function needs settings, use kw_args. The wrapper passes them as keyword arguments on every call.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
def clip_values(X, low, high):
return np.clip(X, low, high)
clipper = FunctionTransformer(clip_values, kw_args={"low": 0.0, "high": 10.0})
print(clipper.fit_transform(np.array([[-5.0], [3.0], [42.0]])))kw_args is a constructor parameter, so you can tune it. In a GridSearchCV over a pipeline whose step is named clip, the grid key is clip__kw_args, and each value is a full dictionary.
param_grid = {
"clip__kw_args": [
{"low": 0.0, "high": 10.0},
{"low": 0.0, "high": 5.0},
]
}Choosing between the two
The deciding question is whether transform needs anything learned from the training data.
| Situation | Use |
|---|---|
| Fixed math such as `log1p`, `sqrt`, or a unit conversion | `FunctionTransformer` |
| Row-wise feature creation, such as a ratio of two columns | `FunctionTransformer` |
| Clipping to bounds you choose in advance | `FunctionTransformer` with `kw_args` |
| Clipping to quantiles computed from training data | Custom class |
| Anything that stores a mean, vocabulary, or fitted model | Custom class |
The quantile clipper from the previous chapters needs lower_ and upper_ from fit. A function cannot hold those values between calls, so that step stays a class.
Common errors
Other problems to watch for:
- Lambdas and pickling. A
lambdaworks in a session, but it cannot be saved withpickle. Use a named function defined at module level if you plan to save the model. - Missing feature names. Leaving out
feature_names_outbreaksget_feature_names_outon the pipeline. Use"one-to-one"or a callable that returns the names. - Inverse mismatch.
check_inverse=Trueis the default. When you passinverse_func,fitchecks that the round trip returns the original values and warns if it does not. - Validation. By default
validate=False, so your function receives the input as given, including a DataFrame. Setvalidate=Trueif you want it converted to a NumPy array with the usual checks.
Exercise
You need a step that divides every value by a fixed constant, 1000, to convert grams to kilograms. A second step must subtract each column's training mean. Which step can be a FunctionTransformer, and why?
Show answer
The division by 1000 can be a FunctionTransformer, for example with lambda X: X / 1000 or a named function. It uses a fixed constant and learns nothing. The mean subtraction needs a value computed in fit and reused in transform, so it needs a class (or the built-in StandardScaler(with_std=False)).
Exercise
A pipeline step is named scale and wraps clip_values with kw_args. Write the param_grid key that tunes the bounds.
Show answer
scale__kw_args, with values that are dictionaries such as {"low": 0.0, "high": 5.0}.