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, use write_json().

Warning

A spec’s formula target (an expression in targets holding a window operator of polars_online.ops that 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

file

A path, or a file object opened for binary writing, such as open(..., "wb") or an io.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 one write, and whether that write can be interrupted is up to whoever opened it.

Raises

OSError

The file cannot be written, with the path in the message: FileNotFoundError for a folder that does not exist, PermissionError for one that cannot be written. A file that was there is left untouched.

TypeError

file is neither a path nor a binary file object.

ValueError

A refused chunk left the bank unable to go on (fit_predict(), Notes).

RuntimeError

A call that learns is in flight on another thread.

UnstableWarning

A 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 df from 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

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.