Reweighted Estimation: Strategy Pattern & IRLS Driver¶
Navigation:
Theory introduction: See the Intro
Related mathematical theory: Reweighted estimation
Implementation only, for the working-response/weight formulas see the math theory.
The estimation/ package mirrors spectrum/: a base contract, one file per loss family, and a registry.
The GLM families¶
class GLMFamily(ReweightingStrategy):
"""A GLM defined by a link, a variance V(mu) and a unit deviance."""
is_glm = True
def __init__(
self,
link: Link,
variance: Callable[[torch.Tensor], torch.Tensor],
unit_deviance: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
name: str,
):
self.link = link
self.variance = variance
self.unit_deviance = unit_deviance
self.name = name
def initial_eta(self, y: torch.Tensor) -> torch.Tensor:
return self.link.link(self.link.starting_mu(y))
def inverse_link(self, eta: torch.Tensor) -> torch.Tensor:
return self.link.inverse(eta)
def working_response_and_weights(self, y, eta):
mu = self.link.inverse(eta)
g_prime = self.link.deriv(mu)
working_response = eta + (y - mu) * g_prime
weights = 1.0 / (g_prime * g_prime * self.variance(mu)).clamp_min(_TINY)
return working_response, weights
def mean_objective(self, y, eta):
mu = self.link.inverse(eta)
return self.unit_deviance(y, mu).mean()
Negative binomial and Tweedie¶
negative_binomial and tweedie are GLMFamily subclasses in _count_families.py, registered in build_strategy (StaticTAM(..., loss="negative_binomial", loss_kwargs={"dispersion": 0.5}) fixes the dispersion, loss_kwargs={"power": 1.3} sets the Tweedie power). The negative binomial variance reads the current dispersion, so the same IRLS loop serves any value of it:
class NegativeBinomialFamily(GLMFamily):
"""Negative binomial (NB2) with log link: variance ``mu + alpha mu^2``, ``alpha = 1 / theta`` estimated by maximum likelihood."""
def __init__(self, dispersion: Optional[float] = None):
if dispersion is not None and not float(dispersion) > 0.0:
raise ValueError(f"dispersion must be > 0; got {dispersion!r}")
self.fixed_dispersion = None if dispersion is None else float(dispersion)
self.dispersion = self.fixed_dispersion if dispersion is not None else 0.1
super().__init__(LogLink(), self._variance, self._unit_deviance, "negative_binomial")
def _variance(self, mu: torch.Tensor) -> torch.Tensor:
return mu + self.dispersion * mu * mu
def _unit_deviance(self, y: torch.Tensor, mu: torch.Tensor) -> torch.Tensor:
alpha = self.dispersion
y_pos, mu_pos = y.clamp_min(_TINY), mu.clamp_min(_TINY)
return 2.0 * (y * torch.log(y_pos / mu_pos) - (y + 1.0 / alpha) * torch.log((1.0 + alpha * y) / (1.0 + alpha * mu_pos)))
def validate_target(self, y: torch.Tensor) -> None:
_check_non_negative(y, "negative binomial")
def estimate_dispersion(self, y: torch.Tensor, mu: torch.Tensor) -> bool:
"""Maximum-likelihood ``alpha`` given the fitted means; returns whether it moved enough to refit the mean."""
if self.fixed_dispersion is not None:
return False
observed = y.detach().cpu().numpy().ravel().astype(float)
mean = np.clip(mu.detach().cpu().numpy().ravel().astype(float), _TINY, None)
def negative_log_likelihood(log_theta: float) -> float:
theta = np.exp(log_theta)
return -float(np.sum(
special.gammaln(observed + theta) - special.gammaln(theta)
+ theta * np.log(theta / (theta + mean)) + observed * np.log(mean / (theta + mean))
))
best = optimize.minimize_scalar(negative_log_likelihood, bounds=(-8.0, 12.0), method="bounded", options={"xatol": 1e-6})
updated = float(np.exp(-best.x))
moved = abs(updated - self.dispersion) / self.dispersion > _DISPERSION_TOL
self.dispersion = updated
return bool(moved)
def quantiles(self, mu: np.ndarray, taus: Sequence[float]) -> np.ndarray:
"""Discrete quantiles (smallest ``k`` with ``F(k) >= tau``), shape ``(len(mu), len(taus))``."""
theta = 1.0 / self.dispersion
mean = np.clip(np.asarray(mu, dtype=float), _TINY, None)
return np.stack([stats.nbinom.ppf(tau, theta, theta / (theta + mean)) for tau in _check_levels(taus)], axis=1)
After the first fit, BaseTAM.fit asks a family that has estimate_dispersion for the dispersion at the fitted means and, if it moved by more than 0.1%, refits the means with the new variance (at most ten rounds). The Tweedie dispersion does not enter the weights, so its estimate returns without a refit. validate_target rejects a negative target before the fit. The estimate is exposed as StaticTAM.dispersion_ (None for the other losses).
The Tweedie family computes the compound Poisson-gamma distribution function with the Poisson jump probabilities up to a tail of 1e-10, and its quantiles by bisection on that function (cost proportional to rows times jumps times 45 steps; a quantile below the mass at zero is exactly 0):
class TweedieFamily(GLMFamily):
"""Tweedie with power ``1 < p < 2`` and log link: variance ``phi mu^p``, a point mass at zero and a positive continuous part.
It is the compound Poisson-gamma law: ``N ~ Poisson(lambda)`` jumps, each ``Gamma(a, b)``, with
``lambda = mu^(2-p) / (phi (2-p))``, ``a = (2-p) / (p-1)`` and ``b = phi (p-1) mu^(p-1)``. ``phi`` is estimated from the Pearson
residuals (it does not change the weights, so no refit).
"""
def __init__(self, power: float = 1.5):
if not 1.0 < float(power) < 2.0:
raise ValueError(f"The Tweedie power must lie in (1, 2) (compound Poisson-gamma); got {power!r}")
self.power = float(power)
self.dispersion = 1.0
super().__init__(LogLink(), lambda mu: mu.clamp_min(_TINY) ** self.power, self._unit_deviance, "tweedie")
def _unit_deviance(self, y: torch.Tensor, mu: torch.Tensor) -> torch.Tensor:
p = self.power
y_pos, mu_pos = y.clamp_min(0.0), mu.clamp_min(_TINY)
return 2.0 * (y_pos ** (2.0 - p) / ((1.0 - p) * (2.0 - p)) - y * mu_pos ** (1.0 - p) / (1.0 - p) + mu_pos ** (2.0 - p) / (2.0 - p))
def validate_target(self, y: torch.Tensor) -> None:
_check_non_negative(y, "Tweedie")
def estimate_dispersion(self, y: torch.Tensor, mu: torch.Tensor) -> bool:
"""Pearson estimate of ``phi``; the mean is not refitted (a constant factor of the weights)."""
observed = y.detach().cpu().numpy().ravel().astype(float)
mean = np.clip(mu.detach().cpu().numpy().ravel().astype(float), _TINY, None)
self.dispersion = float(max(np.mean((observed - mean) ** 2 / mean ** self.power), _TINY))
return False
def _jump_parameters(self, mu: np.ndarray):
p, phi = self.power, self.dispersion
rate = mu ** (2.0 - p) / (phi * (2.0 - p))
shape = (2.0 - p) / (p - 1.0)
scale = phi * (p - 1.0) * mu ** (p - 1.0)
return rate, shape, scale
def probability_of_zero(self, mu: np.ndarray) -> np.ndarray:
"""``P(y = 0) = exp(-lambda)``."""
rate, _, _ = self._jump_parameters(np.clip(np.asarray(mu, dtype=float), _TINY, None))
return np.exp(-rate)
def cdf(self, y: np.ndarray, mu: np.ndarray) -> np.ndarray:
"""``F(y) = P(0) + sum_n P(N = n) GammaCDF(y; n a, b)`` for ``y >= 0``, summed over the jumps that carry mass."""
mu = np.clip(np.asarray(mu, dtype=float), _TINY, None)
y = np.asarray(y, dtype=float)
rate, shape, scale = self._jump_parameters(mu)
top = int(min(max(float(np.max(stats.poisson.ppf(1.0 - _JUMP_TAIL, rate))), 1.0) + 1.0, _MAX_JUMPS))
jumps = np.arange(1, top + 1)[None, :]
weight = stats.poisson.pmf(jumps, rate[:, None])
mass = special.gammainc(jumps * shape, np.maximum(y, 0.0)[:, None] / scale[:, None])
return np.where(y < 0.0, 0.0, np.exp(-rate) + np.sum(weight * mass, axis=1))
def quantiles(self, mu: np.ndarray, taus: Sequence[float]) -> np.ndarray:
"""Quantiles of the compound Poisson-gamma law by bisection on the CDF; ``0`` where ``tau <= P(y = 0)``."""
mu = np.clip(np.asarray(mu, dtype=float), _TINY, None)
levels = _check_levels(taus)
zero = self.probability_of_zero(mu)
out = np.zeros((len(mu), len(levels)))
spread = np.sqrt(self.dispersion * mu ** self.power)
for column, tau in enumerate(levels):
rows = np.flatnonzero(tau > zero)
for start in range(0, len(rows), _CHUNK):
chunk = rows[start:start + _CHUNK]
low, high = np.zeros(len(chunk)), mu[chunk] + 12.0 * spread[chunk] + 1e-9
while True:
short = self.cdf(high, mu[chunk]) < tau
if not short.any():
break
high = np.where(short, high * 2.0, high)
for _ in range(_BISECTION_STEPS):
middle = 0.5 * (low + high)
below = self.cdf(middle, mu[chunk]) < tau
low, high = np.where(below, middle, low), np.where(below, high, middle)
out[chunk, column] = high
return out
StaticTAM.predict_quantiles(data, taus) on a plain model whose loss has a quantiles method (poisson, negative_binomial, tweedie) returns the q<tau> columns of predict_count_quantiles; on any other plain loss it raises as before.
Robust M-estimators and expectiles¶
class HuberLoss(ReweightingStrategy):
"""Huber: weight 1 within delta robust scales, else delta/|u| (bounded influence)."""
name = "huber"
def __init__(self, delta: float = 1.345):
if delta <= 0:
raise ValueError(f"huber delta must be positive; got {delta}")
self.delta = float(delta)
def working_response_and_weights(self, y, eta):
residual = y - eta
scale = _robust_scale(residual)
standardized = (residual / scale).abs()
weights = torch.where(standardized <= self.delta, torch.ones_like(standardized),
self.delta / standardized.clamp_min(_TINY))
return y, weights
class ExpectileLoss(ReweightingStrategy):
"""Asymmetric least squares (Newey-Powell): weight tau above the fit, else 1-tau."""
name = "expectile"
def __init__(self, tau: float = 0.5):
if not 0.0 < tau < 1.0:
raise ValueError(f"expectile level tau must be in (0, 1); got {tau}")
self.tau = float(tau)
def working_response_and_weights(self, y, eta):
residual = y - eta
weights = torch.where(residual >= 0, torch.as_tensor(self.tau, dtype=y.dtype, device=y.device),
torch.as_tensor(1.0 - self.tau, dtype=y.dtype, device=y.device))
return y, weights
def mean_objective(self, y, eta):
residual = y - eta
asymmetric = torch.where(residual >= 0, self.tau, 1.0 - self.tau)
return (asymmetric * residual * residual).mean()
The IRLS schedule¶
reweighted_penalized_fit normalises the weights to unit mean (preserving the nS penalty scale), solves one atom, and, for GLMs, step-halves on the penalized objective. For the Gaussian identity it converges in a single step.
The design matrix depends on neither the coefficients nor the weights, so when it fits in memory (dense_design) it is built once per fit and shared by every pass, every step-halving and every dispersion refit; the covariances and the solve then run on that matrix. When it does not fit, the loop goes back to the chunked solver of the dispatcher, which builds it block by block.
def reweighted_penalized_fit(
model,
x_data: torch.Tensor,
y_data: torch.Tensor,
strategy: ReweightingStrategy,
max_iter: int = 25,
tol: float = 1e-6,
max_halvings: int = 8,
design_matrix=None,
) -> torch.Tensor:
"""Fit a strategy by iteratively reweighted penalized least squares; return the coefficients.
Args:
model: a TAM exposing _solve_pwls_step and _build_design_matrix.
x_data: feature tensor (n_groups, n_samples, n_features).
y_data: response tensor (n_groups, n_samples, 1).
strategy: the reweighting rule producing (z, w) per iteration.
max_iter: maximum outer iterations.
tol: relative change in eta for convergence.
max_halvings: maximum step-halvings per iteration (GLM divergence guard).
design_matrix: Phi(x) when the caller already built it (``dense_design``); built here when None.
"""
y_data = y_data.to(torch.get_default_dtype())
eta = strategy.initial_eta(y_data)
theta = None
penalty_matrix = model._build_penalty_matrix()
if design_matrix is None:
design_matrix = dense_design(model, x_data)
loss_matrix = model._build_loss_matrix() if design_matrix is not None else None
def penalized_objective(theta_value: torch.Tensor, eta_value: torch.Tensor) -> torch.Tensor:
# mean deviance + roughness penalty theta.T * S * theta. Step-halving must judge the
# penalized objective, else a step that lowers deviance but inflates roughness is accepted.
base = strategy.mean_objective(y_data, eta_value)
penalty_quadratic = theta_value.mT @ penalty_matrix.to(theta_value.dtype) @ theta_value
return base + penalty_quadratic.mean()
for _ in range(max_iter):
working_response, weights = strategy.working_response_and_weights(y_data, eta)
weights = weights / weights.mean().clamp_min(_TINY)
theta_candidate = _solve_step(model, x_data, working_response, weights, design_matrix, penalty_matrix, loss_matrix)
eta_candidate = _linear_predictor(model, x_data, theta_candidate, design_matrix)
if theta is not None and strategy.is_glm:
theta_full_step = theta_candidate
objective_previous = penalized_objective(theta, eta)
objective_candidate = penalized_objective(theta_candidate, eta_candidate)
step = 1.0
halving = 0
while (not torch.isfinite(objective_candidate) or objective_candidate > objective_previous) \
and halving < max_halvings:
step *= 0.5
theta_candidate = theta + step * (theta_full_step - theta)
eta_candidate = _linear_predictor(model, x_data, theta_candidate, design_matrix)
objective_candidate = penalized_objective(theta_candidate, eta_candidate)
halving += 1
relative_change = (eta_candidate - eta).norm() / eta.norm().clamp_min(_TINY)
theta = theta_candidate
eta = eta_candidate
if relative_change < tol:
break
return theta