Sub topic 11
Combining feature sets with FeatureUnion
This chapter assumes you can build a Pipeline, use make_pipeline, and address step parameters with step__param names. It also assumes you know what fit and transform do. If not, review the earlier chapters on pipelines and cross-validation first.
What FeatureUnion does
A Pipeline runs steps in sequence. Each step receives the output of the previous one. A FeatureUnion runs several transformers side by side. Every transformer receives the same input, and their outputs are concatenated column-wise into one feature matrix.
Use it when you want several views of the same data as model input. A typical case is the original features plus a few principal components, or the output of two different feature selectors.
A working example
The code below scales the data, builds two feature sets from the scaled data, joins them, and fits a classifier. The FeatureUnion sits inside a Pipeline like any other step.
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import FeatureUnion, Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
features = FeatureUnion([
("pca", PCA(n_components=3)),
("best", SelectKBest(k=5)),
])
pipe = Pipeline([
("scale", StandardScaler()),
("features", features),
("clf", LogisticRegression(max_iter=1000)),
])
print(cross_val_score(pipe, X_train, y_train, cv=5).mean())
pipe.fit(X_train, y_train)
print(pipe[:-1].transform(X_train).shape) # (426, 8)
print(pipe.score(X_test, y_test))The transformed matrix has 8 columns: 3 from PCA and 5 from SelectKBest. Both transformers are fitted inside each cross-validation fold, using only the training part. This is the same leakage protection you get from a plain pipeline. SelectKBest uses the labels, so fitting it on the full dataset before cross-validation would leak label information.
There is also a shortcut, make_union, which names the transformers automatically from their class names.
Tuning a union
Parameter names nest. The pipeline step is features, the union member is pca, and the parameter is n_components. Join the levels with double underscores.
from sklearn.model_selection import GridSearchCV
param_grid = {
"features__pca__n_components": [2, 3, 5],
"features__best__k": [3, 5, 10],
}
search = GridSearchCV(pipe, param_grid, cv=5)
search.fit(X_train, y_train)
print(search.best_params_)Useful options
transformer_weights={"pca": 2.0}multiplies the output of the named transformer by a weight. This matters for models sensitive to feature scale.- Setting a member to
"drop"removes it from the union. Treat that as a tunable choice:{"features__pca": ["drop", PCA(n_components=3)]}. n_jobsfits the members in parallel. This pays off only when the members are slow.get_feature_names_out()returns the combined column names. Each name is prefixed with the member's name, so overlapping names stay distinct.
Common errors
- Row counts differ. Every member must return the same number of rows as its input. A transformer that filters rows breaks the union.
- Output is not 2D. Each member must return a 2D array or sparse matrix. A custom transformer returning a 1D array fails when concatenated.
- Duplicated information. If one member passes through the original columns and another is a linear projection of them, the combined matrix is redundant. This can make an unregularized linear model unstable.
- Confusing it with ColumnTransformer. The two classes differ in what each transformer sees:
| Class | Each transformer sees | Typical use |
|---|---|---|
| `FeatureUnion` | All input columns | Several derived views of the same data |
| `ColumnTransformer` | Its own column subset | Different preprocessing per column type |
If you want different columns to get different treatment, use ColumnTransformer. If you want several transformations of the same columns, use FeatureUnion. You can also nest one inside the other.
Exercise
A pipeline has the steps scale, features (a FeatureUnion with members named "pca" and "best"), and clf. Write the parameter-grid key that tunes the k value of the SelectKBest member. If PCA outputs 3 columns and SelectKBest outputs 5, how many columns reach the classifier?
Show answer
The key is "features_best_k". The classifier receives 8 columns, because FeatureUnion concatenates the outputs of its members side by side (3 + 5).