Distributional (Location-Scale): Thin Delegation

Navigation:

Implementation only, for the two-stage schedule and quantile formulas see the math theory.

There is no DistributionalTAM class: a dict formula makes StaticTAM a thin frontend that delegates the whole schedule to statistics/estimation/_distributional.py. Sub-models are built with type(model)(...), so the module never imports StaticTAM (no circular import).

The schedule (location, then scale on the residuals)

def fit(model, data: pd.DataFrame, select: str = "fixed",
        cv_alpha_grid: Sequence[float] = (-6.0, -4.0, -2.0, 0.0), cv_fraction: float = 0.3):
    """Fit the location, then the scale on its squared residuals, then the tail family.

    select chooses the location smoothing: 'fixed' uses location_alpha_p; 'gcv' runs auto_fit
    (exact for the location); 'cv' picks it from cv_alpha_grid by held-out error. The scale
    smoothing stays fixed (Gaussian GCV is invalid for the Gamma GLM).
    """
    working = data.copy()
    require_positive_target(model, working[model.target_col_].to_numpy())
    fit_target_transform(model, working[model.target_col_].to_numpy())
    working["__mu__"] = _to_model_scale(model, working[model.target_col_].to_numpy())

    location_alpha = model._location_alpha_p_ if model._location_alpha_p_ is not None else model.default_alpha_p_
    if select == "gcv":
        model._location_submodel_ = _build_location_submodel(model, location_alpha)
        try:
            model._location_submodel_.auto_fit(working)
        except Exception:
            model._location_submodel_.fit(working)
    elif select == "cv":
        location_alpha = _select_location_alpha_by_cv(model, working, cv_alpha_grid, cv_fraction)
        model._location_submodel_ = _build_location_submodel(model, location_alpha).fit(working)
    else:
        model._location_submodel_ = _build_location_submodel(model, location_alpha).fit(working)

    model.refit_history_, model.n_refits_, model.converged_ = [], 0, True
    mu_hat, residual, clamped = _fit_scale(model, working)

    for round_index in range(1, model._refit_rounds_ + 1):
        # Efficient location: the weights are the inverse conditional variance of the scale model just fitted.
        weights, clipped = _inverse_variance_weights(_unshrunk_variance(model, working))
        working["__w__"] = weights
        location = model._location_submodel_
        location._weight_col_ = "__w__"
        location.fit(working)
        mu_new, residual, clamped = _fit_scale(model, working)
        change = float(np.linalg.norm(mu_new - mu_hat) / max(np.linalg.norm(mu_hat), _TINY))
        mu_hat = mu_new
        model.refit_history_.append({
            "round": round_index, "change": change, "log_likelihood": _log_likelihood(model, working, residual),
            "clipped_weights": clipped, "clamped_leverages": clamped,
        })
        model.n_refits_ = round_index
        if change < model._refit_tol_:
            break
    if model._refit_rounds_ > 0:
        model.converged_ = bool(model.refit_history_[-1]["change"] < model._refit_tol_)
        if not model.converged_:
            warnings.warn(
                f"The weighted refit of the location did not converge in {model.n_refits_} round(s): the fitted location still moved by "
                f"{model.refit_history_[-1]['change']:.2e} (refit_tol={model._refit_tol_:g}). The last round is kept.",
                UserWarning, stacklevel=3,
            )

    _, sigma_hat = mu_sigma(model, working)
    fit_tail_family(model, residual / sigma_hat)
    model.log_likelihood_ = _log_likelihood(model, working, residual)
    return model

Weighted refit of the location and debiased scale

dist_kwargs takes three more options, defaults of which reproduce the fit above bit for bit: refit_rounds (0), refit_tol (1e-4) and scale_correction ("none", "leverage", "edf").

  • Weights. A plain StaticTAM has a private attribute _weight_col_; when it names a column of the training frame, BaseTAM.fit stacks that column exactly like the target (_stacked_column: same balancing, groups and order), checks it (finite, non-negative, not all zero) and passes it to the penalized least-squares atom (_solve_prepared(..., weights)). predict ignores it.

  • Loop. After the first location and scale fits, each round computes the unshrunk conditional variance of the scale model, turns its inverse into weights (normalised to unit mean so that the n P penalty keeps its scale, then kept within a factor 1e3 of the median: _inverse_variance_weights), refits the same location sub-model with them (its penalties and knots are kept: the smoothing chosen by select on the first pass is not re-chosen), and refits the scale on the new residuals. It stops when the relative change of the fitted location is below refit_tol; if the cap refit_rounds is reached first, a UserWarning gives the last change and the last round is kept.

  • Leverage. StaticTAM.leverage(data) returns h_ii for every row (one batched solve per group, with the same penalty and ridge floor as the fit and the weights of the fit). scale_correction="leverage" divides the squared residuals by 1 - min(h, 0.9), "edf" multiplies them per group by n / (n - sum h) (_corrected_squared_residual); _global_scale_variance_ is the mean of the corrected values. It works with refit_rounds=0. A warning is given once when more than 1% of the leverages hit the clamp.

  • Record. refit_history_ (one dict per round: round, change, log_likelihood, clipped_weights, clamped_leverages), n_refits_, converged_ and log_likelihood_, the log-likelihood of the training rows at the final location, scale and tail law.

