Skip to main content

AI and machine learning · Intermediate · 25 min

Tune model settings with grid search and random search

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · scikit-learn 1.9.1 · SciPy 1.18.1 · NumPy 2.5.5

You will tune a gradient-boosting churn model with GridSearchCV, RandomizedSearchCV and HalvingRandomSearchCV, compare what each costs and finds, read cv_results_ to see how flat the top is, and report an honest score with nested cross-validation and an untouched test set.

On this page

Every model has settings you choose before training: how fast a boosting model learns, how big each tree may grow, how many rows a leaf needs. scikit-learn calls them hyperparameters. The defaults are a reasonable start, not an answer for your data, and choosing better ones by hand means many runs and an easy way to fool yourself: try enough settings against one validation score and the best of them looks better than it is.

In this tutorial a prepaid mobile operator wants to know which customers will stop topping up next month, so it can send them an offer first. You generate 4,000 customers, lock away a test set, and tune a HistGradientBoostingClassifier three ways: a grid of every combination, a random sample from ranges, and successive halving, which tries many settings on a little data and gives the survivors more. You compare their cost and results, read the full table of scores to see how many settings are in fact as good as the winner, and finish with two honest numbers: a nested cross-validation estimate, and one look at the test set.

The data is synthetic, so the numbers repeat and no real customer is involved. The whole tutorial runs on a laptop CPU in about three minutes.

Step 1 · Create the project and install scikit-learn

Make a throwaway folder and a virtual environment, then install pinned versions of scikit-learn, SciPy and NumPy:

Bash
mkdir -p ~/churn-tuning-demo
cd ~/churn-tuning-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet scikit-learn==1.9.1 scipy==1.18.1 numpy==2.5.5

The download is around 60 MB. On prepaid mobile data, do it once on Wi-Fi; nothing after this needs a connection.

HistGradientBoostingClassifier uses every CPU core through OpenMP. When a search also runs many fits, or the laptop is busy with other work, too many threads compete and each fit can become many times slower. Cap the threads so the timings you compare later are steady:

Bash
export OMP_NUM_THREADS=2

The setting lasts for this terminal only. Run it again if you open a new one.

Check it worked

Bash
python -c "import sklearn, scipy, numpy; print(sklearn.__version__, scipy.__version__, numpy.__version__)"

The output is 1.9.1 1.18.1 2.5.5.

Step 2 · Generate customers and lock away a test set

Each customer has six features and one label:

  • days_since_topup: days since the last airtime or data purchase
  • avg_topup: average top-up, in US dollars
  • data_gb: data used last month, in GB
  • tenure_months: months on the network
  • complaints: support complaints in the last 90 days
  • dual_sim: 1 if the phone also holds another network's SIM
  • churned: 1 if the customer stopped topping up the next month, the thing to predict

The hidden rule has the kind of interactions boosting is good at: complaints matter more for a dual-SIM customer, who can switch networks by tapping a menu, and a small spender with a second SIM is more likely to drift.

Bash
cat > make_data.py <<'PY'
import csv

import numpy as np

rng = np.random.default_rng(7)
N = 4000

days_since_topup = rng.integers(0, 61, size=N)
avg_topup = rng.lognormal(mean=np.log(1.5), sigma=0.6, size=N).round(2)
data_gb = rng.gamma(shape=2.0, scale=1.5, size=N).round(2)
tenure_months = rng.integers(1, 97, size=N)
complaints = rng.poisson(0.4, size=N)
dual_sim = rng.integers(0, 2, size=N)

score = (
    -1.2
    + 0.06 * np.maximum(days_since_topup - 14, 0)
    + 0.8 * complaints * dual_sim
    + 0.5 * complaints
    - 0.6 * np.log1p(data_gb)
    - 0.015 * tenure_months
    + 0.9 * ((avg_topup < 1.0) & (dual_sim == 1))
)
p = 1 / (1 + np.exp(-score))
churned = (rng.random(N) < p).astype(int)

