Skip to content

OOF Blending & Hill Climbing

Ensembling combines predictions from several models, usually in the hope of beating the best single one. Out-of-fold (OOF) predictions let you tune the blend without touching the test set. They do not guarantee a win: on this page the tuned blend beats every single model on OOF AUC but trails two of them on the test set.

Every code block runs in a container in the companion repository, so the numbers and figures are real. The dataset has 3000 samples and four base models.

A naive ensemble averages model predictions on the test set. It can help. But you have no reliable way to measure how much it helps, or to find good weights. Out-of-fold predictions fix this: all models share the same folds, and each one predicts only on the fold it never trained on, which gives you unbiased predictions for every training sample. Use those to tune the ensemble before you ever touch the test set.

The dataset is synthetic and noisy: 20 features, 6 of them informative, and label noise from flip_y=0.12. That setting reassigns 12% of the labels at random. With two classes, about half of the reassigned labels land on their original class, so only about half of those 12% actually change. A stratified split holds out 20% of the samples as the test set. The four base models are a scaled logistic regression and three tree ensembles.

from collections import Counter
from pathlib import Path
import lightgbm as lgb
import matplotlib.pyplot as plt
import numpy as np
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
out = Path("outputs")
out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=3000,
n_features=20,
n_informative=6,
n_redundant=2,
flip_y=0.12,
class_sep=0.7,
random_state=42)
x_train, x_test, y_train, y_test = train_test_split(features,
y,
test_size=0.2,
random_state=42,
stratify=y)
base_models = {
"Logistic Regression":
Pipeline([("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000,
random_state=42))]),
# One job: parallel trees add their votes in a varying order, which
# changes the last bit of predict_proba from run to run.
"Random Forest":
RandomForestClassifier(n_estimators=200,
max_depth=10,
random_state=42,
n_jobs=1),
"XGBoost":
xgb.XGBClassifier(n_estimators=200,
max_depth=5,
learning_rate=0.1,
random_state=42,
eval_metric="logloss"),
"LightGBM":
lgb.LGBMClassifier(n_estimators=200,
num_leaves=31,
learning_rate=0.1,
random_state=42,
verbose=-1),
}

Loop over shared folds, train on the training part, predict the held-out part, and average the test predictions across folds.

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
oof_preds, test_preds, results = {}, {}, {}
for name, model in base_models.items():
oof = np.zeros(len(x_train))
test_fold = np.zeros((len(x_test), cv.n_splits))
for fold, (tr, va) in enumerate(cv.split(x_train, y_train)):
model.fit(x_train[tr], y_train[tr])
oof[va] = model.predict_proba(x_train[va])[:, 1]
test_fold[:, fold] = model.predict_proba(x_test)[:, 1]
oof_preds[name] = oof
test_preds[name] = test_fold.mean(axis=1)
results[name] = (roc_auc_score(y_train, oof),
roc_auc_score(y_test, test_preds[name]))
print(f"{name:20}: OOF AUC = {results[name][0]:.4f} | "
f"Test AUC = {results[name][1]:.4f}")
Logistic Regression : OOF AUC = 0.8446 | Test AUC = 0.8123
Random Forest : OOF AUC = 0.9031 | Test AUC = 0.8754
XGBoost : OOF AUC = 0.9000 | Test AUC = 0.8821
LightGBM : OOF AUC = 0.9029 | Test AUC = 0.8823

Averaging test predictions across the five fold models reduces variance versus a single final model.

blind_oof = np.mean(list(oof_preds.values()), axis=0)
blind_test = np.mean(list(test_preds.values()), axis=0)
results["Blind Average"] = (roc_auc_score(y_train, blind_oof),
roc_auc_score(y_test, blind_test))
print(f"Blind average: OOF AUC = {results['Blind Average'][0]:.4f} | "
f"Test AUC = {results['Blind Average'][1]:.4f}")
Blind average: OOF AUC = 0.9044 | Test AUC = 0.8776

On OOF AUC the blind average already edges past the best single model, 0.9044 against 0.9031, even though it includes the weak logistic regression. On test it falls below XGBoost and LightGBM. Can we find better weights?

Hill climbing greedily builds a “bag” of models. At each step it adds whichever model most improves the OOF AUC. A model can be added many times, so its final weight is how often it was chosen.