def _corrected_squared_residual(model, working: pd.DataFrame, residual: np.ndarray) -> Tuple[np.ndarray, int]:
    """Squared residuals of the location fit, debiased for its leverage: ``r^2 / (1 - h)`` (``"leverage"``) or ``r^2 n / (n - edf)`` per
    group (``"edf"``); returns them and the number of leverages that hit the clamp."""
    squared = np.clip(residual ** 2, _TINY, None)
    if model._scale_correction_ == "none":
        return squared, 0
    leverage = model._location_submodel_.leverage(working)
    clamped = int(np.count_nonzero(leverage > _LEVERAGE_MAX))
    if model._scale_correction_ == "leverage":
        return squared / (1.0 - np.clip(leverage, 0.0, _LEVERAGE_MAX)), clamped
    group_col = model._sub_group_col_
    if group_col is not None and group_col in working.columns:
        keys = working[group_col].to_numpy()
    else:
        keys = np.zeros(len(working))
    factor = np.ones(len(working))
    for key in np.unique(keys):
        rows = keys == key
        n_rows = int(rows.sum())
        factor[rows] = n_rows / max(n_rows - float(leverage[rows].sum()), 0.1 * n_rows)
    return squared * factor, clamped
def _inverse_variance_weights(variance: np.ndarray) -> Tuple[np.ndarray, int]:
    """``1 / variance`` normalised to unit mean (the penalty keeps its scale), then kept within 1e3 of the median; returns them and the
    number of clipped weights."""
    raw = 1.0 / np.clip(variance, _TINY, None)
    weights = raw / np.mean(raw)
    median = float(np.median(weights))
    clipped = np.clip(weights, median / _WEIGHT_RANGE, median * _WEIGHT_RANGE)
    return clipped / np.mean(clipped), int(np.count_nonzero(clipped != weights))

The tail law and the location/scale predictions

def select_tail_family(
    standardized_residual: np.ndarray,
    tail_family: str,
    kurtosis_threshold: float,
) -> Tuple[str, Optional[float]]:
    """Choose the standardized-residual law by excess kurtosis.

    'normal' / 'student_t' force the family; 'auto' picks Student-t only when the excess kurtosis
    exceeds kurtosis_threshold, fitting nu from it. Returns (family, nu); nu is None for the Normal.
    """
    centred = standardized_residual - standardized_residual.mean()
    variance = np.mean(centred ** 2)
    excess_kurtosis = float(np.mean(centred ** 4) / max(variance ** 2, _TINY) - 3.0)
    if tail_family == "normal":
        return "normal", None
    if tail_family == "student_t":
        return "student_t", float(np.clip(4.0 + 6.0 / max(excess_kurtosis, 1e-3), 3.0, 60.0))
    # "auto"
    if excess_kurtosis <= kurtosis_threshold:
        return "normal", None
    return "student_t", float(np.clip(4.0 + 6.0 / excess_kurtosis, 3.0, 60.0))
