Tune relational models
The defaults of scikit-link's models are chosen to give good results on most relational data without tuning. When you do tune, a few parameters matter much more than the rest. The relational ones decide which tables a model can read, and the usual ones decide how it fits them. This guide gives the order to tune them in, how to search, and recipes by situation. The pages for each model show the effect of every parameter on executed examples:
Start from the defaults
Fit the default model first and keep its score as the baseline. Tuning that does not beat it on held-out data is noise.
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalGradientBoostingClassifier
db, X, y = make_relational_classification(
600, signal="mixed", n_noise_tables=2, random_state=0
)
cv = StratifiedKFold(3, shuffle=True, random_state=0)
baseline = RelationalGradientBoostingClassifier(
db, entity="customers", key="customer_id", random_state=0
)
print(f"{cross_val_score(baseline, X, y, cv=cv).mean():.3f}")0.967Tune in this order
Each group decides what the next one can do, so tune them in this order and keep the earlier choices fixed while you search the later ones.
| Step | What it decides | Parameters |
|---|---|---|
| 1. Reach | Which tables and columns the model can read | max_relationship_depth, max_lookup_depth, primitives |
| 2. Questions | How detailed one question about related rows can be | max_conditions, condition_penalty, max_categories, max_bins, max_condition_bins |
| 3. Size | How many questions the model asks | max_depth, min_samples_leaf, max_leaf_nodes |
| 4. Ensemble | How the trees combine | n_estimators, max_features, learning_rate, subsample, l2_regularization |
| Speed | How many samples a large node searches its learned conditions on | max_search_samples |
Reach comes first because a table the model cannot read cannot help, whatever the rest. The default depth of 2, with one lookup, reaches the children of the entity, their children, and the rows those point to; raise it only when a relevant table is further away.
Search efficiently
The models are scikit-learn estimators, so every search tool works. Some habits keep relational searches affordable:
- Use the right splitter. With cutoffs, search with
TemporalCutoffSplit; with several rows per entity, group by entity. A search on the wrong splitter picks parameters that do not hold on new data. - Reuse the evaluated expressions. Fits on the same entities reuse evaluated expressions from a cache, so a grid over the size and ensemble parameters does not recompute the aggregates, within one process and up to
cache_bytes(see fit faster); withn_jobsin the search, each worker has its own cache. Parameters of the reach and questions groups change the expressions, so each value computes them again. - Search wide, then narrow.
RandomizedSearchCVor scikit-learn'sHalvingRandomSearchCV(afterfrom sklearn.experimental import enable_halving_search_cv) over the ranges of the model pages, then a small grid around the best values. Steps 3 and 4 can be searched together, as below. - Stop boosting early.
n_iter_no_changepicks the number of trees for you, so do not searchn_estimatorswith it. Its held-out rows are a random split ofX, so with cutoffs or several rows per entity, see early stopping.
from scipy.stats import loguniform
from sklearn.model_selection import RandomizedSearchCV
search = RandomizedSearchCV(
baseline,
{
"learning_rate": loguniform(0.02, 0.3),
"max_depth": [2, 3, 4],
"min_samples_leaf": [1, 5, 20],
},
n_iter=6,
cv=cv,
random_state=0,
).fit(X, y)
best = {
k: round(float(v), 3) if isinstance(v, float) else v
for k, v in search.best_params_.items()
}
print(f"{search.best_score_:.3f}", best)0.965 {'learning_rate': 0.088, 'max_depth': 3, 'min_samples_leaf': 1}Here the search does not beat the defaults, and the values it finds are close to them, so the defaults stay: a search pays only when it wins on held-out data.
Recipes by situation
Few samples
With a few hundred entities, every node holds few samples and learned conditions can fit noise. Compare a higher condition_penalty and max_conditions=0 with the defaults: when the label depends on filtered rows, as in the examples of these guides, conditions are needed. Raise min_samples_leaf, and prefer boosting with a small learning_rate and early stopping over one deep tree. Compare settings with RepeatedStratifiedKFold, because one split is noisy.
Many relationships or wide tables
Every extra hop and column multiplies the candidate questions, so fits slow down and chance winners become more likely. Keep max_relationship_depth at 1 or 2, list the aggregations you need in primitives, drop columns that carry no signal with Database(exclude={"table": ["column"]}), and search max_features in forests: low values fit faster but can miss the few tables that matter (see forests).
Imbalanced classes
Score with a metric that reads the minority class, such as average_precision or roc_auc, and stratify the folds. Tree and forest classifiers take class_weight="balanced" (forests also "balanced_subsample"). Gradient boosting has no class_weight, so pass sample_weight to fit, which every model accepts.
Fit faster
See fit faster for the settings that change only the speed.
Next steps
- Tune trees and forests
- Tune gradient boosting
- Model selection for splitters, pipelines and meta-estimators.