Examples · scikit-learn

Periodic Gaussian process for seasonal data

A Gaussian process for a value over time that repeats with the seasons and drifts slowly: its kernel adds a periodic part, a smooth trend and noise, each a brick on the canvas.

Open in the editor See the code

Code
scikit-learn
Task
Regression
Input
1
Bricks
8
Model
GaussianProcessRegressor

What the network does

The Input is one feature, the time. ExpSineSquared is a periodic kernel: points one period apart count as similar. Multiplied by an RBF with a long length scale (10), the seasonal pattern may change slowly from year to year. A second RBF with length scale 5 models the trend, and WhiteKernel the noise. KernelSum adds the three parts.

Fitting tunes all five hyperparameters, including the periodicity. Set its starting value to the season length in standardised units of the time feature, because the pipeline standardises the features first.

When to use it

  • For seasonal measurements with few points: monthly sales, temperatures, energy use, sensor readings with a daily cycle.
  • When you want the uncertainty of a forecast to grow the further it reaches from the data.
  • To learn how composite kernels describe structure: remove the trend brick and see what the fit makes of the data.

Layers, shapes and parameters

Diagram of the example Periodic Gaussian processInput (1) → RBF (kernel) → ExpSineSquared (kernel) → KernelProduct (kernel) → RBF (kernel) → WhiteKernel (kernel) → KernelSum (kernel) → GaussianProcessRegressor (1)Input1RBFkernel1 hyperparameterExpSineSquaredkernel2 hyperparametersKernelProductkernelRBFkernel1 hyperparameterWhiteKernelkernel1 hyperparameterKernelSumkernelGaussianProcessRegressor1
The network as it is laid out in the editor. Each box shows the output shape (without the batch dimension) and the number of parameters.
The bricks of Periodic Gaussian process: settings, output shape and parameters, computed by Brick DNN's shape inference
BrickTypeSettingsOutputParameters
timeInputshape=110
decayRBFlength_scale=10kernel1 hyperparameter
seasonExpSineSquaredlength_scale=1 periodicity=1kernel2 hyperparameters
seasonalKernelProductdefaultskernel0
trendRBFlength_scale=5kernel1 hyperparameter
noiseWhiteKernelnoise_level=0.1kernel1 hyperparameter
kernelKernelSumdefaultskernel0
gpGaussianProcessRegressornormalize_y=true10
Total5 hyperparameters

Training it in Brick DNN

Use a CSV file with the time as a number (for example days since the first measurement) as the only feature column and the measured value as the target (last column). The run shows the fitted kernel with all its hyperparameters and the log marginal likelihood.

The generated code

This is the scikit-learn script that the editor’s code dialog generates from the graph above (periodic_gp.py). It runs on its own: python periodic_gp.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
"""Gaussian process regression: generated with Brick DNN.

A scikit-learn model for 1 numeric feature: they are standardised, then
GaussianProcessRegressor predicts one number per row.

Kernel (the starting point; fitting optimises its hyperparameters):
    RBF(length_scale=10.0) * ExpSineSquared(length_scale=1.0, periodicity=1.0)
    + RBF(length_scale=5.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.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ExpSineSquared, WhiteKernel
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

NUM_FEATURES = 1


def make_model() -> Pipeline:
    """Standardise the features (with the mean and standard deviation of the data
    it is fitted to), then fit GaussianProcessRegressor."""
    rbf_1 = RBF(length_scale=10.0)
    periodic = ExpSineSquared(length_scale=1.0, periodicity=1.0)
    rbf_2 = RBF(length_scale=5.0)
    white = WhiteKernel(noise_level=0.1)
    kernel = rbf_1 * periodic + rbf_2 + white
    model = GaussianProcessRegressor(kernel=kernel, alpha=1e-10, normalize_y=True)
    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}")
    gp = model.named_steps["model"]
    print(f"Learned kernel: {gp.kernel_}")
    print(f"Log marginal likelihood: {gp.log_marginal_likelihood_value_:.4g}")
    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)
    # The Gaussian process also says how uncertain it is: one standard deviation.
    mean, std = model.predict(features, return_std=True)
    print(f"{bundle['target']},std")
    for value, spread in zip(mean, std):
        print(f"{value:.6g},{spread:.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="Gaussian process 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="Gaussian process regression",
            config={
                "model": "GaussianProcessRegressor",
                "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()

Open in the editor