Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
350 changes: 350 additions & 0 deletions core/janus/forecast/gbdt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,350 @@
"""Gradient-boosted quantile regression, numpy only (#128).

A nonlinear baseline beside :class:`~janus.forecast.quantiles.EmpiricalQuantileModel`.
Each requested quantile gets its own additive model of shallow regression trees
fitted on the pinball-loss gradient, so the output is the same ``QuantileForecast``
every other quantile model returns.

Deliberately small and auditable: histogram split candidates, no randomness, no
sklearn / lightgbm / xgboost, and ``predict`` is a pure function of the fitted
state. The pinball loss has a zero second derivative almost everywhere, so the
Newton leaf ``sum(g) / sum(h)`` reduces to the mean gradient, which is what
``_build`` stores.
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from typing import Any, Sequence

import numpy as np

from .quantiles import QuantileForecast, _validate_probabilities


def _number(payload: dict[str, Any], field: str) -> float:
value = payload[field]
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(
f"model payload field {field!r} must be a number, got {type(value).__name__}"
)
if not math.isfinite(float(value)):
raise ValueError(f"model payload field {field!r} must be finite")
return float(value)


def _integer(payload: dict[str, Any], field: str) -> int:
value = payload[field]
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(
f"model payload field {field!r} must be an integer, got {type(value).__name__}"
)
return int(value)

@dataclass(frozen=True)
class _Tree:
"""One shallow regression tree; leaves carry a constant gradient mean."""

value: float
feature: int = -1
threshold: float = 0.0
left: "_Tree | None" = None
right: "_Tree | None" = None

def predict(self, rows: np.ndarray) -> np.ndarray:
if self.left is None or self.right is None:
return np.full(rows.shape[0], self.value)
mask = rows[:, self.feature] <= self.threshold
out = np.empty(rows.shape[0])
out[mask] = self.left.predict(rows[mask])
out[~mask] = self.right.predict(rows[~mask])
return out

def to_dict(self) -> dict[str, Any]:
if self.left is None or self.right is None:
return {"value": self.value}
return {
"value": self.value,
"feature": self.feature,
"threshold": self.threshold,
"left": self.left.to_dict(),
"right": self.right.to_dict(),
}

@classmethod
def from_dict(cls, payload: Any, *, n_features: int) -> "_Tree":
if not isinstance(payload, dict) or "value" not in payload:
raise ValueError("tree payload field 'value' is missing or not an object")
value = _number(payload, "value")
children = [key for key in ("left", "right") if key in payload]
if not children:
if "feature" in payload or "threshold" in payload:
raise ValueError("tree payload carries split fields but no children")
return cls(value)
if len(children) != 2:
raise ValueError("tree payload must carry both children or neither")
for key in ("feature", "threshold"):
if key not in payload:
raise ValueError(f"tree payload is missing {key!r}")
feature = _integer(payload, "feature")
if not 0 <= feature < n_features:
raise ValueError(
f"tree payload field 'feature' must be in [0, {n_features}), got {feature}"
)
return cls(
value,
feature,
_number(payload, "threshold"),
cls.from_dict(payload["left"], n_features=n_features),
cls.from_dict(payload["right"], n_features=n_features),
)


def _build(
x: np.ndarray,
residual: np.ndarray,
*,
depth: int,
max_depth: int,
min_samples_leaf: int,
n_bins: int,
) -> _Tree:
value = float(residual.mean())
if depth >= max_depth or residual.size < 2 * min_samples_leaf:
return _Tree(value=value)
best: tuple[float, int, float] | None = None
for feature in range(x.shape[1]):
column = x[:, feature]
cuts = np.unique(np.quantile(column, np.linspace(0.0, 1.0, n_bins + 1)[1:-1]))
for threshold in cuts:
mask = column <= threshold
left, right = residual[mask], residual[~mask]
if left.size < min_samples_leaf or right.size < min_samples_leaf:
continue
gain = left.size * (left.mean() - value) ** 2 + right.size * (
right.mean() - value
) ** 2
if best is None or gain > best[0]:
best = (float(gain), feature, float(threshold))
if best is None:
return _Tree(value=value)
_, feature, threshold = best
mask = x[:, feature] <= threshold
return _Tree(
value=value,
feature=feature,
threshold=threshold,
left=_build(
x[mask], residual[mask], depth=depth + 1, max_depth=max_depth,
min_samples_leaf=min_samples_leaf, n_bins=n_bins,
),
right=_build(
x[~mask], residual[~mask], depth=depth + 1, max_depth=max_depth,
min_samples_leaf=min_samples_leaf, n_bins=n_bins,
),
)


class GradientBoostedQuantileModel:
"""Per-quantile gradient boosting on the pinball loss.