with open("customers.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["days_since_topup", "avg_topup", "data_gb", "tenure_months", "complaints", "dual_sim", "churned"])
    for row in zip(days_since_topup, avg_topup, data_gb, tenure_months, complaints, dual_sim, churned):
        w.writerow(row)

print(f"wrote {N} customers, {churned.mean():.1%} churned")
PY
python make_data.py

Now split off 20% as a test set and save the two parts to separate files. Every search in this tutorial reads only train.npz. The test file is opened once, in the last step, after every choice is made. If you tune against the test set, it stops being a test.

Bash
cat > split.py <<'PY'
import numpy as np
from sklearn.model_selection import train_test_split

data = np.loadtxt("customers.csv", delimiter=",", skiprows=1)
X, y = data[:, :-1], data[:, -1].astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

np.savez("train.npz", X=X_train, y=y_train)
np.savez("test.npz", X=X_test, y=y_test)
print(f"train: {len(y_train)} rows, test: {len(y_test)} rows (locked away until the last step)")
PY
python split.py

The three search scripts share a loader, one set of five stratified folds, a timer and a function that saves each search's result to results/:

Bash
cat > common.py <<'PY'
import json
import time
from pathlib import Path

import numpy as np
from sklearn.model_selection import StratifiedKFold

SEED = 0
CV = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)


def load_train():
    """The training part only. test.npz stays closed until the last step."""
    data = np.load("train.npz")
    return data["X"], data["y"]


def plain(params):
    """Turn NumPy numbers into plain Python ones so they can be saved as JSON."""
    return {k: (v.item() if hasattr(v, "item") else v) for k, v in params.items()}


def save_result(name, search, seconds):
    Path("results").mkdir(exist_ok=True)
    settings = {json.dumps(plain(p), sort_keys=True) for p in search.cv_results_["params"]}
    out = {
        "name": name,
        "best_score": float(search.best_score_),
        "best_params": plain(search.best_params_),
        "settings_tried": len(settings),
        "seconds": round(seconds, 1),
    }
    Path(f"results/{name}.json").write_text(json.dumps(out, indent=2))
    return out


class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, *exc):
        self.seconds = time.perf_counter() - self.start
PY

Before tuning anything, score the default settings with the same folds, so you know what tuning has to beat. The score is ROC AUC: the chance that a random churner gets a higher score than a random stayer. 0.5 is guessing, 1.0 is perfect.

Bash
cat > baseline.py <<'PY'
import json
from pathlib import Path

from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_validate

from common import CV, SEED, load_train

X, y = load_train()
scores = cross_validate(
    HistGradientBoostingClassifier(random_state=SEED), X, y,
    cv=CV, scoring="roc_auc", return_train_score=True,
)
val = scores["test_score"]
print(f"default settings: train AUC {scores['train_score'].mean():.3f}, "
      f"validation AUC {val.mean():.3f} ± {val.std():.3f}")

Path("results").mkdir(exist_ok=True)
Path("results/baseline.json").write_text(json.dumps({"best_score": float(val.mean())}))
PY
python baseline.py

Check it worked

You see wrote 4000 customers, 29.4% churned, then train: 3200 rows, test: 800 rows, then a default validation AUC of about 0.755 ± 0.006. The training AUC is about 0.984. That gap says the default model fits its training rows far better than new ones: trees of 31 leaves with as few as 20 rows each are learning noise. That is the first thing tuning can fix.

Step 3 · Search a grid with GridSearchCV

A grid search tries every combination of the values you list. Three settings control how much each boosting round can learn:

  • learning_rate: how much each new tree corrects the previous ones
  • max_leaf_nodes: the most leaves one tree may have
  • min_samples_leaf: the fewest training rows a leaf may hold

Three values, three values and two values make 18 combinations. With five folds, that is 90 fits:

Bash
cat > grid.py <<'PY'
import json
from pathlib import Path

from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import GridSearchCV

from common import CV, SEED, Timer, load_train, save_result

X, y = load_train()

param_grid = {
    "learning_rate": [0.03, 0.1, 0.3],
    "max_leaf_nodes": [7, 15, 31],
    "min_samples_leaf": [20, 80],
}

search = GridSearchCV(
    HistGradientBoostingClassifier(random_state=SEED),
    param_grid,
    scoring="roc_auc",
    cv=CV,
)
with Timer() as t:
    search.fit(X, y)

r = save_result("grid", search, t.seconds)
print(f"grid search: {r['settings_tried']} settings x 5 folds = {r['settings_tried'] * 5} fits in {r['seconds']} s")
print(f"best validation AUC: {r['best_score']:.4f}")
print(f"best settings: {r['best_params']}")

