Sub topic 11
Combining feature sets with FeatureUnion
This chapter assumes you can build a Pipeline, read step__parameter names, and have met ColumnTransformer. It also assumes you know why fitting a transformer outside cross-validation leaks information. The goal is to learn when to build features in parallel and how to keep that parallel step safe, tunable, and inspectable.
What FeatureUnion does
A Pipeline runs steps in sequence, so each step consumes the output of the one before it. A FeatureUnion runs several transformers side by side on the same input. It then concatenates their outputs column-wise into one feature matrix.
Use it when you want several different views of the same data in one model. Examples:
- Principal components next to the best raw features.
- Word n-gram features next to character n-gram features from the same text.
- The original columns next to a transformed copy of them.
Every branch must return the same number of rows as the input. The number of output columns is the sum of the columns from all branches.
A first union
The union below puts three principal components next to the two features that score best on an F-test. The SelectKBest branch uses y, so fit needs the labels.
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X = StandardScaler().fit_transform(X) # fine for a demo; the pipeline version below does this safely
union = FeatureUnion([
("pca", PCA(n_components=3)),
("best", SelectKBest(f_classif, k=2)),
])
X_new = union.fit_transform(X, y)
print(X.shape, "->", X_new.shape)The output is (569, 30) -> (569, 5). Three PCA columns plus two selected columns give five.
make_union is the shorthand. It names each branch after its lowercased class name:
from sklearn.pipeline import make_union
union = make_union(PCA(n_components=3), SelectKBest(f_classif, k=2))
print([name for name, _ in union.transformer_list])The names are pca and selectkbest. Prefer explicit names with FeatureUnion when you plan to tune the union, because you will type those names in parameter grids.
Putting the union inside a pipeline
The scaler call above ran on the full dataset, which is the leak the earlier chapters warned about. The union has the same risk, and a worse one. SelectKBest learns from the labels, so selecting features on all the data before cross-validation makes scores optimistic. Put the union inside the pipeline so every step is refit on each training fold.
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest, f_classif
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)
pipe = Pipeline([
("scale", StandardScaler()),
("features", FeatureUnion([
("pca", PCA(n_components=3)),
("best", SelectKBest(f_classif, k=2)),
])),
("clf", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(pipe, X_train, y_train, cv=5)
print(scores.mean())In each fold, scale is fitted on the training part. The union then fits PCA and SelectKBest on the scaled training part, and the classifier trains on the combined columns. The validation part is only transformed, never fitted on.
Tuning a union
A union is one step, and its branches are nested parameters. Names join with double underscores at each level: step, branch, parameter.
from sklearn.model_selection import GridSearchCV
param_grid = {
"features__pca__n_components": [2, 5],
"features__best__k": [2, 5],
"clf__C": [0.1, 1],
}
search = GridSearchCV(pipe, param_grid, cv=5)
search.fit(X_train, y_train)
print(search.best_params_)
print(search.score(X_test, y_test))Run pipe.get_params().keys() when you are unsure of a name. It lists every valid key.
You can also treat a whole branch as a hyperparameter. Setting a branch to the string "drop" removes it from the union. This lets the search decide whether a branch earns its place:
param_grid = {
"features__pca": [PCA(n_components=3), "drop"],
"features__best__k": [2, 5],
}If every branch is dropped, the union has no features and fit raises an error. Keep at least one branch alive in every grid combination.
Weighting branches
transformer_weights multiplies each branch's output by a constant before concatenation:
union = FeatureUnion(
[("pca", PCA(n_components=3)), ("best", SelectKBest(f_classif, k=2))],
transformer_weights={"pca": 1.0, "best": 0.5},
)Weights matter for models sensitive to feature scale, such as regularized linear models and k-nearest neighbors. A weight below 1 shrinks a branch's influence under L2 regularization. Tree-based models are unaffected by a uniform rescale of a column. The weights can be tuned too, through features__transformer_weights, with a list of dictionaries as the candidate values.
Keeping the original features
A common pattern is to append engineered features to the originals. An identity transformer serves as the "original" branch. FunctionTransformer with no function does exactly that:
from sklearn.preprocessing import FunctionTransformer
import numpy as np
union = FeatureUnion([
("raw", FunctionTransformer()),
("log", FunctionTransformer(np.log1p)),
])
X_demo = np.array([[0.0, 1.0], [9.0, 99.0]])
print(union.fit_transform(X_demo))The output has four columns: the two originals, then their log1p versions. Using "passthrough" as the transformer is a shorter alternative in recent releases, but FunctionTransformer() works in every version.
A text example with sparse output
Text is the classic use case. Word n-grams capture vocabulary, and character n-grams are robust to typos and word forms. Both read the same raw strings, which is why a union fits better than a sequence here.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import FeatureUnion, Pipeline
docs = [
"great product, works well",
"terrible, it broke in a day",
"really great value",
"awful quality and poor support",
"works great, very happy",
"poor build, very disappointed",
]
labels = [1, 0, 1, 0, 1, 0]
text_model = Pipeline([
("features", FeatureUnion([
("word", TfidfVectorizer(ngram_range=(1, 2))),
("char", TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4))),
])),
("clf", LogisticRegression(max_iter=1000)),
])
text_model.fit(docs, labels)
print(text_model.predict(["great quality", "broke and poor"]))
print(text_model[:-1].transform(docs).shape)If any branch returns a sparse matrix, FeatureUnion stacks the result as a sparse matrix. A dense branch is converted as part of the stacking, so mixing a few dense columns with a large sparse block can use more memory than you expect.
Inspecting a union
FeatureUnion implements get_feature_names_out, and it prefixes each name with the branch name. That keeps names unique even when two branches produce the same label.
pipe.fit(X_train, y_train)
print(pipe.named_steps["features"].get_feature_names_out())You will see names like pca__pca0 and best__x7. Because the input was a NumPy array, the selected features show as positional names such as x7. Fit on a pandas DataFrame and you get the real column names. To read fitted branches, use named_transformers on the union, for example pipe.named_steps["features"].named_transformers["pca"].explained_variance_ratio_.
To return a DataFrame from the union, call union.set_output(transform="pandas"). This needs scikit-learn 1.2 or later, and it requires every branch to support that output. Place it before fitting.
FeatureUnion versus ColumnTransformer
The two classes look similar because both concatenate the output of several transformers. They answer different questions.
| Aspect | FeatureUnion | ColumnTransformer |
|---|---|---|
| Input to each branch | The whole input | A chosen subset of columns |
| Main purpose | Several views of the same data | Different treatment per column type |
| Column selection | None built in | Names, indices, masks, or selectors |
| Unlisted columns | Not applicable | Dropped by default, or kept with `remainder="passthrough"` |
| Typical input | Arrays, text, or any single object | DataFrames or arrays with columns |
A ColumnTransformer can list the same column in several transformers, which makes it capable of the same job on tabular data. A union is simpler when every branch should see everything, and it is the only one of the two that works when the input is not a table. Raw text, as in the example above, is a list of strings with no columns to select.
The two combine well. A common design puts a ColumnTransformer for type-specific cleaning first. A FeatureUnion after it adds PCA and selected features computed from the cleaned matrix. Nest them as steps, and use the step names in the parameter grid.
Running branches in parallel
FeatureUnion(..., n_jobs=2) fits and transforms branches concurrently using joblib. Parallelism pays off only when branches are expensive, such as large TF-IDF fits or heavy decompositions. For small, cheap transformers, process startup and data copying cost more than they save. If you tune with GridSearchCV(n_jobs=-1), avoid also setting n_jobs on the union. The two levels compete for the same CPU cores.
Common errors and pitfalls
- Branches that change the row count. A branch that drops or reorders rows breaks concatenation. Row-preserving transformers only.
- Unscaled branches. PCA on unscaled data is dominated by the largest-variance columns. Scale before the union, or give each branch its own scaling pipeline.
- Selection or fitting outside the pipeline. A supervised branch such as
SelectKBestfitted before cross-validation leaks labels into the validation folds. - Wrong parameter names.
features__kfails becausekbelongs to thebestbranch. The key isfeatures__best__k. - Duplicate step names. Names must be unique within the union, and a name cannot contain a double underscore.
- Redundant columns. Concatenating PCA output with the raw columns it came from creates strongly correlated features. Linear models cope with this under regularization, but unregularized ones become unstable.
- Forgetting
y. Callfit(X, y)or use a pipeline. Callingfit(X)alone fails for supervised branches.
Summary of the working model
- A union fits every branch on the same input and concatenates the outputs by column.
- Inside a pipeline it is refit per fold, so it adds no leakage.
- Branch settings are reachable as
unionstep__branch__param, and a branch can be switched off with"drop". - Output names carry the branch prefix, which helps debugging and feature analysis.
- Use
ColumnTransformerwhen branches need different columns, andFeatureUnionwhen they need the same input.
Exercise
A pipeline has steps named "scale", "features" (a FeatureUnion with branches "pca" and "best"), and "clf". Write the parameter-grid key that sets the number of components of the PCA branch, and explain why fitting SelectKBest on the full dataset before crossvalscore would be a mistake.
Show answer
The key is "features_pcancomponents". SelectKBest uses the labels to choose features. If it is fitted on the full dataset first, the validation folds influence which features are kept, so the cross-validation score is optimistically biased. Inside the pipeline, it is refit on each training fold only.
Exercise
You combine PCA(ncomponents=4) and SelectKBest(k=3) in a FeatureUnion, and the input has 200 rows. What shape does fittransform return, and what happens if you pass the string "drop" for the PCA branch?
Show answer
The shape is (200, 7), because the branch outputs are concatenated column-wise (4 + 3 columns). With "drop" for the PCA branch, that branch is skipped and the output has shape (200, 3). If both branches were dropped, fitting would raise an error because no features remain.