polars_online.stream.embargo¶
- polars_online.stream.embargo(lf: LazyFrame, *, clock: str, delay: float | timedelta | str | Expr, weight: str | None = None, role: str = ROLE) LazyFrame[source]¶
- polars_online.stream.embargo(lf: DataFrame, *, clock: str, delay: float | timedelta | str | Expr, weight: str | None = None, role: str = ROLE) DataFrame
Double a stream so that each row’s target is learned
delayafter its row.Use it when a target is a forward quantity, known only
delayclock units after its row, and you want the delay visible in the data: an independent check of a spec’s ownembargo, a demonstration, or a model or engine with noembargoof its own. Otherwise give the specembargo=delay, which does the same in the stream with no second copy of each row, or alabel_clockcolumn when each row’s target becomes known at a time of its own (Notes).Parameters
lfThe stream, a
LazyFrameor aDataFrame, already inclockorder across all its rows, not only within each group. The two copies are merged by the clock alone, so a frame sorted within its groups but not across them comes back with a group’s clock stepping back. Sort it first withlf.sort(clock, maintain_order=True), or embargo each group and concatenate.clockThe clock column: numeric,
Datetime,DateorDuration.delayThe time from predicting a row to learning it, finite and above 0. It is measured as a spec’s clock parameters are: a number of the clock’s own units on a numeric clock, and a duration (
pl.duration(minutes=5), atimedeltaor"5m") on a temporal one. A duration must be a whole number of the column’s own steps, since the learn copy’s clock is the column plus the delay: aDateclock takes whole days, where"12h"would be cut to nothing. On an integer clock a wholedelay,5.0as well as5, keeps the clock’s dtype.weightAn existing weight column, of any numeric dtype, to carry onto the learn rows and set to 0 on the predict rows. It comes back as
Float64, the number a bank reads it as. The default,None, adds a weight column namedrole + "_weight": 1 on learn rows and 0 on predict rows. Pass that name to the spec’sweight=.roleThe name of the column that says which copy a row is,
"predict"or"learn". Default"_online_role"(ROLE).
Returns
The kind of frame it was given, with every row twice, in clock order:
the row
at
carrying
a predict row
clockits weight forced to 0, so the model predicts it and learns nothing from it
a learn row
clock + delaythe same features and target at the row’s own weight (1 without
weight)The columns are the input’s, then the weight column it adds (without
weight), thenrole. At the same clock value a learn row comes before a predict row, since a target whosedelayhas just run out is known at that instant, and a prediction made then may use it. A spec’sembargoreleases in the same order, so the two can be compared row for row. Keep the predictions without.filter(pl.col(role) == "predict").Raises
ColumnNotFoundErrorThe frame has no
clockorweightcolumn of that name. It is both aValueErrorand Polars’ColumnNotFoundError.WrongTypeErrorThe
clockcolumn is neither numeric nor temporal, is an integer wider than 64 bits (Int128), which a bank refuses as a clock, or is aTime, since a time of day starts again at midnight; or, on a numeric clock,delayis neither a number nor a duration, such asNone. It is both aTypeErrorand aValueError.ValueErrorWhen:
delayis not finite and above 0 (0would be the undoubled stream, and a negative delay a target learned before its row);delayis of the wrong kind for the clock, or is not a whole number on an integer clock;delayis a duration that is not a whole number of the clock column’s steps, such as"12h"on aDate;the frame already has a column named
role, or, withoutweight, one namedrole + "_weight".
TypeErrordelayis an expression that reads a column or does not give one duration.polars.exceptions.InvalidOperationErrorWhen the query runs, if an integer clock within
delayof its dtype’s top cannot hold its learn copy. Polars names the column, where wrapping the clock around would put the learn copy before the stream.ConsumedSourceWarningA warning, not an error, issued as the query is built when the input reads a source written in Python (Notes).
Examples
rows = pl.DataFrame({"t": [0.0, 1.0, 2.0]}) doubled = po.stream.embargo(rows, clock="t", delay=1.0) # adds a weight and a role column for row in doubled.rows(): # (t, weight, role) print(row)
(0.0, 0.0, 'predict') (1.0, 1.0, 'learn') (1.0, 0.0, 'predict') (2.0, 1.0, 'learn') (2.0, 0.0, 'predict') (3.0, 1.0, 'learn')
A bank fed the doubled stream learns each row’s target 5 rows late, and the predict rows carry its predictions. This code reads
lffrom Example data:doubled = po.stream.embargo(lf, clock="t", delay=5.0) scored = doubled.online.fit_predict( [po.spec.ewridge("m", targets=["y"], features=["x0"], clock="t", gap_cap=10.0, half_life=50.0, weight="_online_role_weight")] ).filter(pl.col("_online_role") == "predict").collect() pred = scored["m"].struct.field("pred_y") print(scored.height, pred.count()) # predict rows, and those with a prediction
400 393
See also
The spec’s
embargoandlabel_clock(polars_online.spec), which delay the learning inside the bank.Learn targets known late, the how-to: each of the three ways, with a check that it worked.
Notes
A target that is a forward quantity over
delayclock units is not known at the row it sits on. A stream that learns it there has seendelayof the future before predicting the rows in between, and every out-of-sample number after that is contaminated. With an autocorrelated feature, even a pure-noise column shows a correlation with its target. A row of weight 0 is legal and means “advance the clock, learn nothing”, so the doubled stream says what is wanted: predict here, learn later.When each row’s target becomes known at a time of its own, give the spec a
label_clockcolumn of those times rather than doubling by hand. A doubled stream learns the same targets at the same clocks, so its predict rows’ predictions are the ones alabel_clockbank serves. But on each learn row the bank predicts again before learning, and computes every residual diagnostic from that second prediction, not the one the predict row was given. On New York’s 2013 flights its 90% interval covered 88.0% of the delays it was shown while reporting 90.0%.label_clockscores each target against the prediction and interval its row was served.The function reads its input twice, once for each copy, merging the two as they stream. A source that can be read once only, such as what
pl.scan_arrow_c_streambuilds over a DuckDB relation or a pyarrow reader, gives the second read nothing, and half the stream would go missing with no error. Whether a source is spent cannot be seen until the query runs. So where the query reads a source written in Python, as such a stream does, the function issues aConsumedSourceWarningas the query is built. Write such an input to a file and read that file as a query, or pass it as a frame.A bank refuses a doubled stream in which a group’s clock steps back, as it refuses every step back unless
restart_after_step_backsays it is a new start.