Examples · scikit-learn
Stacking ensemble regression in scikit-learn
Stacking lets a model learn how much to trust other models: gradient boosting, a support vector regression and a Gaussian process predict a number from eight features, and a ridge regression learns from their predictions how to combine them.
Open in the editor See the code
- Code
- scikit-learn
- Task
- Regression
- Input
- 8
- Bricks
- 8
- Model
- StackingRegressor
What the network does
The three models get the features from the Input. The Gaussian process has a kernel of its own, an RBF plus a WhiteKernel joined by KernelSum (the dashed connections carry the kernel). The dotted connections into StackingRegressor carry the three models.
With cv = 5, each model is fitted five times, each time without a fifth of the training rows, and predicts that fifth. The ridge regression learns from these predictions for rows the models did not see, so it does not reward a model that only memorised the data. Then each model is fitted once more on all rows. Fitting therefore takes about six times as long as fitting the three models once.
When to use it
- When different kinds of models capture different parts of the relationship, for example house prices with smooth and abrupt effects.
- When a simple average is not enough because one model is clearly better in some regions.
- On tables up to a few thousand rows here, because of the Gaussian process (at most 5,000 training rows in Brick DNN).
Layers, shapes and parameters
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
features | Input | shape=8 | 8 | 0 |
boosting | HistGradientBoostingRegressor | learning_rate=0.1 max_iter=200 max_leaf_nodes=31 min_samples_leaf=20 l2_regularization=0 early_stopping=auto random_state=0 | model | – |
svr | SVR | kernel=rbf C=1 gamma=scale epsilon=0.1 | model | – |
rbf | RBF | length_scale=1 hyperparameters=optimize | kernel | 1 hyperparameter |
noise | WhiteKernel | noise_level=0.1 hyperparameters=optimize | kernel | 1 hyperparameter |
kernel | KernelSum | defaults | kernel | 0 |
gp | GaussianProcessRegressor | alpha=1e-10 normalize_y=true n_restarts_optimizer=0 | model | 0 |
stack | StackingRegressor | cv=5 passthrough=false | 1 | – |
| Total | none: fitted by scikit-learn | |||
Training it in Brick DNN
Upload a CSV file of eight numeric features and a numeric target, or use a dataset from the Data tab. The run reports RMSE and R² of the ensemble and of each model on the validation rows, so you see whether stacking beats its best model.
The generated code
This is the scikit-learn script that the editor’s code dialog generates from the graph above (stacking_ensemble_regression.py). It runs on its own: python stacking_ensemble_regression.py fits the model to random data, --csv data.csv fits it to your table and saves it, --predict predicts new rows.
# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""Stacking regression: generated with Brick DNN.
A scikit-learn ensemble for 8 numeric features: they are standardised, then
StackingRegressor combines 3 models (boosting: HistGradientBoostingRegressor, svr: SVR, gp:
GaussianProcessRegressor) and predicts one number per row. RidgeCV learns from their
predictions for rows they were not fitted on (5-fold cross-validation) how to combine them.
Kernel of gp (the starting point; fitting optimises it):
RBF(length_scale=1.0)
+ WhiteKernel(noise_level=0.1)
Print the model and fit it to random data:
python this_file.py
Fit it to a CSV file (every column but the last is a feature, the last column is
the target), then predict new rows with the saved model:
python this_file.py --csv data.csv
python this_file.py --predict new_data.csv
Log the fit to Brick DNN, to see its results next to the runs trained there (the runs
page): create an API token on the page API tokens (one that may only log runs is enough)
and set it in the environment before you train:
export BRICKDNN_TOKEN=<your token>
python this_file.py --csv data.csv
It sends the model and its hyperparameters, the name of the CSV file, the RMSE, MAE and
R² on the validation rows and the time the fit took to BRICKDNN_URL (default
https://brickdnn.com). Without BRICKDNN_TOKEN nothing is sent and the script runs
offline with the same results; a network error never stops the training. The token is
never stored in this file.
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import os
import sys
import time
import urllib.error
import urllib.request
import warnings
import joblib
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor, StackingRegressor
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
from sklearn.linear_model import RidgeCV
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
NUM_FEATURES = 8
def make_model() -> Pipeline:
"""Standardise the features (with the mean and standard deviation of the data
it is fitted to), then fit StackingRegressor with its 3 models."""
boosting = HistGradientBoostingRegressor(
learning_rate=0.1,
max_iter=200,
max_leaf_nodes=31,
max_depth=None,
min_samples_leaf=20,
l2_regularization=0.0,
early_stopping="auto",
random_state=0,
)
svr = SVR(kernel="rbf", C=1.0, gamma="scale", epsilon=0.1)
gp_kernel = RBF(length_scale=1.0) + WhiteKernel(noise_level=0.1)
gp = GaussianProcessRegressor(kernel=gp_kernel, alpha=1e-10, normalize_y=True)
model = StackingRegressor(
estimators=[("boosting", boosting), ("svr", svr), ("gp", gp)],
final_estimator=RidgeCV(),
cv=5,
passthrough=False,
)
return Pipeline([("scale", StandardScaler()), ("model", model)])
# --------------------------------------------------------------------------- #
# CSV files: fitting, saving and predictions for new rows
# --------------------------------------------------------------------------- #
def read_csv(path: str) -> tuple[list[str], list[list[str]]]:
"""Read a CSV file: the column names of its header line (an empty list if it has none)
and the rows (as text)."""
with open(path, newline="") as f:
rows = [row for row in csv.reader(f) if row]
header: list[str] = []
if rows:
cells = rows[0][:-1] or rows[0] # the last column (the target) may hold text
try:
[float(value) for value in cells]
except ValueError:
header, rows = [name.strip() for name in rows[0]], rows[1:]
if not rows:
raise SystemExit(f"{path} contains no data rows.")
return header, rows
def numbers(rows: list[list[str]], path: str) -> np.ndarray:
try:
return np.array([[float(value) for value in row] for row in rows])
except ValueError as exc:
raise SystemExit(f"{path}: {exc}") from None
def load_csv(path: str) -> tuple[list[str], np.ndarray, np.ndarray]:
"""Training data: every column but the last is a feature, the last one is the target."""
header, rows = read_csv(path)
if any(len(row) != NUM_FEATURES + 1 for row in rows):
raise SystemExit(f"Expected {NUM_FEATURES} feature columns and the target in every row.")
features = numbers([row[:-1] for row in rows], path)
target = numbers([row[-1:] for row in rows], path)[:, 0]
return header, features, target
def fit(
model: Pipeline,
features: np.ndarray,
target: np.ndarray,
seed: int,
run: BrickDNNRun | None = None,
) -> None:
"""Fit on a random 80 % of the rows and validate on the rest (the split depends only on
``seed``). The StandardScaler of the pipeline learns from the training rows only."""
if len(features) < 4:
raise SystemExit("The CSV file needs at least 4 rows (training + validation).")
order = np.random.default_rng(seed).permutation(len(features))
n_val = max(1, len(features) // 5)
val_rows, train_rows = order[:n_val], order[n_val:]
print(f"Fitting on {len(train_rows)} rows, {len(val_rows)} for validation")
started = time.perf_counter()
model.fit(features[train_rows], target[train_rows])
seconds = time.perf_counter() - started
print(f"Fitted in {seconds:.1f} s")
errors = model.predict(features[val_rows]) - target[val_rows]
rmse = float(np.sqrt(np.mean(errors**2)))
spread = float(np.sum((target[val_rows] - target[val_rows].mean()) ** 2))
r2 = 1 - float(np.sum(errors**2)) / spread if spread > 0 else float("nan")
print(f"Validation RMSE {rmse:.4g}, R² {r2:.3f}")
ensemble = model.named_steps["model"]
print(f"Models: {', '.join(ensemble.named_estimators_)}")
print(f"Final estimator: {ensemble.final_estimator_}")
if run is not None and run.active:
summary = scores(model, features[val_rows], target[val_rows])
run.finish(summary={**summary, "fit_seconds": round(seconds, 3)})
def save_model(model: Pipeline, path: str, header: list[str]) -> None:
"""Save the fitted pipeline with what predict() needs to read new rows. joblib files
are pickles: only load files you trust."""
bundle = {
"format": "brickdnn-sklearn-1",
"model": model,
"columns": header[:-1], # the feature columns by name (empty: no header line)
"target": header[-1] if header else "target",
"task": "regression",
"class_names": None,
}
joblib.dump(bundle, path)
print(f"Saved the fitted model to {path}")
def scores(model: Pipeline, features: np.ndarray, target: np.ndarray) -> dict[str, float]:
"""The numbers of the fitted model on the validation rows that are logged to Brick DNN,
named like the columns of its runs table. Logging never stops the script: a number that
cannot be computed is left out."""
found: dict[str, float] = {}
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore") # e.g. R² of a single validation row
predicted = model.predict(features)
found["val_rmse"] = float(np.sqrt(mean_squared_error(target, predicted)))
found["val_mae"] = float(mean_absolute_error(target, predicted))
found["val_r2"] = float(r2_score(target, predicted))
except Exception:
pass
return found
def model_settings(model: Pipeline) -> dict:
"""The hyperparameters of the model for its run in Brick DNN: numbers, words and
switches, other objects (an inner model) as text, at most 60. It only reads them."""
found: dict = {}
try:
for key, value in model.named_steps["model"].get_params().items():
if isinstance(value, np.generic):
value = value.item()
if isinstance(value, float) and not math.isfinite(value):
value = str(value)
if value is None or isinstance(value, (bool, int, float)):
found[key] = value
elif isinstance(value, str) or ("__" not in key and hasattr(value, "get_params")):
found[key] = str(value)[:120]
if len(found) == 60:
break
except Exception: # logging never stops the script
pass
return found
def predict(path: str, csv_path: str) -> None:
"""Print a prediction for every row of a CSV file.
If both the saved model and the file have a header line, the feature columns are found
by their names; otherwise they have to come first. Other columns (such as the target)
are ignored. The pipeline standardises the features like the training data.
"""
bundle = joblib.load(path) # a pickle: only load files you trust
model, columns = bundle["model"], bundle["columns"]
header, rows = read_csv(csv_path)
if columns and header:
missing = [name for name in columns if name not in header]
if missing:
raise SystemExit(f"{csv_path} lacks the columns {', '.join(missing)}.")
rows = [[row[header.index(name)] for name in columns] for row in rows]
elif all(len(row) >= NUM_FEATURES for row in rows):
rows = [row[:NUM_FEATURES] for row in rows]
else:
raise SystemExit(f"Expected {NUM_FEATURES} feature columns.")
features = numbers(rows, csv_path)
print(bundle["target"])
for value in model.predict(features):
print(f"{value:.6g}")
def demo(model: Pipeline) -> None:
"""Fit the model to 40 random rows and predict two of them (shows that it works)."""
rng = np.random.default_rng(0)
features = rng.normal(size=(40, NUM_FEATURES))
target = features[:, 0] + np.sin(2 * features[:, -1])
model.fit(features, target)
print("Predictions for 2 random rows:", model.predict(features[:2]))
# --------------------------------------------------------------------------- #
# Logging to Brick DNN, only with the environment variable BRICKDNN_TOKEN
# --------------------------------------------------------------------------- #
# The server and the saved network the runs belong to (BRICKDNN_URL and BRICKDNN_PROJECT
# override them). The token is never stored here: it is read from BRICKDNN_TOKEN.
BRICKDNN_URL = "https://brickdnn.com"
BRICKDNN_PROJECT = None
class BrickDNNRun:
"""A run logged to Brick DNN (see brickdnn/tracking.py), or an inert one without the
environment variable BRICKDNN_TOKEN."""
# Points are sent in batches: when this many are waiting, or after INTERVAL seconds.
BATCH = 200
INTERVAL = 2.0
# Points kept while the server cannot be reached; failures in a row before giving up.
BUFFER = 1000
ATTEMPTS = 3
RETRY_SECONDS = 10.0
TIMEOUT = 5.0
def __init__(self, url: str | None = None, token: str | None = None) -> None:
url = os.environ.get("BRICKDNN_URL") or url or "https://brickdnn.com"
self.url = url.strip().rstrip("/")
self.token = (token if token is not None else os.environ.get("BRICKDNN_TOKEN", "")).strip()
self.id: str | None = None
self.active = bool(self.token)
self.points: list[dict] = []
self._create: dict = {}
self._started = time.monotonic()
self._sent = self._started # the first batch waits INTERVAL too
self._failures = 0
self._retry_at = 0.0
self._warned = False
@classmethod
def start(
cls,
name: str | None = None,
config: dict | None = None,
project: int | None = None,
dataset: str | None = None,
task: str | None = None,
epochs: int | None = None,
url: str | None = None,
token: str | None = None,
) -> BrickDNNRun:
"""Create the run on the server (nothing happens without a token)."""
run = cls(url, token)
if not run.active:
return run
if os.environ.get("BRICKDNN_PROJECT", "").strip().isdigit():
project = int(os.environ["BRICKDNN_PROJECT"].strip())
body = {
"name": os.environ.get("BRICKDNN_RUN_NAME") or name,
"config": config or {},
"project": project,
"dataset": dataset,
"task": task,
"epochs": epochs,
"client": "brickdnn-tracking/1",
}
run._create = {key: value for key, value in body.items() if value is not None}
run._open()
return run
def _open(self) -> bool:
"""Create the run on the server if that has not worked yet."""
if self.id is None and self.active and time.monotonic() >= self._retry_at:
answer = self._send("POST", "/api/tracking/runs/", self._create)
if isinstance(answer, dict) and isinstance(answer.get("id"), str):
self.id = answer["id"]
print(f"Brick DNN: logging this run to {self.url}/runs", file=sys.stderr)
return self.id is not None
def log(self, epoch: int | None = None, step: int | None = None, **metrics) -> None:
"""One point of the curves: ``epoch`` (or ``step``) and numbers such as
``train_loss``, ``val_loss`` or ``val_accuracy``; other values are left out."""
if not self.active:
return
try:
point: dict = {"time": round(time.monotonic() - self._started, 3)}
if epoch is not None:
point["epoch"] = int(epoch)
if step is not None:
point["step"] = int(step)
for key, value in metrics.items():
number = self._number(value)
if number is not None:
point[str(key)] = number
self.points.append(point)
del self.points[: max(0, len(self.points) - self.BUFFER)]
if len(self.points) >= self.BATCH or time.monotonic() - self._sent >= self.INTERVAL:
self.flush()
except Exception as error: # logging never stops the training
self._fail(error)
def flush(self) -> None:
"""Send the points that wait."""
if not self.active or not self.points or time.monotonic() < self._retry_at:
return
if not self._open():
return
while self.active and self.points:
batch = self.points[: self.BATCH]
if self._send("POST", f"/api/tracking/runs/{self.id}/log/", {"points": batch}) is None:
return
del self.points[: len(batch)]
self._sent = time.monotonic()
def finish(
self, status: str = "completed", summary: dict | None = None, message: str | None = None
) -> None:
"""End the run: ``completed``, ``failed`` or ``stopped``, with its final numbers
(e.g. ``{"test_accuracy": 0.93}``)."""
if not self.active:
return
try:
self._retry_at = 0.0
self.flush()
if self.active and self._open():
numbers = {str(k): self._number(v) for k, v in (summary or {}).items()}
body: dict = {
"status": status,
"summary": {k: v for k, v in numbers.items() if v is not None},
}
if message:
body["message"] = str(message)[:500]
self._send("POST", f"/api/tracking/runs/{self.id}/finish/", body)
except Exception as error:
self._fail(error)
self.active = False
def __enter__(self) -> BrickDNNRun:
return self
def __exit__(self, kind, error, traceback) -> bool:
if kind is None:
self.finish("completed")
elif issubclass(kind, KeyboardInterrupt):
self.finish("stopped", message="Stopped with Ctrl+C.")
else:
self.finish("failed", message=f"{kind.__name__}: {error}")
return False # an error goes on as before
@staticmethod
def _number(value) -> float | int | None:
try:
if hasattr(value, "item"):
value = value.item() # a tensor or a NumPy number
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
return value if math.isfinite(value) else None
except Exception:
return None
def _send(self, method: str, path: str, body: dict) -> dict | None:
"""The server's answer, or None if the request failed (warned once)."""
try:
request = urllib.request.Request(
self.url + path,
data=json.dumps(body).encode(),
method=method,
headers={
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
"User-Agent": "brickdnn-tracking/1",
},
)
with urllib.request.urlopen(request, timeout=self.TIMEOUT) as response:
answer = json.loads(response.read().decode() or "{}")
self._failures = 0
return answer if isinstance(answer, dict) else {}
except urllib.error.HTTPError as error:
# Busy or broken for a moment: again later. Refused (token, limit, the run was
# stopped in the app): for good.
self._fail(error, final=error.code not in (408, 429) and error.code < 500)
except Exception as error:
self._fail(error)
return None
def _fail(self, error: Exception, final: bool = False) -> None:
self._failures += 1
if not self._warned:
self._warned = True
detail = str(error)
if isinstance(error, urllib.error.HTTPError):
try:
detail = json.loads(error.read().decode()).get("detail") or detail
except Exception:
detail = f"HTTP {error.code}"
print(
f"Brick DNN: could not log to {self.url} ({detail}). The training goes on"
+ ("." if final else "; logging is tried again a few times."),
file=sys.stderr,
)
if final or self._failures >= self.ATTEMPTS:
self.active = False
self.points = []
else:
self._retry_at = time.monotonic() + self.RETRY_SECONDS
def main() -> None:
parser = argparse.ArgumentParser(description="Stacking regression, generated with Brick DNN")
parser.add_argument("--csv", help="fit the model to this CSV file (last column = target)")
parser.add_argument("--predict", metavar="CSV", help="predict the rows of this file")
parser.add_argument("--seed", type=int, default=0, help="for a repeatable split")
parser.add_argument(
"--save",
default="model.joblib",
help="the fitted model (--csv writes it, --predict reads it)",
)
args = parser.parse_args()
if args.predict:
predict(args.save, args.predict)
return
model = make_model()
print(model)
if args.csv:
header, features, target = load_csv(args.csv)
# Logged to Brick DNN only with the environment variable BRICKDNN_TOKEN.
with BrickDNNRun.start(
name="Stacking regression",
config={
"model": "StackingRegressor",
"seed": args.seed,
"val_split": 0.2,
"params": model_settings(model),
},
project=BRICKDNN_PROJECT,
dataset=os.path.basename(args.csv),
task="regression",
url=BRICKDNN_URL,
) as run:
fit(model, features, target, args.seed, run)
save_model(model, args.save, header)
return
demo(model)
if __name__ == "__main__":
main()