polars_online.gbdt.lightgbm_dataset

polars_online.gbdt.lightgbm_dataset(source: Source, *, label: str, weight: str | None = None, features: Sequence[str] | None = None, categorical: Sequence[str] | None = None, max_bin: int = 255, params: dict[str, Any] | None = None, reference: lightgbm.Dataset | None = None, init_score: str | None = None, in_memory: bool | Literal['auto'] = 'auto', threads: int | None = None, engine: Engine = 'auto') → lightgbm.Dataset[source]

Build a constructed LightGBM Dataset from files or a query, binned on LightGBM’s own sample.

Use it to train LightGBM on Arrow IPC files, Parquet files or a query whose result does not fit in memory: lgb.train takes the dataset as it is, with its validation sets, early stopping and callbacks. It grows the trees LightGBM’s own route grows from a float32 array of the data. For XGBoost, use xgboost_matrix().

Parameters

source

The rows: Arrow IPC or Parquet paths (globs taken, all of one kind), a LazyFrame, or a DataFrame. A query is run once for each pass, its result taken one chunk at a time. The native engine reads Arrow IPC files itself, one block of the file at a time.

label, weight

The columns of the label, LightGBM’s word for the target, and of the row weights: numeric or Boolean, with no nulls and finite values, and a weight never negative. weight is None by default, for rows of weight 1.

features

The feature columns, in order: numeric, Boolean or pl.Enum (the module’s What the columns may hold says what each may hold). None, the default, takes every column but the label, the weight and the margin.

categorical

The categorical features, pl.Enum, integer or Boolean columns (a code below 0 is missing, as LightGBM reads it). None, the default, takes every pl.Enum feature. A pl.Enum left out goes in as its codes, a number.

max_bin

Bins per feature, LightGBM’s max_bin, 255 by default as in LightGBM.

params

Other dataset parameters, as lightgbm.Dataset(params=) takes them: verbose, min_data_in_bin, bin_construct_sample_cnt, data_random_seed, use_missing, zero_as_missing, … Not max_bin, categorical_feature or num_threads, which are this function’s own arguments. None by default. Training may not change a dataset parameter, since the dataset is constructed and its raw data is not kept: LightGBM refuses, as it does for any constructed dataset.

reference

The training dataset, for a validation dataset binned on its bins, built in one pass. It must have the same features in order, when it records its feature names. A reference built here must have each pl.Enum feature of the same categories in order, since a code is read as the training level at that position. A reference built elsewhere is checked by its feature names alone. Given a reference, this call’s max_bin, params and categorical are checked as usual but not used: the dataset takes the reference’s bins, parameters and categorical features.

init_score

The column of each row’s margin, LightGBM’s init_score: the raw score the row’s prediction starts from, so that the trees fit what the margin leaves of the label. LightGBM then skips boost_from_average, its own constant start. None by default, for no margin. A number a row, or for a K-class objective a List or Array of K numbers a row, one for each class; any numeric type, read as float64. The native engine’s two passes push each chunk’s margin with its rows, so the margin is never held whole. in_memory holds every row’s, n · K float64 values for n rows, as it holds the labels. engine="python" holds them too, because LightGBM’s Python Dataset takes init_score whole: 80 MB for 10 million rows of one class, and K times that for K classes. The bins do not read it. A tree cannot predict outside the range of labels it split on, and a margin is added after it. So an online model’s prediction as the margin carries a level the training rows never reached, and since that prediction is out-of-sample, it leaks nothing from the row’s own label. Predict with a margin a model trained with one, or every prediction lacks the level the margin carried, and LightGBM does not warn: add the rows’ margin to booster.predict(X, raw_score=True). So a reference built with a margin needs one here, with as many values a row, and a reference built without one needs none.

in_memory

Whether to hand LightGBM the whole stream at once, held in memory: as Arrow under the native engine, as a float32 numpy array under the Python one. True always does, False never does, and "auto", the default, does when the features as float32 take at most a quarter of the memory available and, under the native engine, the LightGBM loaded takes an Arrow stream (4.7.0 on).

threads

The threads for LightGBM’s construction and the conversions. None, the default, is LightGBM’s default, every core. At most 1024, or the machine’s cores where it has more: more threads than cores run no faster.

engine

"native", "python", or "auto", the default: the native engine, falling back to the Python engine with a warning when the native engine cannot load LightGBM. Both grow the same trees.

Returns

