rheon.spec.bocpd

rheon.spec.bocpd(name: str, *, features: list[str], hazard_rows: float | None = None, hazard: float | timedelta | str | _Expr | None = None, 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, warm_span: float | timedelta | str | _Expr | 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’s emit_breaks for a break in its coefficients.

Parameters

The stream parameters every builder takes, such as clock, gap_cap, min_weight and group, are in rheon.spec. This model takes features and no targets. half_life and lam are refused, since the run-length posterior is what forgets, and the hazard is how fast. fit_intercept has nothing to act on, as there is no regression. min_weight withholds what is reported, never what is learned. No diagnostic that reads residuals applies. This model’s own:

hazard_rows, hazard

How likely a break is, per row or per unit of clock time:

parameter

what it is

the chance of a break

hazard_rows, 250 by default

the expected rows between breaks, on any clock

H = 1 / hazard_rows after every row

hazard

tau, the expected clock time between breaks: a number of the clock’s units, or of rows where the spec has no clock, or a duration such as "1h" on a temporal clock

h = 1 - exp(-dt / tau) for the step of dt into each row, before the row is read

Choose hazard_rows where a break is as likely after any row, however far apart the rows fall: Adams and MacKay’s hazard, one step an observation. Choose hazard where breaks come in time, so a long gap makes a break near certain and a row sharing the last row’s stamp cannot begin a run. On regular steps the two are the same model at hazard_rows = 1 / (1 - exp(-dt / tau)): every output agrees but p_change, which the per-row form reads with H of the mass at r = 0 after the row, p_rows = H + (1 - H) * p_clock (Reading p_change and run_mode in Notes). On data with irregular steps, each form fits best where breaks come as it assumes, so the choice is a model of where breaks come from.

hazard_rows is finite and above 1. hazard is a clock parameter like half_life: a plain number is refused on a temporal clock, a duration without one, and either beside a clock parameter written the other way. It is finite and above 0. dt is the step decay reads, so a gap past gap_cap counts as the cap and a row of weight 0 is in no step. The two are refused together. A clock hazard in Notes gives the rules at a step of 0.

hazard_col

Read 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 / value is the chance of a break after the row, between it and the next. A null, NaN, ±inf or magnitude above 1e100 falls back to hazard_rows, and any other value of 1 or less is refused by every call that reads the column, rheon.polars.ModelBank.predict() included, naming the row. Default none. hazard puts its chance before each row, so the two are refused together.

covariance_type

The covariance each run’s predictive keeps, in scikit-learn’s words, both exact conjugate updates:

covariance_type

the 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, since p_change never 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_prior

The conjugate prior, under scikit-learn’s BayesianGaussianMixture names:

parameter

what it is

default

mean_prior

mu_0, one value per feature

the first warm_rows rows’ mean

mean_precision_prior

the weight of that mean in rows, finite and above 0

1.0

degrees_of_freedom_prior

the degrees of freedom, finite and above d + 1 under "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 + 2 under "full", whose inverse-Wishart needs nu > d + 1, and 3 under "diag", whose per-feature normal-inverse-gamma needs nu > 2 whatever d

covariance_prior

the prior scale of the variance as a list, in the data’s units: one positive number [s] for s times the identity, or the d * d entries of a symmetric positive-definite matrix, row by row

the first warm_rows rows’ covariance, its diagonal under "diag"

d is the number of features. mean_precision_prior and degrees_of_freedom_prior are 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_beta

Temper 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_beta in 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") - rp.ewm_mean("x", half_life=h)) / rp.ewm_std("x", half_life=h) with lf.rheon.with_windows, which runs the window operators (Polars’ with_columns cannot). Tempering in Notes gives the measurements.

prune_below, max_run

prune_below is the share of the mass below which a run is dropped (default 1e-6, at least 0 and below 1). max_run caps a run’s length: the runs that reach max_run - 1 rows 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. There max_run is the bound on the runs kept and on a row’s work (Pruning and the capped run in Notes).

warm_rows

The learned rows held to set the prior from, where mean_prior or covariance_prior is left out. Default d + 2, one more than d + 1, the smallest count whose covariance is positive definite in general. hmm() and kmeans() 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 a warm_rows of tens, all from one regime (The prior in Notes).

warm_span

The warm-up over a span of the clock in place of warm_rows: the learned rows from the first through the first row at least warm_span after it, once they are at least two. A number of the clock’s units, or of rows where the spec has no clock, or a duration such as "1h" on a temporal clock; finite and above 0. The span is read off the rows’ exact stamps, and a row of weight 0 is no row of it, so on a clock of one unit a row it holds warm_span + 1 rows: the prior of warm_rows = warm_span + 1, to the bit. The data decides how many rows that is, so they are held to 256 MiB as they come: past half of it a warning, once a group, and the row that would pass it stops the run with an error naming the group and the bytes. Refused beside warm_rows and beside both priors.

Output

One output column, named after the spec, whose value in each row is a record of these fields. Every field but p_change is read before the row is learned. p_change is the posterior once this row’s evidence is in. docs/OUTPUTS.md#bocpd gives each field’s type and when it is null:

p_change

P(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 default min_weight. With both priors given and min_weight=0 it reads 1 however the row looks (Reading p_change and run_mode in Notes).

run_mode

The most likely run length before the row, so t - run_mode is the row the current run began on. It dates a break more reliably than p_change flags one.

run_mean

The 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.

loglik

The row’s log predictive density under that mixture.

weight_sum

The weight the model has accumulated before the row and before the row’s own decay.

settled_frac

Always null, since nothing decays.

withheld_reason

Why the row’s fields were withheld, null where they were not: below_min_weight on a group’s first row under the default min_weight, which takes precedence, then below_warm_rows on the rest of the rows held to set the prior from.

A row whose predictive cannot be evaluated reports nulls and is counted in rheon.polars.ModelBank.solve_failures(). It leaves the posterior where it stands, except for hazard’s chance of a break over its step, which time passing applies.

Raises

As every builder does (rheon.spec), TypeError for targets, which this model does not take, and ValueError naming the problem for:

  • an empty features, any half_life or lam, and a covariance_type other than "full" or "diag";

  • a hazard_rows of 1 or less or not finite; a hazard at 0 or below or not finite, a duration hazard with no clock or beside a plain-number clock parameter, and a number hazard on a temporal clock or beside a duration; hazard beside hazard_rows or hazard_col;

  • a mean_prior of the wrong length or holding a value that is not finite, a covariance_prior holding a value that is not finite, a mean_precision_prior not finite or not above 0, a degrees_of_freedom_prior not finite or at or below its floor, and a covariance_prior that is neither [s] nor d * d entries, or is not positive, symmetric and positive definite (checked whole, even under "diag", which reads its diagonal);

  • a robust_beta beside covariance_type="full", and one at 0, below it or not finite;

  • a prune_below outside [0, 1), a max_run below 2, a warm_rows below 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, ValueError for a hazard_col value of 1 or less, naming the row.

The update

Adams and MacKay’s Algorithm 1, in log space. r is a run length, H = 1 / hazard_rows the chance of a break after the row, and pi_r run r’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 hazard, the chance h = 1 - exp(-dt / tau) that a break fell inside the step belongs before the row. So h of every run’s mass moves to the empty run before the row is read, and the recursion above runs with H = 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 >= 1

Run r keeps the conjugate statistics of exactly the r rows 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 weight w is learned at w / w_bar, w_bar the 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 all predict can 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 = rp.spec.bocpd("regime", features=["x"], hazard_rows=250.0)
out = pl.scan_parquet("step.parquet").rheon.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 hazard_rows, p_change is P(r <= 1) and not P(r = 0): the changepoint branch and the growth branch share the same predictive, which makes the normalized mass at r = 0 exactly H on every row whatever the data. Under hazard, the chance of a break is applied before the row, so no mass sits at r = 0 after it, and p_change is the chance that this row began a run. On regular steps of dt the two forms read every row against the same posterior, and p_rows = H + (1 - H) * p_clock with H = 1 - exp(-dt / tau): about H apart on a quiet row. There, under hazard, 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. With mean_prior and covariance_prior both given, the default min_weight withholds such a row, and with min_weight=0 it reports a p_change of 1 there. Unless both are given, the first warm_rows rows report null.

run_mode dates a break more reliably than p_change flags one. A break the posterior accepts a row or two late shows as a fall in run_mode, not in p_change. Over six seeds of a 5-sigma step at row 500, at the defaults, run_mode fell to 1 or 2 within two rows of the break on every seed, while the largest p_change near it ranged from 0.021 to 0.749.

the break

p_change

the 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 break

A clock 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 counts in no clock, so the next row’s step runs from the last row that counted, one step of the time since. Without a clock column each row of positive weight is a step of 1. Under prune_below = 0 each step of 0 leaves one run of no mass among the runs kept, until max_run folds it.

Tempering. Untempered, a single 20-sigma row reads p_change 0.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 at hazard_rows=250, a shift counts as found once run_mode dates it to within 5 rows, inside 150 rows:

robust_beta

the shifts found

0.1

all 50, the worst 6 rows late, while a 20-sigma outlier left p_change at its floor

0.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 ** w carries the constant a change of units multiplies the density by as c ** w, and w differs from run to run, so the runs’ odds move with the units. At a level of 1e4 with a spread of 1e-2, p_change moved by up to 0.86 against the same stream at level 0 and spread 1. robust_beta is 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_prior or covariance_prior left out, the first warm_rows learned rows report null and are held. Their weighted mean and covariance (numpy.cov’s with aweights, 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 default degrees_of_freedom_prior the prior’s mean variance is then that covariance. A feature that does not move over those rows has no variance to give. It takes 2**-52 * max(mean**2, 1), the spread of a value known to 2**-26 of 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_prior and covariance_prior are 2a and 2b in the gamma parametrization, which is how Adams and MacKay give their own finance example (a = 1, b = 1e-4, hazard_rows = 250: in this model’s terms degrees_of_freedom_prior=2.0 and covariance_prior=[2e-4]).

The prior is set once from the warm_rows rows and kept for the stream’s life, so at d + 2 rows its scale rests on d + 1 degrees 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) under covariance_type="diag", tempered or not, and O(runs * d³) under "full", which factors each run’s scale. The run vector would grow by one every row, so runs below prune_below of the mass are dropped. The runs that reach max_run - 1 rows 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 to max_run - 1 rows’ weight, as a decay would scale them: the weight and scatter shrink, the mean stays. No run kept is longer than max_run - 1 rows, so run_mode saturates one below it, and the runs kept, at most max_run lengths, bound the work a row takes. The capped run is an exponentially weighted run, scaled by (max_run - 1) / max_run each row. Its mean steps by 1 / max_run of the row’s deviation. Its half-life is ln 2 / ln(max_run / (max_run - 1)), about 0.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 runs prune_below drops. 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 than prune_below of 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 sets prune_below larger (1e-4 took 4 µs a row and 1e-3 0.4 µs on those rows) or max_run smaller; either drops runs, so p_change and run_mode move.