kumulant

BayesianRegressionStat

class BayesianRegressionStat(val featureSize: Int, val priorVariance: Double = StatDefaults.BAYESIAN_REGRESSION_PRIOR_VARIANCE, val link: Link = StatDefaults.regressionLink, val concurrency: Concurrency = Concurrency.None, priorMean: Vector? = null, priorCovariance: Matrix? = null) : RegressionStat<PrecisionRegressionResult> (source)

Bayesian generalised linear regression with a Gaussian prior on the weights and a canonical Link for the response. Produces the full joint posterior as the Cholesky factor of its precision H, from which the covariance S = H^-1 and every quantity built on it follow by triangular solve. Suitable for Thompson-sampling-style bandits drawing a fresh weight vector from N(weights, exploration * S) per round.

A square-root information filter. Each observation contributes local precision w_c = weight * link.curvature(eta) and is folded straight into the factor:

L       <- chol(L * LT + w_c * x xT)     (rank-1 update)
v       = (L * LT)^-1 * x                (two triangular solves)
w       = w + weight * (y - mu) * v

Carrying H rather than S is what makes this stable: w_c is non-negative for every canonical link, so the rank-1 update can never leave the positive-definite cone, and the same event expressed on the covariance would be a Sherman-Morrison downdate that can. There is no repair path because there is nothing to repair.

An observation with a non-finite feature is skipped whole, since it would leave the factor non-finite and every later merge unable to factor it. Non-finite targets follow the arithmetic: the factor stays finite while weights, bias and sse become NaN.

Under Link.Identity this is the strict closed-form conjugate Gaussian posterior (curvature = 1). Under Link.Logit / Link.Log it is the online Laplace approximation - each observation tightens the posterior by the local Hessian curvature * x xT, which is exact only at the current linear predictor. The approximation tracks the true GLM posterior closely for well-identified problems.

Regularisation is the Gaussian prior, controlled by priorVariance / priorMean / priorCovariance; tighten the prior to shrink weights toward zero (or a target). The prior covariance is factored, inverted, and factored again at construction, so a non-positive-definite prior throws there rather than corrupting later fits.

Residual variance: sigma^2 = 1. Callers wanting heteroscedastic noise can re-scale y before update() or pass per-observation precision via weight.

Use cases: Thompson-sampling-style linear-bandit arms (draws from N(weights, exploration · S) per round), full-covariance online regression for low-to-mid dimensions, GLM fitting where the joint posterior is needed. Reach for DiagonalRegressionStat when only marginal posteriors are required and dimensions are high.

Memory: O(featureSize^2); weights plus the precision factor and the prior matrices the merge needs, and the pooled scratch the first update or merge borrows, which is then held for the life of the stat so later calls reuse it.

Update: O(featureSize^2) per observation; one rank-1 Cholesky update and two triangular solves, with no refactorization path.

Concurrency: Body serialised by an internal lock under any concurrent Concurrency level (no-op under Concurrency.None). Exact under every level up to floating-point reorder ULPs; throughput bound by lock contention; shard and merge for higher write rates. The update and merge scratch is owned per stat and guarded by that lock alone, so a Concurrency.None stat updated or merged from two threads can fail inside the linear-algebra layer rather than only drift.

Constructors

BayesianRegressionStat

constructor(featureSize: Int, priorVariance: Double = StatDefaults.BAYESIAN_REGRESSION_PRIOR_VARIANCE, link: Link = StatDefaults.regressionLink, concurrency: Concurrency = Concurrency.None, priorMean: Vector? = null, priorCovariance: Matrix? = null)(source)

Types

Link copied to clipboard
object Companion

Empirical-Bayes / hierarchical helpers that operate on populations of fitted snapshots.

Properties

concurrency

open override val concurrency: Concurrency(source)

Thread-safety mode fixed at construction. See Concurrency for the shared contract and the implementation's KDoc for its cell and lock strategy.

featureSize

open override val featureSize: Int(source)

Number of features expected in x on each update. Mismatched lengths throw.

priorVariance

Isotropic prior variance used when neither priorCovariance nor priorMean is supplied.

Functions

create

open override fun create(concurrency: Concurrency? = null): BayesianRegressionStat(source)

Create an independent accumulator at the configured baseline. A null concurrency preserves this accumulator's mode; a non-null value overrides it. Modality subtypes narrow the return type to preserve the input shape.

merge

open override fun merge(values: PrecisionRegressionResult, timestampNanos: Long = currentTimeNanos())(source)

Combine two independent Gaussian posteriors over the same parameter by multiplying their densities and renormalising. Each posterior already includes one prior factor, so the combined precision subtracts one copy back out:

H_new  = H_self + H_other - H_prior
b_new  = H_self * mu_self + H_other * mu_other - H_prior * mu_prior
mu_new = H_new^-1 * b_new

Both operands already carry their precision factor, so H comes back by syrk and the information vectors by two triangular products each; the factor of H_new is the new state, so nothing is inverted and nothing is factored twice. For a non-zero prior mean the H_prior * mu_prior correction is subtracted from the information vector as well, otherwise the merged posterior would count the prior shift twice. When H_new drifts outside SPD, CholeskyPolicy.Regularize clamps the offending pivot and factors a nearby matrix rather than returning NaNs. Bias is merged the same way, treating the intercept as a scalar Gaussian with zero prior mean.

read

open override fun read(timestampNanos: Long = currentTimeNanos()): PrecisionRegressionResult(source)

Return the current result evaluated at timestampNanos. Time-independent statistics ignore the timestamp. Reading does not add an observation.

Snapshot consistency depends on the implementation's synchronisation. Locks protect coupled state under Concurrency.Strict and Concurrency.HighWrite; independently updated cells and JVM striped adders can still yield a best-effort snapshot. Concurrency.Relaxed permits drift across coupled cells.

reset

open override fun reset()(source)

Restore the configured baseline, including any prior seed. Preserves the configuration and concurrency.

validateMerge

open override fun validateMerge(values: PrecisionRegressionResult)(source)

Validate values for merge without changing accumulator state. Containers validate every child before merging any of them. Successful validation checks compatibility; it does not make a concurrent merge transactional.

Link copied to clipboard
open fun update(x: Vector, y: Double, weight: Double = 1.0)

Record the pair (x, y) with weight at the current monotonic time.

open fun update(x: DoubleArray, y: Double, weight: Double = 1.0)

Convenience overload that wraps x as a DenseVector.

open fun update(x: DoubleArray, y: Double, timestampNanos: Long, weight: Double = 1.0)

Timestamped convenience overload that wraps x as a DenseVector.

open override fun update(x: Vector, y: Double, timestampNanos: Long, weight: Double = 1.0)

Record the pair (x, y) with weight at timestampNanos.

update

open override fun update(x: Vector, y: Double, timestampNanos: Long, weight: Double = 1.0)(source)

Record the pair (x, y) with weight at timestampNanos.