baseline = json.loads(Path("results/baseline.json").read_text())["best_score"]
assert r["best_score"] > baseline
PY
python grid.py

search.fit runs every fit, keeps the mean validation score of each combination, and then, because refit=True is the default, trains one more model on all 3,200 rows with the winning settings. That model is search.best_estimator_.

Check it worked

The output reads something like 18 settings x 5 folds = 90 fits in 13 s, a best validation AUC of 0.7798 and best settings: {'learning_rate': 0.1, 'max_leaf_nodes': 7, 'min_samples_leaf': 80}. Smaller trees with bigger leaves beat the default by about 0.025: the overfitting from the previous step was costing real accuracy.

Notice where the winner sits: 7 leaves is the smallest value on the grid and 80 rows the largest. When the best value is on the edge of a grid, the true best may lie beyond it. You could extend the grid, but every new value multiplies the number of fits.

Step 4 · Sample settings with RandomizedSearchCV

A random search draws each candidate from a range instead of a list. For the same budget it tries 18 different values of every setting, not three, which matters when only one or two settings drive the score: a grid wastes most of its fits repeating the same few values of the setting that counts.

Ranges come from scipy.stats. loguniform suits a learning rate, where 0.01 to 0.05 matters as much as 0.1 to 0.5; randint gives whole numbers; uniform(0.0, 2.0) means 0.0 to 2.0. This search also adds a fourth setting, l2_regularization, which penalises large leaf values, at no extra cost:

Bash
cat > random_search.py <<'PY'
import json
from pathlib import Path

from scipy.stats import loguniform, randint, uniform
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV

from common import CV, SEED, Timer, load_train, plain, save_result

X, y = load_train()

param_distributions = {
    "learning_rate": loguniform(0.01, 0.5),
    "max_leaf_nodes": randint(4, 64),        # 4 to 63
    "min_samples_leaf": randint(10, 150),    # 10 to 149
    "l2_regularization": uniform(0.0, 2.0),  # 0.0 to 2.0
}

search = RandomizedSearchCV(
    HistGradientBoostingClassifier(random_state=SEED),
    param_distributions,
    n_iter=18,
    scoring="roc_auc",
    cv=CV,
    random_state=SEED,
)
with Timer() as t:
    search.fit(X, y)

r = save_result("random", search, t.seconds)
print(f"random search: {r['settings_tried']} settings x 5 folds = {r['settings_tried'] * 5} fits in {r['seconds']} s")
print(f"best validation AUC: {r['best_score']:.4f}")
print("best settings:", {k: round(v, 3) for k, v in r["best_params"].items()})

res = search.cv_results_
rows = [
    {
        "rank": int(res["rank_test_score"][i]),
        "mean": float(res["mean_test_score"][i]),
        "std": float(res["std_test_score"][i]),
        "params": plain(res["params"][i]),
    }
    for i in range(len(res["params"]))
]
Path("results/random_cv_results.json").write_text(json.dumps(rows, indent=2))
PY
python random_search.py

random_state=SEED on the search fixes which 18 candidates are drawn, so you get the same ones each run. The script also saves cv_results_, the full table of scores, for a later step.

Check it worked

The output shows 18 settings x 5 folds = 90 fits, a best validation AUC of about 0.7803, and best settings close to learning_rate 0.092, max_leaf_nodes 4, min_samples_leaf 63 and l2_regularization 0.912. The same budget found a score level with the grid's, with a tree size (4 leaves) the grid could not try. results/ now holds random.json and random_cv_results.json.

Step 5 · Try more settings for less with successive halving

Most candidates in a search are clearly worse after a quick look. Successive halving uses that: it scores many candidates on a small slice of the training rows, keeps the best third (factor=3), gives those three times as many rows, and repeats until a few candidates run on nearly all the data.

HalvingRandomSearchCV is still marked experimental in scikit-learn 1.9, so you switch it on with an import first. Its API may change between releases without the usual deprecation warnings, so pin your scikit-learn version when you use it:

Bash
cat > halving.py <<'PY'
from scipy.stats import loguniform, randint, uniform
from sklearn.experimental import enable_halving_search_cv  # noqa: F401  (switches the feature on)
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import HalvingRandomSearchCV

from common import CV, SEED, Timer, load_train, save_result

X, y = load_train()

