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
Datasetfrom 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.traintakes 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, usexgboost_matrix().Parameters
sourceThe rows: Arrow IPC or Parquet paths (globs taken, all of one kind), a
LazyFrame, or aDataFrame. 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,weightThe 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.
weightisNoneby default, for rows of weight 1.featuresThe 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.categoricalThe categorical features,
pl.Enum, integer or Boolean columns (a code below 0 is missing, as LightGBM reads it).None, the default, takes everypl.Enumfeature. Apl.Enumleft out goes in as its codes, a number.max_binBins per feature, LightGBM’s
max_bin, 255 by default as in LightGBM.paramsOther 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, … Notmax_bin,categorical_featureornum_threads, which are this function’s own arguments.Noneby 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.referenceThe 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
referencebuilt here must have eachpl.Enumfeature of the same categories in order, since a code is read as the training level at that position. Areferencebuilt elsewhere is checked by its feature names alone. Given areference, this call’smax_bin,paramsandcategoricalare checked as usual but not used: the dataset takes the reference’s bins, parameters and categorical features.init_scoreThe 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 skipsboost_from_average, its own constant start.Noneby default, for no margin. A number a row, or for a K-class objective aListorArrayof 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_memoryholds every row’s,n · Kfloat64 values fornrows, as it holds the labels.engine="python"holds them too, because LightGBM’s PythonDatasettakesinit_scorewhole: 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 tobooster.predict(X, raw_score=True). So areferencebuilt with a margin needs one here, with as many values a row, and areferencebuilt without one needs none.in_memoryWhether 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.
Truealways does,Falsenever 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).threadsThe 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 eachpl.Enumfeature’s categories and the margin’s width, for the checks of a dataset built later with it asreference.Raises
WrongTypeErrormax_binorthreadsis not a whole number; a feature, the label, the weight or the margin is of a type LightGBM does not read, apl.Categoricalamong them; orcategoricalnames a float column. It is both aTypeErrorand aValueError.ColumnNotFoundErrorA column named is not in the source. It is both Polars’
ColumnNotFoundErrorand aValueError.TypeErrorreferenceis not alightgbm.Dataset(one not yet constructed is constructed here),sourceis of another type, orfeaturesorcategoricalis one name in place of a list.FileNotFoundErrorA glob of local files matches nothing.
ValueErrorWhen, each named in the message:
max_binbelow 2,threadsbelow 1 or above its bound, anenginenot one of the three, or anin_memorythat is notTrue,Falseor"auto";a parameter in
paramsthat 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
featuresleft out, a source with no column besides the label, the weight and the margin;a
categoricalname 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
referencethat records other features, or built here on apl.Enumof other categories;a
referencebuilt with a margin and noinit_scorehere, orinit_scorehere and areferencebuilt without one;under
engine="native", a LightGBM the native engine cannot load;in_memory=Trueunder the native engine with a LightGBM before 4.7.0, which takes no Arrow stream (engine="auto"does not fall back on it).
RuntimeErrorUnder the Python engine, LightGBM asks for the rows out of order, which a source read in order cannot give: pass
in_memory=True.UserWarningUnder
engine="auto", the native engine cannot load LightGBM, and the Python engine builds the dataset.UnstableWarningUnder
POLARS_ONLINE_WARN_UNSTABLE=1, on each call (the module’s warning says why).
Examples
This code reads
ticks/*.parquetandtoday.parquetfrom 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
xgboost_matrix(), XGBoost’s training input from the same sources.Training XGBoost and LightGBM, the guide: training around an online model’s prediction as the margin, and serving with it.
Notes
LightGBM places each feature’s bins from a sample of
bin_construct_sample_cntrows (200,000 by default), drawn from the row count anddata_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. Within_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_DatasetCreateFromSampledColumnnor theBinMapper::FindBinit 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 andmax_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.gbdtdescribes, 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_memory1.45
2.9
LightGBM’s own route from a Polars frame in memory
1.54
8.9
LightGBM’s
Sequence2.17
2.7