Skip to content

Pipelines and meta-estimators ​

Place RelationalFeaturizer before a tabular estimator in a pipeline, or pass a relational classifier directly to a wrapper such as a calibration or bagging estimator. A pipeline keeps feature learning inside each training fold. A meta-estimator wraps one or more models to change how they train or combine their predictions.

Setup ​

Run this block once before trying a recipe. It generates customers and orders with some missing values and defines the base tree used below. Install the pandas extra for these examples.

python
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklink.datasets import make_relational_classification
from sklink.feature_extraction import RelationalFeaturizer
from sklink.tree import RelationalDecisionTreeClassifier

db, X, y = make_relational_classification(
    n_entities=600, signal="mixed", missing_rate=0.1, output="pandas", random_state=0
)
tree = RelationalDecisionTreeClassifier(
    db,
    entity="customers",
    key="customer_id",
    max_depth=4,
    random_state=0,
)

Native categorical features in HistGradientBoosting ​

Ask the featurizer for a pandas DataFrame so expressions such as mode(orders.type) become categorical columns. The classifier reads their types with categorical_features="from_dtype" and treats the order types as labels. Each fold learns its own columns and categories from its training rows.

python
from sklearn.ensemble import HistGradientBoostingClassifier

pipe = make_pipeline(
    RelationalFeaturizer(
        db, entity="customers", key="customer_id", max_relationship_depth=1
    ).set_output(transform="pandas"),
    HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=0),
)
print(f"{cross_val_score(pipe, X, y, cv=5).mean():.3f}")
text
0.945

A linear model with missing values ​

A customer without orders has no mean order amount. Fill missing numeric values with the median learned on each training fold, then scale them for logistic regression. One-hot encoding turns each unordered category into its own indicator column. Both steps use the featurizer's DataFrame output.

python
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import OneHotEncoder, StandardScaler

preprocess = ColumnTransformer(
    [
        (
            "categories",
            OneHotEncoder(handle_unknown="ignore"),
            make_column_selector(dtype_include="category"),
        ),
    ],
    remainder=make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
)

pipe = make_pipeline(
    RelationalFeaturizer(
        db,
        entity="customers",
        key="customer_id",
        max_relationship_depth=1,
    ).set_output(transform="pandas"),
    preprocess,
    LogisticRegression(max_iter=1000),
)
print(f"{cross_val_score(pipe, X, y, cv=5).mean():.3f}")
text
0.827

Relational trees, forests and gradient boosting models handle missing values themselves, so they need no imputer.

Calibrated probabilities ​

Use calibration when the probabilities inform a decision, such as whether to send a customer a reminder. CalibratedClassifierCV uses held-out folds to learn how to adjust the tree's probabilities. The two rows below show the output format. Its columns follow calibrated.classes_.

python
from sklearn.calibration import CalibratedClassifierCV

calibrated = CalibratedClassifierCV(tree, cv=3).fit(X, y)
print(calibrated.predict_proba(X.iloc[:2]).round(3))
text
[[0.082 0.918]
 [0.933 0.067]]

Bagging and other meta-estimators that use arrays ​

Some meta-estimators, such as BaggingClassifier, pass X to the inner estimator as a NumPy array without column names. Give the key by position, key=0, so the inner model finds customer_id in the first column. The wrapper trains several trees on resampled sets of customers and combines their predictions.

python
from sklearn.ensemble import BaggingClassifier

bagging = BaggingClassifier(
    RelationalDecisionTreeClassifier(db, entity="customers", key=0, max_depth=4),
    n_estimators=5,
    random_state=0,
)
print(f"{cross_val_score(bagging, X, y, cv=3).mean():.3f}")
text
0.923

Stacking a featurizer pipeline and a relational tree ​

Use stacking when a second model should learn how to combine predictions. Here it combines predictions from gradient boosting and the relational tree. The inner cv=3 produces out-of-fold predictions for training the combiner. The outer cross_val_score evaluates the entire stack on held-out folds.

python
from sklearn.ensemble import HistGradientBoostingClassifier, StackingClassifier

stack = StackingClassifier(
    [
        (
            "boosting",
            make_pipeline(
                RelationalFeaturizer(
                    db,
                    entity="customers",
                    key="customer_id",
                    max_relationship_depth=1,
                ).set_output(transform="pandas"),
                HistGradientBoostingClassifier(random_state=0),
            ),
        ),
        ("tree", tree),
    ],
    cv=3,
)
print(f"{cross_val_score(stack, X, y, cv=3).mean():.3f}")
text
0.948

Imbalanced classes ​

When one class is rare, use class_weight="balanced" to give it more weight during fitting. Forests also accept "balanced_subsample", which calculates weights separately for each tree's bootstrap sample. Score with balanced accuracy to give recall on each class equal weight. The example keeps only one in five positive samples to create an imbalance.

python
import numpy as np

keep = y == 0
keep[np.flatnonzero(y == 1)[::5]] = True

balanced = RelationalDecisionTreeClassifier(
    db,
    entity="customers",
    key="customer_id",
    max_depth=4,
    class_weight="balanced",
    random_state=0,
)
scores = cross_val_score(
    balanced, X.loc[keep], y[keep], cv=5, scoring="balanced_accuracy"
)
print(f"{scores.mean():.3f}")
text
0.780

Customers similar to a given one ​

To find lookalikes of a customer, describe every customer by aggregates of their orders and search the nearest ones with scikit-learn's NearestNeighbors. The include patterns keep the order counts and amounts, which are the features a person would compare. Fill the missing values first, such as the mean amount of a customer without orders, then scale so that a count and an amount weigh the same.

A Pipeline has no kneighbors, so transform with every step but the last (lookalikes[:-1]) and query the last one. The first neighbor is the customer itself; the others are its lookalikes, shown with their unscaled features.

python
from sklearn.impute import SimpleImputer
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler

lookalikes = make_pipeline(
    RelationalFeaturizer(
        db,
        entity="customers",
        key="customer_id",
        max_relationship_depth=1,
        include=["count(orders)", "count(orders[type ==*", "*(orders.amount)"],
    ).set_output(transform="pandas"),
    SimpleImputer(),
    StandardScaler(),
    NearestNeighbors(n_neighbors=4),
).fit(X)
_, neighbors = lookalikes[-1].kneighbors(lookalikes[:-1].transform(X.head(1)))
similar = X.iloc[neighbors[0]]
features = lookalikes[0].transform(similar).set_index(similar["customer_id"])
print(features[["count(orders)", "mean(orders.amount)"]].round(1))
text
             count(orders)  mean(orders.amount)
customer_id
0                     18.0                 97.7
119                   18.0                103.3
231                   17.0                 99.1
570                   17.0                 98.4

Released under the MIT License.