rheon.spec.ftrl¶
- rheon.spec.ftrl(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], features: list[str], alpha: float | None = None, beta: float | None = None, l1: float | None = None, l2: float | None = None, strict_binary: bool = False, loss: Literal['logistic', 'squared'] = 'logistic', **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Logistic regression for a 0/1 target, or a sparse linear regression, by FTRL-proximal.
Use it for a 0/1 target, or where an L1 penalty should zero the coefficients of features with too little evidence: it is McMahan et al.’s (2013) algorithm, the standard for click prediction, with a learning rate per coefficient. Use
lasso()for an L1 penalty on the mean scale, which more rows or heavier ones do not outweigh, andsgd()for other losses.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weight,groupand the diagnostics, are inrheon.spec. None ofalpha,beta,l1andl2is free of units (Units in Notes). This model’s own:alphaThe learning-rate scale, in a coefficient’s units: the target (log-odds, under the logistic loss) per unit of the feature. Default 0.1, which keeps a coefficient’s first step under 0.1 in its units. Finite and above 0. A larger
alphafollows a break sooner, and moves more from row to row once the fit has reached its steady state (Breaks in Notes).betaThe learning rate’s smoothing, which keeps the first steps from being too large, in a gradient’s units: the target times the feature. Default 1.0, the value McMahan et al. suggest. Finite and at least 0.
l1The L1 penalty, which zeroes a coefficient whose summed evidence is below it, in the summed gradient’s units. Default 0.0, no L1 penalty. Finite and at least 0. It weighs against the rows’ summed evidence, not a mean (Weights and the penalties in Notes).
l2The L2 penalty, which shrinks every coefficient toward zero as a ridge does, in the feature’s squared units. Default 1.0, which adds a tenth to the default prior’s
beta / alphaof 10. Finite and at least 0.strict_binaryUnder
loss = "logistic", make a call that reads the target (a call that learns, orpredict) refuse a chunk whose target is not 0 or 1, naming the row, before any model learns from it. DefaultFalse: such a target is clamped into[0, 1]. Refused beside"squared", which reads the target as it stands.loss"logistic"(the default) for a 0/1 target:predis a probability."squared"for a continuous target:predis the linear prediction, and the model is a sparse linear regression with no solves and the L1 supportewridge()does not have. The two differ in the link, and in how the target is read:"logistic"clamps it into[0, 1], takesstrict_binaryand refuses a formula target. The gradient is(p - y) * zeither way.
min_weightcounts the rows the target was present on, at their weights, decayed, whereweight_sumcounts every row. So rows with a null target do not warm up coefficients they never moved, and neither does a row the model does not learn from because its squared gradient would overflow.Output
One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#ftrl gives each field’s type and when it is null:
pred_<t>,resid_<t>Per target: the prediction, a probability under
"logistic", andy - predwhere the target is not null.weight_sumThe weight the model has accumulated before the row and before the row’s own decay.
settled_fracHow far the model had come toward its steady state under decay before the row.
withheld_reasonWhy the row’s predictions were withheld, null where they were not: a reason of the shared gates (
rheon.spec), such asbelow_min_weighton the first rows under the defaultmin_weight.coefPer 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.specdescribes them. Under"logistic",emit_metricsreads the fit as probabilities against the 0/1 targets, in its own fields:hit_rate_<slot>is the accuracy at 0.5,r2_<slot>the Brier skill score andic_<slot>the point-biserial correlation.Raises
As every builder does (
rheon.spec), andValueErrornaming the problem for:a
lossother than"logistic"or"squared";an
alphanot finite or not above 0, and abeta,l1orl2not finite or below 0;strict_binarybeside"squared";under
"logistic", a formula target: the model fits a probability to a 0/1 target.
And, from a call that learns or
predict,ValueErrorfor a chunk with a target other than 0 or 1 understrict_binary, naming the row.The update
Here
zis the row’s features, with the intercept’s 1 underfit_intercept,wits weight,ythe target, andzz,nanddthe sums kept per coefficienti.λ = 0.5 ** (Δclock / half_life)(lam ** Δclockunderlam) is the decay since the last row the target was learned from,Δclockthe clock’s step since then, each step capped atgap_cap(orsession_gapat a session change):b_i = 0 if |zz_i| <= l1 else -(zz_i - sign(zz_i) l1) / (r_i + l2) r_i = beta / alpha + d_i (under a half-life) = (beta + sqrt(n_i)) / alpha (without one: river's closed form) p = sigmoid(z . b) (z . b itself under loss="squared") n_i <- λ * n_i ; zz_i <- λ * zz_i ; d_i <- λ * d_i (on a row the target is learned from) g_i = (p - y) * z_i * w s_i = (sqrt(n_i + g_i^2) - sqrt(n_i)) / alpha zz_i += g_i - s_i * b_i ; n_i += g_i^2 ; d_i += s_ibholds the coefficients,pis the prediction made before the row is learned, andr_iis coefficienti’s rate.Example
This code fits a logistic regression to 0/1 targets drawn with an intercept of 0.5, a slope of 1.5 on
x0and none onx1, and prints the coefficients found. The L1 penalty zeroesx1’s:import numpy as np rng = np.random.default_rng(4) x0, x1 = rng.standard_normal(20_000), rng.standard_normal(20_000) p = 1.0 / (1.0 + np.exp(-(0.5 + 1.5 * x0))) # x1 plays no part y = (rng.random(20_000) < p).astype(float) pl.DataFrame({"x0": x0, "x1": x1, "y": y}).write_parquet("clicks.parquet") click = rp.spec.ftrl( "click", targets=["y"], features=["x0", "x1"], half_life=float("inf"), l1=50.0, # zeroes a coefficient whose evidence is below it ) bank = rp.ModelBank([click]) bank.fit(pl.scan_parquet("clicks.parquet")) # learn every row, keep no output coef = {r["term"]: r["coef"] for r in bank.coef().iter_rows(named=True)} print(f"intercept {coef['intercept']:.2f}, x0 {coef['x0']:.2f}") print(f"x1 is exactly 0: {coef['x1'] == 0.0}")
intercept 0.49, x0 1.52 x1 is exactly 0: True
See also
lasso(), an L1 penalty on the mean scale, solved on running sums.sgd(), gradient steps under other losses.
Notes
Under a half-life. The sums decay on the model’s clock like every other model’s. The fit after a row the target is learned from minimizes FTRL’s objective. That is a fixed regularizer,
l1 |b|_1 + (beta / alpha + l2) |b|^2 / 2, against the rows’ linearized losses and proximal terms, each weighted by its age on the clock. So old evidence counts for less against the prior. In steady state the penalties act as a mean-scale ridge of(1 - f) * (beta / alpha + l2),fthe decay factor over one row’s clock. Underloss="squared"at the defaultalpha,betaandl2, one row a clock unit, a constant 5 is fitted at 4.65 athalf_life = 100and 4.96 at 1000. Without a half-life the fit is theFTRLProximalof the Python library river, to 1e-12 row for row.Breaks. Under a half-life the fit follows a break at the pace of its steps, not of its half-life. A coefficient steps by its gradient over the root of its recent squared gradients. Once those sums hold the break’s large gradients, a coefficient closes on the break at about
2 * alpha * sqrt(1 - f)a row,fthe decay factor over one row’s clock, however large the error. Just after the break, before the sums have grown, it moves faster, by up to aboutalphain one row. SoD / (2 * alpha * sqrt(1 - f))estimates the rows a break that moves a coefficient byDtakes to follow, and is not a bound. Underloss="squared"on one feature with noise of spread 0.3, over breaks of 2 and 20 in the intercept, at half-lives of 200 and 1000 andalphafrom 0.1 to 1 (two seeds each), the rows to close 90% of the break came to 0.37 to 1.54 times the estimate. The large gradients just after a break increase the sums that divide every step for about a half-life. The table was measured underloss="squared"on two features athalf_life = 200, one row a clock unit, after a change of regime that moved the intercept by 46. The table gives the worst of 50 seeds, the largest coefficient gap to the decayed least squares:alphaat its steady state, before the break
4 half-lives after
8 half-lives after
12 half-lives after
0.1, the default
0.17
34.4
28.5
19.9
0.3
0.24
18.4
2.7
0.86
1.0
0.43
2.7
0.61
0.85
At the default the intercept closed at 0.011 a row from 4 to 12 half-lives after the break, against
2 * alpha * sqrt(1 - f)= 0.012. So a largeralphafollows a break sooner, and it moves more from row to row at its steady state: atalpha = 1the gap stops shrinking by 8 half-lives, within twice its steady state’s. Over the 24 half-lives after the noise quadrupled, the default came at most 0.23 from the decayed least squares, andalpha = 1came 1.17 from it.Rows the target is not learned from. The model learns nothing about the target from some rows: a row where it is absent, a row of weight 0, and a row whose squared gradient would overflow. Each leaves the sums as the last row the target was learned from left them. So the fit does not move, as
ewridge()’s does not, and a row of weight 0 moves the clock alone, as in every model. The next row the target is learned from is predicted with that fit, then ages the sums by the whole clock since and learns. The gap ages the evidence and not the prior. The fit of a constant 5, athalf_life = 100and at its steady state (4.65), stands at 0.75 of that fit after that row when the gap was one half-life, and at 0.15 of it when it was five.Weights and the penalties. A row’s weight is an importance weight, as in the learner Vowpal Wabbit: the gradient carries it, against penalties in absolute weight. So a heavier stream overcomes
l1andl2sooner (tests/test_second_opinion.pyholds the fit to Vowpal Wabbit’s, weighted).l1,l2andbetaare a prior of fixed mass against evidence that grows with weight and density, which FTRL’s regret bound rests on. So under a half-life the effective penalty isl1 / Wfor the weightWthe half-life holds, and more rows in a half-life, or heavier ones, outweigh it sooner. For a penalty on the mean scale, invariant to both, uselasso().Units. A coefficient is
zz_ioverr_i + l2, andg_iis the target (a probability, under the logistic loss) times the feature, at the row’s weight. Sobetais in the units ofsqrt(n_i), a gradient,alphain the coefficient’s, the target per unit of the feature,l1in the summed gradient’s, andl2inr_i’s, the feature squared. Withfit_intercept=False, every feature scaled bycfits the same model atalpha / c,beta * c,l1 * candl2 * c**2. The intercept’s 1 does not scale, and the four are shared by every coefficient, so with an intercept there is no such equivalence.Features at a level.
ftrldoes not center a feature. A coefficient’s error reaches the prediction multiplied by the feature’s value, so a feature that sits at a levelLcarries it atLtimes its size. On the stream ofcrates/rheon-core/tests/held_values.rs, with one of three features atL, the squared loss’s error is about0.018 * L: 18.3 at 1,000 and at -1,000, and 1.8e6 at 1e8, against 0.75 at 0.5. Standardize or z-score such a feature before the bank, as Scale a feature by its spread shows. There is nostandardizehere becausel1zeroes a coefficient in the feature’s own units: a scale inside the model would move which coefficients it zeroes as the feature’s spread moved.