rheon.spec.pa

rheon.spec.pa(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], features: list[str], mode: Literal['pa', 'pa1', 'pa2'] = 'pa1', c: float | None = None, eps: float | None = None, coef_min: float | list[float] | None = None, coef_max: float | list[float] | None = None, coef_sum: float | None = None, standardize: bool = True, **common: Unpack[CommonKwargs]) → dict[str, Any][source]

Passive-aggressive regression, which moves the fit by the smallest step that brings each row within a margin of its target.

Use it for a fit in O(k) time a row, k the number of features, with no learning rate to tune. A row whose prediction is within eps standard deviations of its target moves nothing, and any other row moves the fit toward it by the smallest change, capped by c under pa1 and damped under pa2 (Crammer et al. 2006). Use sgd() for other losses or a learning rate, and ewridge() for an exact fit on running sums.

Parameters

The stream parameters every builder takes, such as clock, half_life, gap_cap, min_weight, group and the diagnostics, are in rheon.spec. This model’s own:

mode

"pa", "pa1" (the default) or "pa2". Prefer the bounded modes when outliers are possible: plain "pa" moves the fit as far as it takes to satisfy a single bad row.

c

Under pa1, the cap on the step size tau. It is in the target’s units over the units of q, the row’s squared length: the features’ squared units, or none under standardize, where c is in the target’s units alone. So what the cap does depends on the target’s scale (c and the target’s units in Notes). Under pa2, c sets the damping 1 / (2c) added to q, in q’s units and free of the target’s. Default 1.0, which caps a step of pa1 at one unit of the target per unit of q. Above 0. inf caps nothing, so either bounded mode is then "pa". "pa" reads no c and refuses one.

eps

The margin, in units of sigma, the target’s own exponentially weighted (EW) standard deviation: a row whose prediction is inside it moves nothing. Finite and at least 0. Default 0.01: residuals under 1% of the target’s own spread do not move the fit. On a target a fit predicts closely, the default margin can be many noise standard deviations wide (The margin in Notes).

coef_min, coef_max, coef_sum

Constraints on the slopes, exactly as for sgd(). Default: no constraint. The projection follows each step, so the step does not meet the row’s margin exactly: it is the closest feasible coefficient to the one that would. A truth outside the feasible set is never reached, so the model keeps stepping against the walls. A small c keeps those steps small.

standardize

Take the step in standardized coordinates, with sgd()’s scaler, its rule and its warm-up. Each row is standardized against the running moments with the row admitted, z_i = (x_i - m_i) / s_i (z_i = x_i / s_i, the root mean square, without an intercept), and a box or a sum is projected with its bounds carried over. Default True. Without it, q and c are in the features’ units, so one feature in thousands makes every step tiny and one in thousandths makes the cap bind on most steps. Once the scaler has warmed up, a change in the moments moves no prediction (Standardizing in Notes).

min_weight counts the rows the target was present on, at their weights, decayed, where weight_sum counts every row, so rows with a null target do not warm up coefficients they never moved.

A row’s weight below 1 scales tau, so a half-weight row moves the fit half as far. In the step, a weight above 1 counts as 1, though weight_sum, each target’s weight, the scaler and sigma take the full weight. In a model that keeps running sums, a row of weight 2 counts as two rows of weight 1. Here the step aims at the row’s constraint, so a weight past 1 would overshoot. A constant weight of 2 would make the plain "pa" step oscillate without settling. The coefficients do not decay, so one very heavy row would move the fit with no way back.

Output

One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#pa gives each field’s type and when it is null:

pred_<t>, resid_<t>

Per target: the prediction, and y - pred where the target is not null.

weight_sum

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

settled_frac

How far the model had come toward its steady state under decay before the row.

withheld_reason

Why the row’s predictions were withheld, null where they were not: a reason of the shared gates (rheon.spec), such as below_min_weight on the first rows under the default min_weight.

coef

Per target, the intercept (unless fit_intercept=False) then one entry per feature, after the row is learned (coef_index()).

plus the fields of the diagnostics switched on, as rheon.spec describes them.

Raises

As every builder does (rheon.spec), and ValueError naming the problem for:

  • a mode other than "pa", "pa1" or "pa2";

  • a c not above 0, and any c beside mode="pa", which reads none;

  • an eps not finite or below 0;

  • coef_min, coef_max and coef_sum, checked as for sgd().

