polars_online.spec.bocpd¶
- polars_online.spec.bocpd(name: str, *, features: list[str], hazard: float | timedelta | str | Expr = 250.0, hazard_col: str | None = None, covariance_type: Literal['full', 'diag'] = 'diag', mean_prior: list[float] | None = None, mean_precision_prior: float | None = None, degrees_of_freedom_prior: float | None = None, covariance_prior: list[float] | None = None, robust_beta: float | None = None, prune_below: float | None = None, max_run: int | None = None, warm_rows: int | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Bayesian online changepoint detection, a posterior over how long the current regime has lasted.
Use it where the age of the current regime matters: it keeps a distribution over the run length, the rows since the last break, so “we are 40 rows into a regime” comes with every row, where a test answers only “has something changed?”. It is Adams and MacKay’s (2007) algorithm, over the features, with no target. Use
corrchange()for a test of a change in correlation, and a regression’semit_breaksfor a break in its coefficients.Parameters
The stream parameters every builder takes, such as
clock,gap_cap,min_weightandgroup, are inpolars_online.spec. This model takesfeaturesand notargets.half_lifeandlamare refused, since the run-length posterior is what forgets, andhazardis how fast.fit_intercepthas nothing to act on, as there is no regression.min_weightwithholds what is reported, never what is learned. No diagnostic that reads residuals applies. This model’s own:hazardHow likely a break is, in one of two forms:
hazardwhat it is
the chance of a break
a number, 250 by default
the expected rows between breaks, on any clock
1 / hazardafter every rowa duration, such as
"1h"tau, the expected time between breaks, on a temporal clock1 - exp(-dt / tau)for the step ofdtinto each row, before the row is readA number is finite and above 1. A duration is a clock parameter like
half_life. It is refused without a temporal clock, beside a clock parameter given as a plain number, and at 0 or below.dtis the step decay reads, so a gap pastgap_capcounts as the cap. A duration hazard in Notes gives the rules at a step of 0.hazard_colRead a per-row hazard from this column instead, which the bank reads beside the features as it reads a weight column. The value at a row is the expected rows between breaks as of that row:
1 / valueis the chance of a break after the row, between it and the next. A null, NaN, ±inf or magnitude above1e100falls back tohazard, and any other value of 1 or less is refused by every call that reads the column,polars_online.ModelBank.predict()included, naming the row. Default none. A durationhazardputs its chance before each row, so the two are refused together.covariance_typeThe covariance each run’s predictive keeps, in scikit-learn’s words, both exact conjugate updates:
covariance_typethe predictive
what it adds
"diag"(the default)a normal-inverse-gamma per feature
"full"a normal-inverse-Wishart over all of them
the one that can see a break in the correlation with the marginals unchanged: in
run_mode, sincep_changenever moves, and late (Reading p_change and run_mode in Notes)While the prior is set from the first rows (the default), both are free of the data’s units: a change of units multiplies every run’s predictive density by one constant, which the posterior’s normalization takes out. A prior given is in the data’s units.
mean_prior,mean_precision_prior,degrees_of_freedom_prior,covariance_priorThe conjugate prior, under scikit-learn’s
BayesianGaussianMixturenames:parameter
what it is
default
mean_priormu_0, one value per featurethe first
warm_rowsrows’ meanmean_precision_priorthe weight of that mean in rows, finite and above 0
1.0
degrees_of_freedom_priorthe degrees of freedom, finite and above
d + 1under"full"(where the predictive has a variance) and above 1 under"diag"(where it has a mean)the smallest integer that gives the prior’s variance a mean:
d + 2under"full", whose inverse-Wishart needsnu > d + 1, and 3 under"diag", whose per-feature normal-inverse-gamma needsnu > 2whateverdcovariance_priorthe prior scale of the variance as a list, in the data’s units: one positive number
[s]forstimes the identity, or thed * dentries of a symmetric positive-definite matrix, row by rowthe first
warm_rowsrows’ covariance, its diagonal under"diag"dis the number of features.mean_precision_prioranddegrees_of_freedom_priorare in rows of the stream’s mean weight. A prior in the data’s units decides what counts as surprising, so the defaults are the data’s own (The prior in Notes).robust_betaTemper the
"diag"predictive, so that a single outlying row is not read as a break: each row is weighted by(pi(x) / pi(mode)) ** robust_betain what the run learns and in the likelihood it passes on. Default none, which tempers nothing: a single 20-sigma row is then a break whose run carries the outlier in its mean. A larger power finds a real shift later, and past about 0.2 mostly not at all. Finite and above 0, and refused beside"full". The tempered predictive is not free of the data’s units, so center and scale each feature before a tempered run. In the query before the bank, make its z-score(pl.col("x") - po.ewm_mean("x", half_life=h)) / po.ewm_std("x", half_life=h)withlf.online.with_windows, which runs the window operators (Polars’with_columnscannot). Tempering in Notes gives the measurements.prune_below,max_runprune_belowis the share of the mass below which a run is dropped (default1e-6, at least 0 and below 1).max_runcaps a run’s length: the runs that reachmax_run - 1rows are folded into the one carrying the most mass (default 10,000, at least 2). A break collapses the runs to a few dozen, but a stream that does not break spreads them over thousands of run lengths. Theremax_runis the bound on the runs kept and on a row’s work (Pruning and the capped run in Notes).warm_rowsThe learned rows held to set the prior from, where
mean_priororcovariance_prioris left out. Defaultd + 2, one more thand + 1, the smallest count whose covariance is positive definite in general.hmm()andkmeans()name theirs the same way. At least 2, and refused beside both priors, which leave nothing to set. Where the first rows are not representative and rows are to spare, pass awarm_rowsof tens, all from one regime (The prior in Notes).
Output
One output column, named after the spec, whose value in each row is a record of these fields. Every field but
p_changeis read before the row is learned.p_changeis the posterior once this row’s evidence is in. docs/OUTPUTS.md#bocpd gives each field’s type and when it is null:p_changeP(r_t <= 1)given this row, a posterior probability: the alarm, spiky and as big as the break is against the prior’s scale. A group’s first row is withheld under the defaultmin_weight. With both priors given andmin_weight=0it reads 1 however the row looks (Reading p_change and run_mode in Notes).run_modeThe most likely run length before the row, so
t - run_modeis the row the current run began on. It dates a break more reliably thanp_changeflags one.run_meanThe posterior mean run length before the row.
pred_<f>The pre-row predictive mean of each feature, mixed over runs as
m* + sum_r p_r (m_r - m*),m*the most probable run’s mean, so a feature at a level keeps the precision of its spread.loglikThe row’s log predictive density under that mixture.
weight_sumThe weight the model has accumulated before the row and before the row’s own decay.
settled_fracAlways null, since nothing decays.
withheld_reasonWhy the row’s fields were withheld, null where they were not:
below_min_weighton a group’s first row under the defaultmin_weight, which takes precedence, thenbelow_warm_rowson the rest of the rows held to set the prior from.
A row whose predictive cannot be evaluated reports nulls and is counted in
polars_online.ModelBank.solve_failures(). It leaves the posterior where it stands, except for a durationhazard’s chance of a break over its step, which time passing applies.Raises
As every builder does (
polars_online.spec),TypeErrorfortargets, which this model does not take, andValueErrornaming the problem for:an empty
features, anyhalf_lifeorlam, and acovariance_typeother than"full"or"diag";a number
hazardof 1 or less or not finite, and a durationhazardwith no clock, beside a plain-number clock parameter, at 0 or below, or besidehazard_col;a
mean_priorof the wrong length or holding a value that is not finite, acovariance_priorholding a value that is not finite, amean_precision_priornot finite or not above 0, adegrees_of_freedom_priornot finite or at or below its floor, and acovariance_priorthat is neither[s]nord * dentries, or is not positive, symmetric and positive definite (checked whole, even under"diag", which reads its diagonal);a
robust_betabesidecovariance_type="full", and one at 0, below it or not finite;a
prune_belowoutside[0, 1), amax_runbelow 2, awarm_rowsbelow 2 or beside both priors, and held rows past 256 MiB;a switch of a diagnostic that reads residuals;
and, from a call that learns or predicts,
ValueErrorfor ahazard_colvalue of 1 or less, naming the row.The update
Adams and MacKay’s Algorithm 1, in log space.
ris a run length,H = 1 / hazardthe chance of a break after the row, andpi_rrunr’s posterior predictive for this row:growth: P(r_t = r+1, x_1:t) = P(r_t-1 = r, x_1:t-1) pi_r (1 - H) changepoint: P(r_t = 0, x_1:t) = sum_r P(r_t-1 = r, x_1:t-1) pi_r H
Under a duration
hazard, the chanceh = 1 - exp(-dt / tau)that a break fell inside the step belongs before the row. Sohof every run’s mass moves to the empty run before the row is read, and the recursion above runs withH = 0, since no time has passed since the row:before the row: P(r = 0) += h * sum_{r >= 1} P(r), P(r) *= 1 - h for r >= 1Run
rkeeps the conjugate statistics of exactly therrows that hypothesis says preceded this one in the run. So run 0 holds none, and its predictive is the prior’s, which is what makes “a new run starts here” something the data can vote on. A row of weightwis learned atw / w_bar,w_barthe mean weight of the rows learned, this one included, in its run’s statistics and in the likelihood it passes the recursion. So a heavier row is more evidence of both kinds, and a constant multiple of every weight changes nothing. What the row reports is read as a row of the mean weight, which is allpredictcan know.Example
This code runs the model over a level that steps up by four standard deviations at row 600, and prints the row the current run began on, before and after the step:
import numpy as np rng = np.random.default_rng(7) x = rng.standard_normal(1_000) x[600:] += 4.0 # the level steps up at row 600 pl.DataFrame({"x": x}).write_parquet("step.parquet") b = po.spec.bocpd("regime", features=["x"], hazard=250.0) out = pl.scan_parquet("step.parquet").online.fit_predict([b]).collect() out = out.unnest("regime") for row in [599, 650, 999]: began = row - out["run_mode"][row] # the row the current run began on print(f"row {row}: the run began on row {began}")
row 599: the run began on row 0 row 650: the run began on row 600 row 999: the run began on row 600
See also
corrchange(), tests for a change in the correlation of two features.hmm(), a fixed number of regimes the stream moves between.docs/REGIMES.md, the models of regimes and changes, side by side.
Notes
Reading p_change and run_mode. Under a number
hazard,p_changeisP(r <= 1)and notP(r = 0): the changepoint branch and the growth branch share the same predictive, which makes the normalized mass atr = 0exactlyHon every row whatever the data. Under a durationhazard, the chance of a break is applied before the row, so no mass sits atr = 0after it, andp_changeis the chance that this row began a run. There, a row whose clock step is 0 (a stamp shared with the last row the model did not skip) reports 0, apart from a run’s first row: a group’s first row, and its first after a reset. Withmean_priorandcovariance_priorboth given, the defaultmin_weightwithholds such a row, and withmin_weight=0it reports ap_changeof 1 there. Unless both are given, the firstwarm_rowsrows report null.run_modedates a break more reliably thanp_changeflags one. A break the posterior accepts a row or two late shows as a fall inrun_mode, not inp_change. Over six seeds of a 5-sigma step at row 500, at the defaults,run_modefell to 1 or 2 within two rows of the break on every seed, while the largestp_changenear it ranged from 0.021 to 0.749.the break
p_changethe run length
the spread steps tenfold, under a prior of the rows’ scale
0.83 on the row of the break
found within a few rows, dated to the right row
a four-sigma mean shift under a diffuse prior
barely lifts
the same
a change in correlation alone
never moves
never found under
"diag"; under"full", found a median of 121 rows after the breakA duration hazard. A step of 0 has no chance of a break: a row that shares the previous row’s stamp cannot begin a run. A row of weight 0 applies its step’s chance, since time passed, and learns nothing, so two steps with nothing learned between them read as one step of their sum. Under
prune_below = 0each step of 0 leaves one run of no mass among the runs kept, untilmax_runfolds it.Tempering. Untempered, a single 20-sigma row reads
p_change0.91, and its run carries the outlier in its mean. Tempered, an outlying row is atypical under every run, every tempered likelihood is about 1, and nothing moves. A whole new regime is a run of individually forgiven rows, which is why a larger power finds a real shift later. Over 50 streams with a four-sigma shift athazard=250, a shift counts as found oncerun_modedates it to within 5 rows, inside 150 rows:robust_betathe shifts found
0.1
all 50, the worst 6 rows late, while a 20-sigma outlier left
p_changeat its floor0.15
all 50, the worst 16 rows late
0.2
38, the worst 120 rows late
0.3
1
0.5
none
The tempered predictive’s message
pi ** wcarries the constant a change of units multiplies the density by asc ** w, andwdiffers from run to run, so the runs’ odds move with the units. At a level of1e4with a spread of1e-2,p_changemoved by up to 0.86 against the same stream at level 0 and spread 1.robust_betais a power on a ratio of two densities, and has no units.The prior. Too wide a prior, and the model goes quiet, because no row is surprising under a predictive that wide. Too narrow or off-center, and every run that begins on a row has no density for it. With
mean_priororcovariance_priorleft out, the firstwarm_rowslearned rows report null and are held. Their weighted mean and covariance (numpy.cov’s withaweights, the sample covariance at equal weights) set what was left out, and then they are read, in order, as rows of a model that had that prior from the start. At the defaultdegrees_of_freedom_priorthe prior’s mean variance is then that covariance. A feature that does not move over those rows has no variance to give. It takes2**-52 * max(mean**2, 1), the spread of a value known to2**-26of its level, since a predictive of no spread has no density. Under"full"a covariance that is not positive definite, two features that are one, gives its diagonal. With both given there is no warm-up.degrees_of_freedom_priorandcovariance_priorare2aand2bin the gamma parametrization, which is how Adams and MacKay give their own finance example (a = 1,b = 1e-4,hazard = 250: in this model’s termsdegrees_of_freedom_prior=2.0andcovariance_prior=[2e-4]).The prior is set once from the
warm_rowsrows and kept for the stream’s life, so atd + 2rows its scale rests ond + 1degrees of freedom. For one feature, a 3-row variance lies between 0.05 and 3 times the truth nine times in ten. A warm-up that straddles a regime change sets a wide prior: a variance of 37 across a 10-sigma step, against 0.53 from rows inside one regime.Pruning and the capped run. A row takes
O(runs * d)undercovariance_type="diag", tempered or not, andO(runs * d³)under"full", which factors each run’s scale. The run vector would grow by one every row, so runs belowprune_belowof the mass are dropped. The runs that reachmax_run - 1rows are folded into the one of them carrying the most mass, the oldest among equals, which takes their mass and the tail’s place. Its statistics are scaled back tomax_run - 1rows’ weight, as a decay would scale them: the weight and scatter shrink, the mean stays. No run kept is longer thanmax_run - 1rows, sorun_modesaturates one below it, and the runs kept, at mostmax_runlengths, bound the work a row takes. The capped run is an exponentially weighted run, scaled by(max_run - 1) / max_runeach row. Its mean steps by1 / max_runof the row’s deviation. Its half-life isln 2 / ln(max_run / (max_run - 1)), about0.69 * (max_run - 1)rows, 6,900 at the default. The run that dominates a quiet stream keeps its memory at the cap however many younger runsprune_belowdrops. After a break, the post-break run takes its place once it reaches the cap.One feature is the slow case. A row’s work is the number of live runs times
d, and with one feature a row carries little evidence about the run length, so the posterior stays spread over many run lengths and many keep more thanprune_belowof the mass. On 60,000 independent standard normal rows, with the defaults, one thread of an Apple M4 Pro, a row took about 120 µs with one feature, 3.5 µs with two and 1.4 µs with four. The default does not change with the number of features. A one-feature stream that needs speed setsprune_belowlarger (1e-4took 4 µs a row and1e-30.4 µs on those rows) ormax_runsmaller; either drops runs, sop_changeandrun_modemove.