A constructed lightgbm.Dataset: the features binned, the labels, the weights and the margin (init_score), with its raw data freed. It records each pl.Enum feature’s categories and the margin’s width, for the checks of a dataset built later with it as reference.

Raises

WrongTypeError

max_bin or threads is not a whole number; a feature, the label, the weight or the margin is of a type LightGBM does not read, a pl.Categorical among them; or categorical names a float column. It is both a TypeError and a ValueError.

ColumnNotFoundError

A column named is not in the source. It is both Polars’ ColumnNotFoundError and a ValueError.

TypeError

reference is not a lightgbm.Dataset (one not yet constructed is constructed here), source is of another type, or features or categorical is one name in place of a list.

FileNotFoundError

A glob of local files matches nothing.

ValueError

When, each named in the message:

  • max_bin below 2, threads below 1 or above its bound, an engine not one of the three, or an in_memory that is not True, False or "auto";

  • a parameter in params that is this function’s own argument;

  • a source that names no files, mixes Arrow IPC and Parquet, or names a file whose extension says neither;

  • a column named twice, or as both a feature and the label, weight or margin, or an empty features;

  • with features left out, a source with no column besides the label, the weight and the margin;

  • a categorical name that is not a feature;

  • a null or non-finite label or weight, or a negative weight;

  • a null or non-finite margin, or a row whose number of margin values differs from the first row’s or from the reference’s margin;

  • an empty source, more rows than LightGBM’s 32-bit row count holds, or a source whose passes give different rows;

  • a reference that records other features, or built here on a pl.Enum of other categories;

  • a reference built with a margin and no init_score here, or init_score here and a reference built without one;

  • under engine="native", a LightGBM the native engine cannot load;

  • in_memory=True under the native engine with a LightGBM before 4.7.0, which takes no Arrow stream (engine="auto" does not fall back on it).

RuntimeError

Under the Python engine, LightGBM asks for the rows out of order, which a source read in order cannot give: pass in_memory=True.

UserWarning

Under engine="auto", the native engine cannot load LightGBM, and the Python engine builds the dataset.

UnstableWarning

Under POLARS_ONLINE_WARN_UNSTABLE=1, on each call (the module’s warning says why).

Examples

This code reads ticks/*.parquet and today.parquet from Example data, the training rows by a glob:

import lightgbm as lgb

features = ["x0", "x1", "x2", "signal_a", "signal_b"]
train = po.gbdt.lightgbm_dataset("ticks/*.parquet", label="y", features=features,
                                 params={"verbose": -1})
valid = po.gbdt.lightgbm_dataset("today.parquet", label="y", features=features,
                                 reference=train)
booster = lgb.train({"objective": "regression", "verbose": -1}, train, 500,
                    valid_sets=[valid],
                    callbacks=[lgb.early_stopping(20, verbose=False)])
rows, cols = train.num_data(), train.num_feature()
print(f"{rows} rows of {cols} features, {valid.num_data()} to validate")
400 rows of 5 features, 400 to validate

See also

Notes

LightGBM places each feature’s bins from a sample of bin_construct_sample_cnt rows (200,000 by default), drawn from the row count and data_random_seed, and then pushes every value into its bin. Here the source is counted (select(pl.len())), a first pass gathers the rows LightGBM samples, and a second pushes every row as float32, built in parallel: two passes, and the data never held. With in_memory, one pass holds the features as float32 Arrow and hands LightGBM the whole stream, which it pushes column by column. Both routes hand LightGBM the same float32 values and grow the same trees, which are LightGBM’s own from a float32 array of the data.

Weights do not move the bins, in LightGBM or here. LightGBM’s sample is uniform, and neither LGBM_DatasetCreateFromSampledColumn nor the BinMapper::FindBin it calls takes a weight, so its bins are those of the unweighted rows. xgboost_matrix() weights its cuts, because XGBoost’s own sketch does: each builds what its library builds. With weight 50 on the values above 1.0 of 50,000 normal ones and max_bin=16, LightGBM’s trees split at the same 14 bounds with the weights as without, 2 of them above 1.0, where 14 of XGBoost’s 15 cuts are.

Measured as polars_online.gbdt describes, on 10 million rows of 50 features from Arrow IPC files: the time before the first round, and the peak memory.

route

seconds

peak, GB

this, streamed in two passes

1.68

1.7

this, in_memory

1.45

2.9

LightGBM’s own route from a Polars frame in memory

1.54

8.9

LightGBM’s Sequence

2.17

2.7