The update

Here z is the row’s features, the intercept’s 1 inside it, b the coefficients, w the row’s weight and p = z . b the prediction. sigma is the target’s own EW standard deviation as the row arrives, loss = max(0, |y - p| - eps * sigma) and q = ||z||^2:

pa    tau = loss / q                 (unbounded)
pa1   tau = min(c, loss / q)         (capped at c)
pa2   tau = loss / (q + 1 / (2c))    (damped by c)
b    += min(w, 1) * tau * sign(y - p) * z

That is the step with standardize=False, z = [1, x]. Under standardize, the default, z is the row standardized. Once the scaler has warmed up, the coefficients are held in the caller’s units, the prediction is p = [1, x] . b, and the step is mapped into the caller’s units by the row’s own means m_i and standard deviations s_i:

step  = min(w, 1) * tau * sign(y - p)
b_i  += step * z_i / s_i
b_0  += step - sum_i m_i * step * z_i / s_i

Example

This code fits a plane with an intercept of 1 and slopes of 2 and -0.5, each step capped at 0.1, and prints the coefficients found at the last row:

import numpy as np

rng = np.random.default_rng(5)
x0, x1 = rng.standard_normal(5_000), rng.standard_normal(5_000)
y = 1.0 + 2.0 * x0 - 0.5 * x1 + 0.3 * rng.standard_normal(5_000)
pl.DataFrame({"x0": x0, "x1": x1, "y": y}).write_parquet("pa.parquet")

pa = rp.spec.pa(
    "pa", targets=["y"], features=["x0", "x1"], half_life=200.0,
    mode="pa1", c=0.1,                    # each step is capped at c
)
bank = rp.ModelBank([pa])
bank.fit(pl.scan_parquet("pa.parquet"))  # learn every row, keep no output
for r in bank.coef().iter_rows(named=True):
    print(f"{r['term']}: {r['coef']:.2f}")
intercept: 0.89
x0: 2.04
x1: -0.56

See also

  • sgd(), gradient steps with a learning rate, under several losses, with the same scaler and constraints.

  • ewridge(), an exact fit on running sums.

  • pa in docs/MODELS.md: recipes on data whose answer is known.

Notes

The margin’s scale. The margin, eps * sigma on each side of the prediction, is a tube, as sgd()’s is. sigma is the target’s own EW standard deviation as the row arrives. It is the spread of y around its EW mean, over the rows with the target and a weight above 0, whatever the fit, each y joining after its own row is judged. Before the target has a sigma above 0, which takes two weighted rows of different values, the tube has no width and every row moves the fit. A tube of 0.1 in the target’s own units would hold a target in hundredths on every row: passive forever, every prediction 0.0 and R² -0.05, where the same target unscaled reached 0.96.

sigma is not a scale of the residuals, such as the one huber()’s cut is drawn in. The fit starts from zero coefficients, so its first residuals are the target’s whole level. On a target at 1,000 with a spread of 2 they put the residual’s standard deviation near 1,000, so a tube of eps = 0.1 drawn in it would be about 100 wide and hold every row. Without decay it would never narrow: R² -52 at a half-life of 1e9.

c and the target’s units. pa1’s tau is in the target’s units over q’s, so a cap of 1 caps every step of a target in thousands and none of a target in thousandths. The figures in The margin are for a target of spread about 2. pa2’s c is added to q as 1 / (2c), in q’s units, so it is free of the target’s. Under "pa" and "pa2" a target scaled by a fits as the unscaled one, scaled by a. Under "pa1" it does so only while the cap does not bind.

The margin. In units of the noise, on a target a fit predicts to R², sigma is the noise’s standard deviation over sqrt(1 - R²), so the tube is eps / sqrt(1 - R²) noise standard deviations wide. At the default 0.01:

R²

0.5

0.978

0.9975

0.9998

0.99998

the tube, in noise standard deviations

0.014

0.067

0.20

0.71

2.2

A tube well inside the noise damps nothing: every row outside it is projected onto its edge, and only a cap that binds damps then. A wider tube damps too, while the cap does not bind: the fit moves only on the rows in the noise’s tails, and they keep pulling it back. But a tube many noise standard deviations wide holds the fit wherever it first lands inside it. Measured (pa1, one feature, a target of spread about 2, no decay; the out-of-sample error above the noise, in noise variances, median over seeds):