def hill_climb(oof_dict, y_true, n_iter=100):
"""Find nonnegative out of fold model weights.
Args:
oof_dict: Mapping from model name to out of fold predictions.
y_true: Observed binary outcomes.
n_iter: Maximum number of greedy selection steps.
Returns:
A tuple of the mapping from model name to normalized weight and the
list of OOF AUC values, one per accepted step.
"""
single = {n: roc_auc_score(y_true, oof_dict[n]) for n in oof_dict}
best = max(single, key=single.get)
bag, history = [best], [single[best]]
for _ in range(n_iter - 1):
pick, cur = None, history[-1]
for n in oof_dict:
c = Counter(bag + [n])
blend = sum((c[k] / sum(c.values())) * oof_dict[k] for k in c)
s = roc_auc_score(y_true, blend)
if s > cur:
cur, pick = s, n
if pick is None:
break
bag.append(pick)
history.append(cur)
c = Counter(bag)
return {n: c[n] / len(bag) for n in c}, history

Run it on the four OOF columns, then apply the same weights to the test predictions.

hc_weights, hc_history = hill_climb(oof_preds, y_train)
print("Hill climbing weights:")
for name in sorted(hc_weights, key=hc_weights.get, reverse=True):
print(f" {name:14}: {hc_weights[name]:.3f}")
hc_oof = sum(w * oof_preds[n] for n, w in hc_weights.items())
hc_test = sum(w * test_preds[n] for n, w in hc_weights.items())
results["Hill Climbing"] = (roc_auc_score(y_train, hc_oof),
roc_auc_score(y_test, hc_test))
print(f"Hill climbing: OOF AUC = {results['Hill Climbing'][0]:.4f} | "
f"Test AUC = {results['Hill Climbing'][1]:.4f}")
Hill climbing weights:
Random Forest : 0.625
LightGBM : 0.250
XGBoost : 0.125
Hill climbing: OOF AUC = 0.9078 | Test AUC = 0.8817

Hill climbing excluded logistic regression entirely and mixed the three tree models. Its OOF score (0.9078) beats the blind average (0.9044). The weights were picked on these same OOF rows, so that score flatters the blend a little, and the test set below is the fair check.

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(range(1, len(hc_history) + 1), hc_history, marker="o",
color="#4c72b0")
ax.set_xlabel("Iteration")
ax.set_ylabel("OOF ROC-AUC")
ax.set_title("Hill climbing convergence")
fig.tight_layout()
fig.savefig(out / "hill-climbing-convergence.png", dpi=150)
plt.close(fig)

Hill climbing OOF AUC rising over iterations then plateauing

labels = list(results)
xpos = np.arange(len(labels))
fig, ax = plt.subplots(figsize=(9, 4))
ax.bar(xpos - 0.2, [results[k][0] for k in labels], 0.4, label="OOF",
color="#4c72b0")
ax.bar(xpos + 0.2, [results[k][1] for k in labels], 0.4, label="Test",
color="#dd8452")
ax.set_xticks(xpos)
ax.set_xticklabels(labels, rotation=30, ha="right", fontsize=8)
ax.set_ylim(0.80, 0.92)
ax.set_ylabel("ROC-AUC")
ax.legend()
ax.set_title("OOF vs test AUC by method")
fig.tight_layout()
fig.savefig(out / "ensemble-oof-comparison.png", dpi=150)
plt.close(fig)

Bar chart of OOF and test AUC for each base model, the blind average, and hill climbing, on a y axis that starts at 0.80

The y axis starts at 0.80, so the bars exaggerate the gaps between methods.

Every test score sits below its OOF score. Some conclusions survive the move to the test set. Logistic regression is the weakest model in both columns, and hill climbing beats the blind average in both, 0.9078 against 0.9044 OOF and 0.8817 against 0.8776 on test. Others do not. OOF ranks Random Forest first among the single models (0.9031), and hill climbing gives it the largest weight (0.625), yet on test it is the weakest tree model (0.8754). The hill climbing blend (0.8817) also finishes below LightGBM (0.8823) and XGBoost (0.8821) on test. The gaps between the tree models are a few thousandths of AUC, and a test set of 600 rows does not separate gaps that small reliably. OOF tuning keeps the test set out of the decisions; it does not promise that the blend wins on it.

Scenario Approach
2 to 3 similar models Simple average is fine
4+ diverse models Hill climbing finds better weights
Weak models in the pool Hill climbing drops them automatically
Many models (10+) Hill climbing or stacking

The next page, Stacking, replaces the weighted average with a trained meta-model on the OOF predictions.

Ke and colleagues, 2017 describe LightGBM, a fast implementation of gradient boosting decision trees.

Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.

  • Caruana on ensemble selection

    The original author describes forward selection from a library of models and optimization for a chosen performance metric. The linked papers provide the method context for the greedy blend search.

  • scikit-learn StackingClassifier

    The reference distinguishes cross-validated meta-model inputs from base-model refits on all training rows. Compare those choices with the fold-averaged test predictions used here.