Unlike :class:`~janus.forecast.quantiles.EmpiricalQuantileModel` this model
needs the feature rows at prediction time, so it matches the
``QuantileModel`` protocol in intent and return type rather than in call
signature: ``predict(x, *, horizon=1)`` returns the same
``QuantileForecast`` rows.

``seed`` is recorded in ``to_dict`` for provenance only; fitting draws no
random numbers, so two runs on the same data already replay exactly.
"""

def __init__(
self,
quantiles: Sequence[float] = (0.1, 0.5, 0.9),
*,
n_estimators: int = 50,
learning_rate: float = 0.1,
max_depth: int = 3,
min_samples_leaf: int = 5,
n_bins: int = 32,
seed: int = 0,
feature_names: Sequence[str] | None = None,
) -> None:
self.quantiles = _validate_probabilities(quantiles)
rules = {
"n_estimators": (n_estimators, int(n_estimators) >= 1, ">= 1"),
"learning_rate": (learning_rate, 0.0 < learning_rate <= 1.0, "in (0, 1]"),
"max_depth": (max_depth, int(max_depth) >= 1, ">= 1"),
"min_samples_leaf": (min_samples_leaf, int(min_samples_leaf) >= 1, ">= 1"),
"n_bins": (n_bins, int(n_bins) >= 2, ">= 2"),
}
for name, (value, ok, rule) in rules.items():
if not ok:
raise ValueError(f"{name} must be {rule}, got {value}")
self.n_estimators = int(n_estimators)
self.learning_rate = float(learning_rate)
self.max_depth = int(max_depth)
self.min_samples_leaf = int(min_samples_leaf)
self.n_bins = int(n_bins)
self.seed = int(seed)
self.feature_names = list(feature_names) if feature_names is not None else None
self.baselines_: list[float] | None = None
self.trees_: list[list[_Tree]] | None = None
self.n_features_in_: int | None = None
self.n_samples_: int = 0

def _matrix(self, x: Any, y: Sequence[float] | None = None) -> tuple[np.ndarray, np.ndarray | None]:
rows = np.asarray(x, dtype=float)
if rows.ndim != 2:
raise ValueError(f"X must be two-dimensional, got {rows.ndim} dimension(s)")
bad = np.argwhere(~np.isfinite(rows))
if bad.size:
row, column = int(bad[0][0]), int(bad[0][1])
label = (
self.feature_names[column]
if self.feature_names is not None and column < len(self.feature_names)
else f"column {column}"
)
raise ValueError(f"X has a non-finite value at row {row}, {label}")
if y is None:
return rows, None
target = np.asarray(list(y), dtype=float)
if target.ndim != 1:
raise ValueError("y must be one-dimensional")
if target.size != rows.shape[0]:
raise ValueError(f"X has {rows.shape[0]} rows but y has {target.size} values")
if not np.isfinite(target).all():
raise ValueError("y contains a non-finite value")
return rows, target

def fit(self, x: Any, y: Sequence[float]) -> "GradientBoostedQuantileModel":
rows, target = self._matrix(x, y)
assert target is not None
required = 2 * self.min_samples_leaf
if rows.shape[0] < required:
raise ValueError(
f"at least {required} samples are required "
f"(2 * min_samples_leaf), got {rows.shape[0]}"
)
self.n_features_in_ = rows.shape[1]
self.n_samples_ = int(rows.shape[0])
self.baselines_, self.trees_ = [], []
for probability in self.quantiles:
baseline = float(np.quantile(target, probability))
prediction = np.full(rows.shape[0], baseline)
forests: list[_Tree] = []
for _ in range(self.n_estimators):
gradient = np.where(target > prediction, probability, probability - 1.0)
tree = _build(
rows, gradient, depth=0, max_depth=self.max_depth,
min_samples_leaf=self.min_samples_leaf, n_bins=self.n_bins,
)
prediction = prediction + self.learning_rate * tree.predict(rows)
forests.append(tree)
self.baselines_.append(baseline)
self.trees_.append(forests)
return self

def _raw(self, rows: np.ndarray) -> np.ndarray:
assert self.trees_ is not None and self.baselines_ is not None
columns = []
for baseline, forests in zip(self.baselines_, self.trees_):
prediction = np.full(rows.shape[0], baseline)
for tree in forests:
prediction = prediction + self.learning_rate * tree.predict(rows)
columns.append(prediction)
# Non-crossing is a property of the output, not a hope.
return np.sort(np.column_stack(columns), axis=1)

def predict(self, x: Any, *, horizon: int = 1) -> list[QuantileForecast]:
if self.trees_ is None or self.baselines_ is None:
raise RuntimeError("model is not fitted")
if horizon < 1:
raise ValueError("horizon must be >= 1")
rows, _ = self._matrix(x)
if rows.shape[0] == 0:
raise ValueError("X must contain at least one row")
if self.n_features_in_ is not None and rows.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {rows.shape[1]} features but the model was fitted on "
f"{self.n_features_in_}"
)
values = self._raw(rows) * float(np.sqrt(horizon))
return [
QuantileForecast.from_values(
self.quantiles, row, observations=int(self.n_samples_)
)
for row in values
]

def to_dict(self) -> dict[str, Any]:
if self.trees_ is None or self.baselines_ is None:
raise RuntimeError("model is not fitted")
return {
"quantiles": list(self.quantiles),
"n_estimators": self.n_estimators,
"learning_rate": self.learning_rate,
"max_depth": self.max_depth,
"min_samples_leaf": self.min_samples_leaf,
"n_bins": self.n_bins,
"seed": self.seed,
"feature_names": self.feature_names,
"n_samples": self.n_samples_,
"n_features": self.n_features_in_,
"baselines": list(self.baselines_),
"trees": [[tree.to_dict() for tree in forests] for forests in self.trees_],
}

@classmethod
def from_dict(cls, payload: Any) -> "GradientBoostedQuantileModel":
if not isinstance(payload, dict):
raise ValueError("model payload must be an object")
required = (
"quantiles", "n_estimators", "learning_rate", "max_depth",
"min_samples_leaf", "n_bins", "seed", "n_samples", "n_features",
"baselines", "trees",
)
for field in required:
if field not in payload:
raise ValueError(f"model payload is missing {field!r}")
model = cls(
payload["quantiles"],
n_estimators=_integer(payload, "n_estimators"),
learning_rate=_number(payload, "learning_rate"),
max_depth=_integer(payload, "max_depth"),
min_samples_leaf=_integer(payload, "min_samples_leaf"),
n_bins=_integer(payload, "n_bins"),
seed=_integer(payload, "seed"),
feature_names=payload.get("feature_names"),
)
n_features = _integer(payload, "n_features")
if n_features < 1:
raise ValueError(
f"model payload field 'n_features' must be >= 1, got {n_features}"
)
baselines = payload["baselines"]
if not isinstance(baselines, list) or len(baselines) != len(model.quantiles):
raise ValueError(
"model payload field 'baselines' needs one value per quantile"
)
model.baselines_ = [
_number({"baseline": value}, "baseline") for value in baselines
]
trees = payload["trees"]
if not isinstance(trees, list) or len(trees) != len(model.quantiles):
raise ValueError("model payload field 'trees' needs one forest per quantile")
forests: list[list[_Tree]] = []
for index, forest in enumerate(trees):
if not isinstance(forest, list) or len(forest) != model.n_estimators:
raise ValueError(
f"model payload field 'trees[{index}]' needs "
f"{model.n_estimators} trees"
)
forests.append(
[_Tree.from_dict(node, n_features=n_features) for node in forest]
)
model.trees_ = forests
model.n_samples_ = _integer(payload, "n_samples")
model.n_features_in_ = n_features
return model
Loading