param_distributions = {
    "learning_rate": loguniform(0.01, 0.5),
    "max_leaf_nodes": randint(4, 64),
    "min_samples_leaf": randint(10, 150),
    "l2_regularization": uniform(0.0, 2.0),
}

search = HalvingRandomSearchCV(
    HistGradientBoostingClassifier(random_state=SEED),
    param_distributions,
    n_candidates=54,
    factor=3,
    min_resources=300,
    scoring="roc_auc",
    cv=CV,
    random_state=SEED,
)
with Timer() as t:
    search.fit(X, y)

r = save_result("halving", search, t.seconds)
print(f"halving search: {r['settings_tried']} settings in {r['seconds']} s")
for i, (n, rows) in enumerate(zip(search.n_candidates_, search.n_resources_)):
    print(f"  round {i}: {n:>3} candidates on {rows:>4} rows")
print(f"best validation AUC: {r['best_score']:.4f}")
print("best settings:", {k: round(v, 3) for k, v in r["best_params"].items()})

assert list(search.n_candidates_) == [54, 18, 6]
PY
python halving.py

Check it worked

The rounds print as:

Text
  round 0:  54 candidates on  300 rows
  round 1:  18 candidates on  900 rows
  round 2:   6 candidates on 2700 rows

The best validation AUC is about 0.7758, and the search took something like 23 s for 54 settings. That score is a little below the other two for two reasons: the final round scores on 2,700 rows, not all 3,200, and a candidate that starts slowly on 300 rows can be dropped early even if it would have won on more data. Halving trades some certainty about each candidate for breadth.

Step 6 · Compare the searches and read how flat the top is

Put the three searches side by side:

Bash
cat > compare.py <<'PY'
import json
from pathlib import Path

base = json.loads(Path("results/baseline.json").read_text())["best_score"]
print(f"default settings                     {base:.4f}")
print("search    settings  seconds  best AUC")
for name in ["grid", "random", "halving"]:
    r = json.loads(Path(f"results/{name}.json").read_text())
    print(f"{name:<8}  {r['settings_tried']:>8}  {r['seconds']:>7}  {r['best_score']:.4f}")
PY
python compare.py

The table shows something like this, with your own timings:

Text
default settings                     0.7554
search    settings  seconds  best AUC
grid            18     12.9  0.7798
random          18     15.0  0.7803
halving         54     22.6  0.7758

The winners differ in the fourth decimal place. Before you read anything into that, look at the whole field. best_score_ is one mean over five folds, and each mean comes with a spread. This script sorts the random search's cv_results_ and counts how many candidates are within one standard deviation of the winner:

Bash
cat > flat_top.py <<'PY'
import json
from pathlib import Path

rows = sorted(json.loads(Path("results/random_cv_results.json").read_text()), key=lambda r: r["rank"])
best = rows[0]

print("rank  mean AUC  ± std   learning_rate  max_leaf_nodes  min_samples_leaf")
for r in rows[:8]:
    p = r["params"]
    print(f"{r['rank']:>4}  {r['mean']:.4f}  {r['std']:.4f}  {p['learning_rate']:>13.3f}  "
          f"{p['max_leaf_nodes']:>14}  {p['min_samples_leaf']:>16}")
print(f"...\nworst {rows[-1]['mean']:.4f}")

close = [r for r in rows if r["mean"] >= best["mean"] - best["std"]]
print(f"\n{len(close)} of {len(rows)} candidates score within one standard deviation ({best['std']:.4f}) of the best")
assert len(close) > 1
PY
python flat_top.py

Check it worked

The top eight rows run from about 0.7803 down to 0.7717, the worst candidate scores about 0.7205, and the last line reads 13 of 18 candidates score within one standard deviation (0.0135) of the best.

That is a flat top. The top candidates differ by less than the fold-to-fold noise, with learning rates from 0.02 to 0.16 and leaf counts from 4 to 35. Treat the winner as one good choice from a group of equals, not as the best settings. In practice that means two things: stop searching once the top is flat, because more candidates mostly find noise; and among the near-equals you may pick the cheaper or simpler one (fewer leaves, a higher learning rate that needs fewer rounds) with a clear conscience. On a slow laptop or a small cloud machine, that choice also makes every later retrain faster.

Step 7 · Report an honest estimate with nested cross-validation

