LazyFrame.online.fit_predict¶
- LazyFrameOnlineNamespace.fit_predict(specs: Iterable[dict[str, Any]] | None = None, *, load_state: str | PathLike[str] | ModelBank | None = None, save_state: str | PathLike[str] | None = None, closed_groups: str | PathLike[str] | None = None, chunk_size: int | None = None, threads: int | None = None) LazyFrame[source]¶
Add each spec’s output column to a query’s rows, learning the rows as the query runs.
Use it for a stream too large to hold in memory, or to fit inside a query that goes on to filter, join or write the result. For a frame already in memory, use
df.online.fit_predict. To keep the bank and feed it more chunks later, usefit_predict_batches(), and to learn without keeping the output,fit().Parameters
specsThe specs of a model bank that starts with nothing learned, as
ModelBanktakes them. Leave it out to resume fromload_state. Given withload_state, they are checked against the specs the state was saved with.load_stateA bank to resume from: the path of a saved state, or a
ModelBank. The file is read, or the bank copied, when the query is built, so a bank given here never moves, and each run of the query starts from the same state.save_stateThe path to write the state the run ends in, after the last row the query gave the bank. The write is atomic (
save()): the file is the old state or the new one, never half of either, so it may beload_state’s path. Nothing is written unless the query gives its last row (see Notes). A rerun whoseload_statethis query already wrote learns the same rows twice, and Notes say how to name the states so that it does not.closed_groupsThe path of a file to write the groups that closed during the run to (
closed_groups()), in the format its extension names. It needs a spec withgroup_close. The bank’s queue of closed groups is emptied after every chunk, so the bank’s memory stays bounded. The file is written once per run, undersave_state’s rules and before it. A run in which no group closed writes an empty frame with the schema. A CSV holds each list column, such ascoef, as JSON text, the bytes the command line writes: read it back withstr.json_decode.chunk_sizeHow many rows the bank learns at a time: 100,000 by default. Memory grows with a chunk and the bank’s state, never with the length of the stream. A chunk’s size never changes the numbers, only which rows
coefis written on: each group’s last row in each chunk.threadsHow many threads the bank runs on, as
ModelBanktakes it.None, the default, shares the process’s threads. A bank given asload_statekeeps its own count unless one is given here. The output is the same at any count. The threads Polars reads the input with are set byPOLARS_MAX_THREADS.
Returns
A query holding the input’s rows, in their order, with one output column added per spec, named after the spec. Its fields are what
fit_predict()writes, whichpolars_online.specdescribes under What a spec writes. The rows must arrive in each group’s clock order, as for the bank.Raises
While the query is built, as Polars reports its own schema errors:
ValueErrorWhen:
neither
specsnorload_stateis given;chunk_sizeorthreadsis below 1;the bank refuses a spec;
a column a spec reads shares the spec’s name, with the message of
fit_predict();closed_groups’s extension names no format, or no spec hasgroup_close;load_stateis not a state this build loads, or was saved with specs other thanspecs(load()).
ColumnNotFoundErrorA column a spec reads is not in the query. It is a
ValueErrortoo.WrongTypeErrorA column a spec reads is of a type its role cannot take, such as a text feature, with the messages of
fit_predict(), or a column isUInt128, which no frame can carry into the bank. It is both aTypeErrorand aValueError.TypeErrorthreadsis not an integer.FileNotFoundErrorload_stateis not there, or the directory ofsave_stateorclosed_groupsis not.IsADirectoryErrorsave_stateis a directory.OrderNotGuaranteedWarningA warning, not an error: the query has a step whose row order Polars does not guarantee when it runs a query a chunk at a time, which the warning names.
While the query runs, an error the rows’ values cause (a null clock, a negative weight, a step back): under py-polars 1.x it arrives as Polars’
ComputeErrorcarrying the bank’s message, and under 2.0 as the bank’sValueErroritself, since how a query wraps an error is Polars’ to change. Asave_statethat cannot be written when the run ends is reported the same way, as theOSErrorthat names the path, wrapped under 1.x.Examples
This code reads
lffrom Example data:spec = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0) fitted = lf.online.fit_predict([spec], save_state="fit.state").collect() # Every field as a column of its own, coef as one column per coefficient. flat = lf.online.fit_predict([spec]).online.unnest([spec]).collect() print(fitted.columns[-1], flat.select("^coef_.*$").columns)
ridge ['coef_y_intercept', 'coef_y_x0', 'coef_y_x1']
See also
df.online.fit_predict, the same over a frame in memory.fit_predict_batches(), the same with a bank you keep.predict(), which predicts and learns nothing.unnest(), which turns each field into a column.polars_online.fit_predict(), this method as a function a type checker can see.
Notes
The query is pure: every run starts from the same state, the specs’ or
load_state’s, so running it twice gives the same frame. Sosave_state’s write gives the same bytes whenever it happens. Polars runs a query’s source once per run, and twice when one query uses it twice (a self-join,pl.concat, orpl.collect_allof two queries that write files), and each run writes the same bytes. Nothing is written unless the query gives its last row: a run abandoned before then, or one the bank ended with an error, leaves the file as it was. An error in a step after the bank does not stop the bank, so the state is written then. Where the output and the state must be written together or not at all, use the command line, which saves the state only after its output is written. Aclosed_groupsfile that cannot be written still leaves the state saved before its error is raised.To rerun a day’s input without learning its rows twice, name the state’s path after the input the run learned, such as
state-2026-11-07for that day’s files, and pass the previous day’s state asload_state. A rerun then starts from the state before that day.Polars pushes a filter, a selection or a
headapplied after the bank into it. A filter never changes what the bank learns from: to keep the bank from learning rows, give them weight 0 in the spec’sweightcolumn. A filter before the bank makes Polars hold several blocks of each parquet file per thread, where one after the bank keeps the query running a chunk at a time. A selection is read from the input, so a wide file read as a query gives only the columns the specs and the query need.head(n)feeds the bank the firstnrows and no more.Unnest a wide spec before writing the result with
sink_parquet(). Polars’ parquet writer encodes an output column’s fields at several times the cost of the same values as plain columns. Anew_covover 20 series writes 233 fields: 2,785 ns a row as one output column, 365 unnested, where the bank’s own work is 550. Over 50 series, 1,328 fields, the output column took 44,642 ns a row against 2,914, and the writer set the run’s pace. So writelf.online.fit_predict([spec]).online.unnest([spec]).sink_parquet(path).sink_ipc()writes the output column at about the cost of plain columns.An online model learns in row order, so the order Polars delivers the rows in is part of the result. Polars runs this query a chunk at a time, where a
join,group_by,uniqueor a sort by several keys without an order guarantee delivers a different stream thanlf.collect()gives, and may differ between runs. Give a joinmaintain_order="left", agroup_bymaintain_order=True, a sort by several keysmaintain_order=True, and sort after aunique, or sort before the bank.