polars_online.spec.ftrl

polars_online.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, and sgd() for other losses.

Parameters

The stream parameters every builder takes, such as clock, half_life, gap_cap, min_weight, group and the diagnostics, are in polars_online.spec. None of alpha, beta, l1 and l2 is free of units (Units in Notes). This model’s own:

alpha

The 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 alpha follows a break sooner, and moves more from row to row once the fit has reached its steady state (Breaks in Notes).

beta

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

l1

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

l2

The 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 / alpha of 10. Finite and at least 0.

strict_binary

Under loss = "logistic", make a call that reads the target (a call that learns, or predict) refuse a chunk whose target is not 0 or 1, naming the row, before any model learns from it. Default False: 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: pred is a probability. "squared" for a continuous target: pred is the linear prediction, and the model is a sparse linear regression with no solves and the L1 support ewridge() does not have. The two differ in the link, and in how the target is read: "logistic" clamps it into [0, 1], takes strict_binary and refuses a formula target. The gradient is (p - y) * z either way.

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, 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", 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 (polars_online.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 polars_online.spec describes them. Under "logistic", emit_metrics reads 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 and ic_<slot> the point-biserial correlation.

Raises

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

  • a loss other than "logistic" or "squared";

  • an alpha not finite or not above 0, and a beta, l1 or l2 not finite or below 0;

  • strict_binary beside "squared";

  • under "logistic", a formula target: the model fits a probability to a 0/1 target.

And, from a call that learns or predict, ValueError for a chunk with a target other than 0 or 1 under strict_binary, naming the row.

The update

Here z is the row’s features, with the intercept’s 1 under fit_intercept, w its weight, y the target, and zz, n and d the sums kept per coefficient i. λ = 0.5 ** (Δclock / half_life) (lam ** Δclock under lam) is the decay since the last row the target was learned from, Δclock the clock’s step since then, each step capped at gap_cap (or session_gap at 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_i

b holds the coefficients, p is the prediction made before the row is learned, and r_i is coefficient i’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 x0 and none on x1, and prints the coefficients found. The L1 penalty zeroes x1’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 = po.spec.ftrl(
    "click", targets=["y"], features=["x0", "x1"], half_life=float("inf"),
    l1=50.0,                              # zeroes a coefficient whose evidence is below it
)
bank = po.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), f the decay factor over one row’s clock. Under loss="squared" at the default alpha, beta and l2, one row a clock unit, a constant 5 is fitted at 4.65 at half_life = 100 and 4.96 at 1000. Without a half-life the fit is the FTRLProximal of 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, f the 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 about alpha in one row. So D / (2 * alpha * sqrt(1 - f)) estimates the rows a break that moves a coefficient by D takes to follow, and is not a bound. Under loss="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 and alpha from 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 under loss="squared" on two features at half_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:

alpha

at 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 larger alpha follows a break sooner, and it moves more from row to row at its steady state: at alpha = 1 the 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, and alpha = 1 came 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, at half_life = 100 and 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 l1 and l2 sooner (tests/test_second_opinion.py holds the fit to Vowpal Wabbit’s, weighted). l1, l2 and beta are 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 is l1 / W for the weight W the 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, use lasso().

Units. A coefficient is zz_i over r_i + l2, and g_i is the target (a probability, under the logistic loss) times the feature, at the row’s weight. So beta is in the units of sqrt(n_i), a gradient, alpha in the coefficient’s, the target per unit of the feature, l1 in the summed gradient’s, and l2 in r_i’s, the feature squared. With fit_intercept=False, every feature scaled by c fits the same model at alpha / c, beta * c, l1 * c and l2 * 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. ftrl does not center a feature. A coefficient’s error reaches the prediction multiplied by the feature’s value, so a feature that sits at a level L carries it at L times its size. On the stream of crates/online-core/tests/held_values.rs, with one of three features at L, the squared loss’s error is about 0.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 no standardize here because l1 zeroes 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.