polars_online.ModelBank.save¶
- ModelBank.save(file: str | PathLike[str] | IO[bytes]) None[source]¶
Write the bank’s state to a file that
load()reads on any supported OS.Use it to keep what a bank has learned, to resume it later or to serve from it. For the bytes without a file, use
save_bytes(), and to read a state outside this library, usewrite_json().Warning
A spec’s formula target (an expression in
targetsholding a window operator ofpolars_online.opsthat looks ahead) is written into the file in a form that is unstable: it may change in any release without that counting as a breaking change. The rest of the file’s form is kept from release to release.Parameters
fileA path, or a file object opened for binary writing, such as
open(..., "wb")or anio.BytesIO, as Polars’write_*methods take either. A path is replaced safely: an interrupted save leaves the file that was there before (see Notes). A file object is handed the bytes in onewrite, and whether that write can be interrupted is up to whoever opened it.
Raises
OSErrorThe file cannot be written, with the path in the message:
FileNotFoundErrorfor a folder that does not exist,PermissionErrorfor one that cannot be written. A file that was there is left untouched.TypeErrorfileis neither a path nor a binary file object.ValueErrorA refused chunk left the bank unable to go on (
fit_predict(), Notes).RuntimeErrorA call that learns is in flight on another thread.
UnstableWarningA warning, not an error, issued only under
POLARS_ONLINE_WARN_UNSTABLE=1: a spec holds a formula target, whose written form is unstable.
Examples
This code reads
dffrom Example data:spec = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0) bank = po.ModelBank([spec]) bank.fit_predict(df) bank.save("bank.state") # a path, replaced safely print(po.ModelBank.load("bank.state").rows_fed)
400
See also
load(), which reads the file back.save_bytes()andwrite_json(), the state as bytes and as JSON.
Notes
The state is versioned MessagePack. A path is written to a temporary file beside it, synced to the disk, and renamed into place, so a power loss cannot leave an empty file where a good state was. The sync takes about 4 ms on macOS, against about 0.1 ms to write a state of 396 KiB. In the same measurement, on a Mac, a whole save of 500 groups (encoding the state, writing it and renaming it) took 5.0 ms with the sync and 0.5 ms without it. A save after every chunk is dominated by the sync, and a save after every hundredth chunk is not.