R²

the defaults

c = 0.1

eps = 0.1

eps = 0.5

0.978

1.15

0.33

0.57

0.06

0.99998

0.14

0.14

65 (25 to 347)

1,496

At R² 0.978 the default tube, 0.067 noise standard deviations, damps nothing, and a cap of 1 binds on few rows of a target of spread 2: a cap of 0.1 or a wider tube damps more. At R² 0.99998 the default tube is 2.2 noise standard deviations and no cap binds. A tube of 0.1 (22 of them) or 0.5 holds the fit wherever it first lands, from 25 to 347 noise variances over 20 seeds at 0.1. Over 108 streams and the three modes, the default had the smallest worst regret (R² from 0.5 to 0.99998, a level of 0 or plus or minus 1,000, a half-life of 50, 500 or none, one feature or five). The default was also measured against a tube drawn in the residuals’ spread, capped by the target’s spread. Without decay, that spread kept the large residuals of the first rows forever: under pa2 it left a target at a level of 1,000 at R² 0.76 to 0.80.

On a level that moves, give a larger c or difference the target. The fit starts from zero coefficients, and a pa1 cap of 1 moves the intercept about one unit a row. On a target falling from 1,000 to -1,000 at 0.5 a row (half-life 200, noise 0.3), the intercept stood at 51.5 at row 50 and 401 at row 400, and met the level near row 670. With the level as a feature too, the capped steps, mapped into the caller’s units through the scaler, swung the fit far past the level instead. A drift that the intercept carries alone keeps a lag at any c: 2.2 on average over rows 800 to 1,600 at c = 1000. About half of it is the tube, eps * sigma, whose sigma holds the drift (97 to 143 here). With eps = 0 the lag was 1.1. Differencing the target and the moving features, y - y.shift(1), takes the level out of the fit: the level is then the last row’s y plus the predicted change, and the change carries noise of 0.42 here. Measured as pred - y:

the run

row 800

row 1,600

every row within 3 from row

the defaults, the level a feature

1,790

-3.2

2,795

c = 10, the level a feature

0.67

1.1

467

c = 1000, the level a feature

-0.52

-0.60

11

the defaults, the level the intercept’s alone

1.3

2.1

never: 2.7 rms over rows 800 to 1,600

differenced, the level read back

-0.73

-0.05

12

Decay. The coefficients keep no running sums, so there is nothing in them for the clock to decay: each step moves the fit toward the current row and keeps nothing else, and older rows survive only through the coefficients they left behind. The clock decays weight_sum and each target’s own weight, which min_weight reads, so min_weight means the same thing as in every model. It decays the scaler and sigma too. The coefficients have no half-life.

Standardizing. Until Kish’s count of the rows the moments have learned reaches 22, the coefficients are held in the standardized coordinates and read back in the caller’s units through the moments as they stand. On the row that count reaches 22, the coefficients are converted to the caller’s units once, and from then on held there, the step mapped into them as The update shows. The step still puts the row where the update’s equations say. The row’s change of prediction is step * ||z||^2, so an uncapped step at weight 1 leaves it on the tube’s edge, and one at weight w < 1 goes that fraction of the way. The prediction reads no moment, so a change in the moments moves none of it. The alternative, a fit read through the moments as they stand, lets a finite half-life’s own wander in the moments move every prediction. At a half-life of 50 and R² 0.99998 that cost 31.8 noise variances of out-of-sample error above the noise, where the fit without standardize had 0.18. Past the warm-up a box or a sum bounds the coefficients in the caller’s units and is projected as for sgd(). The scaler reads each row in the stream’s own unit of weight, one row’s of the stream, and its history keeps at least that weight into any row, as for sgd() (Decay and the rate there). The step is divided by the row’s scale, and after a long gap a history decayed to almost nothing read the row against a scale of one row: over rows 6 to 100 after a gap of 30 half-lives or more the error at the 99th percentile over seeds was up to 6,000 times that of the same stream with no gap, and is now within 1.1 times of it. At weights of 1/8 on 8 features the row, read at weight 1, was too large a share of the moments, and the error was 1,720 noise variances; read in the stream’s unit it is 0.097, and at constant weights of 1 or more every prediction is the one at weights of 1, to the bit.