def mu_sigma(model, data: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
    """Return the location mu_hat (model scale) and scale sigma_hat for each row of data."""
    mu_hat = _estimated(model._location_submodel_.predict(data), "__mu__")
    scale_prediction = _estimated(model._scale_submodel_.predict(data), "__sigma__")
    if model._scale_loss_ == "gamma":
        conditional_variance = np.clip(scale_prediction, _TINY, None)
    else:
        conditional_variance = np.exp(scale_prediction - _LOG_CHI2_1_MEAN)
    if model.scale_shrinkage > 0.0 and model._global_scale_variance_ is not None:
        conditional_variance = (
            model.scale_shrinkage * model._global_scale_variance_
            + (1.0 - model.scale_shrinkage) * conditional_variance
        )
    return mu_hat, np.clip(np.sqrt(conditional_variance), _TINY, None)

For a log target the quantile and the median are exp of a model-scale value. A value beyond the float64 range (a location or scale prediction far outside the training range) is returned as inf with an explicit UserWarning naming the quantity and the first rows, never numpy’s silent overflow warning:

def _to_response_scale(model_scale: np.ndarray, quantity: str) -> np.ndarray:
    """exp() of a model-scale value for a log target; a value beyond float64 is inf, with an explicit warning (not numpy's)."""
    with np.errstate(over="ignore"):
        response = np.exp(model_scale)
    overflowed = np.flatnonzero(np.isposinf(response) & (model_scale > 0))
    if overflowed.size:
        warnings.warn(
            f"exp overflow in {quantity}: {overflowed.size} row(s) exceed the float64 range on the response scale "
            f"and are returned as inf (first rows: {overflowed[:5].tolist()}). The location or scale prediction is "
            f"far outside the training range there.",
            UserWarning, stacklevel=3,
        )
    return response

The log target is the default (dist_kwargs={"log_target": True}). fit first checks the training target: a value <= 0 has no logarithm, and clipping it to a tiny constant would turn it into a huge negative outlier, so the fit raises a ValueError naming the count and the option log_target=False instead. The mixture mode (_mixture.py) runs the same check. Only the training target is checked: the CDF of a new observation <= 0 under a log-scale law is ~0, a valid answer.

def require_positive_target(model, y: np.ndarray) -> None:
    """Reject a training target with values <= 0 when the model works on log(y).

    Args:
        model: A distributional or mixture StaticTAM.
        y: The training target.

    Raises:
        ValueError: If ``log_target`` is on and some finite values are <= 0 (they would be clipped to a tiny constant
            before the log, i.e. turned into huge negative outliers).
    """
    if not model._log_target_:
        return
    values = np.asarray(y, dtype=float)
    finite = values[np.isfinite(values)]
    n_bad = int(np.count_nonzero(finite <= 0))
    if n_bad:
        raise ValueError(
            f"{n_bad} of {finite.size} training target values are <= 0, but the model works on log(y) "
            "(the default for a distributional or mixture StaticTAM). Pass dist_kwargs={'log_target': False} "
            "to model the target on its own scale, or shift it to positive values."
        )

Target transform. dist_kwargs={"target_transform": ...} takes "none", "log" (the default, same as log_target=True), "log1p", "asinh", "logit" or "boxcox"; giving it together with a contradicting log_target raises a ValueError, and a mixture accepts "none" and "log" only. The maps themselves (estimate_params, forward, inverse, inverse_mean) live in statistics/estimation/_target_transform.py, one code path for the distributional and the plain model. resolve_target_transform reads the options once, in the constructor:

def resolve_target_transform(dist_kwargs: dict, mixture: bool = False) -> Tuple[str, bool, Optional[Tuple[float, float]]]:
    """Read ``target_transform``, ``log_target`` and ``bounds`` of ``dist_kwargs``.

    Args:
        dist_kwargs: The ``dist_kwargs`` of the model.
        mixture: Whether the model is a mixture (only ``"none"`` and ``"log"`` are available there).

    Returns:
        ``(transform, log_target, bounds)``: the transform name, ``transform == "log"``, and the given bounds or None.

    Raises:
        ValueError: On an unknown transform, a contradiction with ``log_target``, invalid ``bounds``, or a mixture with
            ``"asinh"`` or ``"logit"``.
    """
    transform = dist_kwargs.get("target_transform")
    if transform is None:
        transform = "log" if bool(dist_kwargs.get("log_target", True)) else "none"
    elif transform not in _TRANSFORMS:
        raise ValueError(f"target_transform must be one of {_TRANSFORMS}; got {transform!r}")
    elif "log_target" in dist_kwargs and bool(dist_kwargs["log_target"]) != (transform == "log"):
        raise ValueError(
            f"dist_kwargs target_transform={transform!r} contradicts log_target={dist_kwargs['log_target']!r}; give one of them."
        )
    if mixture and transform not in ("none", "log"):
        raise ValueError(f"target_transform={transform!r} is not available for a mixture; use 'log' or 'none'.")
    bounds = dist_kwargs.get("bounds")
    if bounds is not None:
        if transform != "logit":
            raise ValueError("bounds applies to target_transform='logit' only.")
        low, high = float(bounds[0]), float(bounds[1])
        if not low < high:
            raise ValueError(f"bounds must be (low, high) with low < high; got {bounds!r}")
        bounds = (low, high)
    return transform, transform == "log", bounds

fit estimates the parameters of the transform on the training target and stores them in _transform_params_: for "asinh" the median and a robust scale (normalised MAD, else the standard deviation); for "logit" the bounds, from dist_kwargs={"bounds": (low, high)} or the observed range widened by 5% on each side, and a training value outside given bounds raises a ValueError.

def fit_target_transform(model, y: np.ndarray) -> None:
    """Estimate and store the parameters of the target transform on the training target.

    ``"asinh"`` stores the median and a robust scale (normalised MAD, else the standard deviation, else 1); ``"logit"`` stores
    the bounds (given, or the observed range widened by a margin); ``"log1p"`` and ``"boxcox"`` check their domain (the Box-Cox
    exponent is estimated by maximum likelihood).

    Args:
        model: A distributional StaticTAM.
        y: The training target.

    Raises:
        ValueError: If a ``"logit"`` target has values outside the given bounds, or a ``"log1p"`` / ``"boxcox"`` target is outside its domain.
    """
    transform = model._target_transform_
    if transform == "logit":
        kwargs = {"bounds": model._transform_bounds_} if model._transform_bounds_ is not None else {}
    else:
        kwargs = {}
    # the log keeps its own check (require_positive_target) and its parameter-free form
    model._transform_params_ = {} if transform in ("none", "log") else _tt.estimate_params(transform, y, kwargs)

The forward map is applied to the target everywhere it is read (fit, CDF, CRPS, anomaly score), and from_model_scale is the single back-transform used by predict_median, predict_quantile and anomaly_score, and by the studentized conformal intervals through the model method _from_model_scale:

def from_model_scale(model, z: np.ndarray, quantity: str = "the back-transformed values") -> np.ndarray:
    """Back-transform model-scale values to the response scale (exact for a monotone transform, quantiles included).

    Args:
        model: A distributional StaticTAM.
        z: Values on the model scale.
        quantity: Name used in the overflow warning of the log transform.

    Returns:
        The values on the response scale.
    """
    values = np.asarray(z, dtype=float)
    transform = model._target_transform_
    if transform == "log":
        return _to_response_scale(values, quantity)
    return _tt.inverse(transform, model._transform_params_, values)

The additive.py bridge (one-line delegates)

    def predict_quantiles(self, data: pd.DataFrame, taus: Sequence[float] = (0.05, 0.5, 0.95)) -> pd.DataFrame:
        """Quantiles on the response scale: of the location-scale law (distributional mode), or of the fitted law of a
        ``poisson``, ``negative_binomial`` or ``tweedie`` loss (discrete quantiles for the counts, the compound Poisson-gamma
        law for Tweedie; non-negative by construction)."""
        strategy = getattr(self, "_reweighting_strategy_", None)
        if getattr(self, "_mode_", "plain") != "distributional" and hasattr(strategy, "quantiles"):
            return predict_count_quantiles(self, data, taus)
        if self._transform_active():
            levels = list(taus)
            offsets = np.interp(levels, self._plain_residual_levels_, self._plain_residual_values_)
            z_hat = self._model_scale_prediction(data)
            quantiles = {f"q{level}": _tt.inverse(self._plain_transform_, self._plain_params_, z_hat + offset)
                         for level, offset in zip(levels, offsets)}
            return pd.DataFrame(quantiles, index=data.index)
        return _distributional.predict_quantiles(self, data, taus)

Target transform of a plain model

StaticTAM(formula, target_transform="log", transform_kwargs={...}) applies the same maps without a scale law. fit, auto_fit and grid_search_fit fit the model on a copy of the frame whose target is \(g(y)\) (_transformed_frame; the parameters of \(g\) are estimated on the training frame only), then store the model-scale residual variance and a 20 001-point quantile function of the residuals (_finish_transform_fit). predict returns \(g^{-1}(\hat t)\) (or the second-order mean with transform_kwargs={"mean_correction": True}), and predict_quantiles returns \(g^{-1}(\hat t+\hat F_e^{-1}(\tau))\) as columns q<tau>. A GLM loss refuses a transform (its link is one already), as do a dict formula and a mixture, which take dist_kwargs. Lag columns that hold past values of the target are built by the caller and are not transformed. decompose_prediction stays on the model scale, calibrate_conformal works on the response scale.