Skip to content

Case study: relational models in the scikit-learn toolbox ​

scikit-link's estimators are scikit-learn estimators, so the tools built around scikit-learn work on related tables too. This case study blends two relational models in a VotingClassifier, then lets TunedThresholdClassifierCV choose the decision threshold that costs a business the least. The scikit-learn guide lists every tool that is tested with scikit-link; this page shows a few of them working together on one decision.

The decision ​

A team calls customers it believes will buy a premium plan. A call to a customer who does not buy costs 1; missing a buyer costs 5, the margin of a sale. The label is whether the customer bought, and the evidence is in their orders, order items and the products in them.

python
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklink.datasets import make_relational_classification

db, X, y = make_relational_classification(
    800, signal="mixed", flip_y=0.05, random_state=0
)
X_train, X_rest, y_train, y_rest = train_test_split(
    X, y, test_size=0.5, stratify=y, random_state=0
)
X_tune, X_test, y_tune, y_test = train_test_split(
    X_rest, y_rest, test_size=0.5, stratify=y_rest, random_state=0
)
cv = StratifiedKFold(3, shuffle=True, random_state=0)
common = {"entity": "customers", "key": "customer_id"}
print(len(X_train), len(X_tune), len(X_test))
text
400 200 200

The training set fits the models, the tuning set chooses the threshold, and the test set measures the cost once.

Two views of the same tables ​

A RelationalFeaturizer followed by HistGradientBoostingClassifier reads a fixed catalog of aggregates. Relational gradient boosting learns its own aggregates and conditions at each split. A soft VotingClassifier averages their probabilities. Whether the blend beats its best member depends on the data, so all three go through the same folds.

python
from sklearn.ensemble import HistGradientBoostingClassifier, VotingClassifier
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklink.ensemble import RelationalGradientBoostingClassifier
from sklink.feature_extraction import RelationalFeaturizer

features = make_pipeline(
    RelationalFeaturizer(db, **common), HistGradientBoostingClassifier(random_state=0)
)
boosting = RelationalGradientBoostingClassifier(db, random_state=0, **common)
vote = VotingClassifier([("features", features), ("boosting", boosting)], voting="soft")
for name, model in [("features", features), ("boosting", boosting), ("vote", vote)]:
    scores = cross_val_score(model, X_train, y_train, cv=cv, scoring="roc_auc")
    print(f"{name:<9} ROC AUC {scores.mean():.3f}")
text
features  ROC AUC 0.954
boosting  ROC AUC 0.962
vote      ROC AUC 0.960

Each fold fits the featurizer's catalog and the learned conditions on its own training customers, so the scores stay honest inside the ensemble. The blend is kept for robustness: it ranks about as well as the better member. With scores this close, the simpler boosting model would serve as well.

Choose the threshold from the costs ​

predict calls a customer a buyer when the probability is above 0.5, which treats both mistakes the same. With a missed buyer five times as costly as a call, a lower threshold should pay. FrozenEstimator keeps the fitted ensemble as it is, and TunedThresholdClassifierCV searches the threshold on the tuning set with a scorer that returns the negative cost.

python
from sklearn.frozen import FrozenEstimator
from sklearn.metrics import make_scorer
from sklearn.model_selection import TunedThresholdClassifierCV


def negative_cost(y_true, y_pred):
    missed = ((y_true == 1) & (y_pred == 0)).sum()
    calls = ((y_true == 0) & (y_pred == 1)).sum()
    return -(5 * missed + calls)


vote.fit(X_train, y_train)
tuned = TunedThresholdClassifierCV(
    FrozenEstimator(vote), scoring=make_scorer(negative_cost)
).fit(X_tune, y_tune)
print(f"threshold {tuned.best_threshold_:.2f}")
print("cost at 0.5:", -negative_cost(y_test, vote.predict(X_test)))
print("cost tuned: ", -negative_cost(y_test, tuned.predict(X_test)))
text
threshold 0.13
cost at 0.5: 61
cost tuned:  36

The test customers were never used to fit or to tune, so the two costs compare the default and the tuned decision fairly.

Where to go from here ​

  • CalibratedClassifierCV(FrozenEstimator(model)) recalibrates the probabilities on the tuning set when they will be read as risks, not only ranked.
  • StackingClassifier learns the weights of the blend instead of averaging; it fits every model once per fold, so it costs more.
  • The scikit-learn guide covers ColumnTransformer for extra columns of X, importances of a scikit-learn model grouped by table, and the limits of each tool.
  • sklink.compose.TransformedTablesEstimator fits scikit-learn transformers, such as a TfidfVectorizer on a text column, on the tables themselves; see transform the tables.

Released under the MIT License.