best_score_ is the score of the candidate that won on these folds. Choosing the maximum of several noisy numbers biases it upwards, so it is not a fair estimate of how the tuned model will do on new customers. Nested cross-validation fixes that by wrapping the whole search in a second loop. An outer split holds out one fifth of the training rows, the search runs on the other four fifths (with its own inner folds), and the chosen model is scored on the held-out fifth, which the search never saw. Five outer folds give five honest scores.

A search object is an estimator, so you can pass it straight to cross_val_score. The inner search here is the same one as in the random search step:

Bash
cat > nested.py <<'PY'
import json
from pathlib import Path

from scipy.stats import loguniform, randint, uniform
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold, cross_val_score

from common import CV, SEED, Timer, load_train

X, y = load_train()

search = RandomizedSearchCV(
    HistGradientBoostingClassifier(random_state=SEED),
    {
        "learning_rate": loguniform(0.01, 0.5),
        "max_leaf_nodes": randint(4, 64),
        "min_samples_leaf": randint(10, 150),
        "l2_regularization": uniform(0.0, 2.0),
    },
    n_iter=18,
    scoring="roc_auc",
    cv=CV,
    random_state=SEED,
)

# A different shuffle from the inner folds, so the outer folds are a separate split.
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)

with Timer() as t:
    outer = cross_val_score(search, X, y, cv=outer_cv, scoring="roc_auc")

picked = json.loads(Path("results/random.json").read_text())["best_score"]
print(f"nested CV: {5 * 18 * 5} inner fits in {t.seconds:.0f} s")
print("outer fold AUCs:", " ".join(f"{s:.3f}" for s in outer))
print(f"nested estimate:              {outer.mean():.4f} ± {outer.std():.4f}")
print(f"best_score_ from the search:  {picked:.4f}")
print(f"optimism of picking the best: {picked - outer.mean():+.4f}")

assert 0.70 < outer.mean() < 0.85
PY
python nested.py

This is the slowest step: 450 fits, about a minute on a laptop.

Check it worked

The outer fold AUCs read something like 0.764 0.772 0.799 0.788 0.775, the nested estimate is about 0.7798 ± 0.0123, and the optimism line is close to +0.0004.

Here the bias is tiny: 18 candidates on a flat top cannot inflate the maximum much. Do not count on that. Search hundreds of candidates on a few hundred rows and the gap can be several points, which is how a model that looked strong in a notebook disappoints in production. The nested run is also how you learn the spread: five honest scores from 0.76 to 0.80 tell a manager far more than one number to four decimal places. Note that nested CV scores the tuning procedure, not one fixed set of settings, and each outer fold may pick different winners. For the model you ship, run the search once on all the training data, as the earlier steps did.

Step 8 · Score the chosen model once on the test set

Every choice is now made: the random search's settings, trained on all 3,200 training rows. Open test.npz for the first time, and score the tuned model and the defaults side by side:

Bash
cat > final_test.py <<'PY'
import json
from pathlib import Path

import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score

from common import SEED, load_train

X_train, y_train = load_train()
test = np.load("test.npz")
X_test, y_test = test["X"], test["y"]

params = json.loads(Path("results/random.json").read_text())["best_params"]
tuned = HistGradientBoostingClassifier(random_state=SEED, **params).fit(X_train, y_train)
default = HistGradientBoostingClassifier(random_state=SEED).fit(X_train, y_train)

tuned_auc = roc_auc_score(y_test, tuned.predict_proba(X_test)[:, 1])
default_auc = roc_auc_score(y_test, default.predict_proba(X_test)[:, 1])
print(f"test AUC, tuned settings:   {tuned_auc:.4f}")
print(f"test AUC, default settings: {default_auc:.4f}")

assert tuned_auc > default_auc
PY
python final_test.py

Check it worked

The output is about 0.7951 for the tuned settings and 0.7603 for the defaults. The tuned score sits inside the 0.76 to 0.80 range the nested run predicted, a little high, which is what one sample of 800 customers does. Report the nested estimate and its spread as the expected performance, and the test score as the check that nothing went wrong.

Resist the urge to go back and tune again now that you have seen the test score. If you do, the test set becomes one more validation fold and you need a fresh one to make an honest claim.

Step 9 · Clean up

Leave the virtual environment and delete the project folder:

Bash
deactivate
cd ~
rm -rf ~/churn-tuning-demo
ls ~/churn-tuning-demo 2>/dev/null || echo "removed"

Check it worked

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.