polars_online.gbdt.xgboost_matrix

polars_online.gbdt.xgboost_matrix(source: Source, *, label: str, weight: str | None = None, features: Sequence[str] | None = None, max_bin: int = 256, sample_rows: int | None = 200000, ref: xgboost.DMatrix | None = None, base_margin: str | None = None, threads: int | None = None, seed: int = 0, engine: Engine = 'auto') → xgboost.QuantileDMatrix[source]

Build XGBoost’s QuantileDMatrix from files or a query, binned as the rows stream.

Use it to train XGBoost on Arrow IPC files, Parquet files or a query whose result does not fit in memory: xgb.train takes the matrix as it is, with its evaluation sets, early stopping and callbacks. For data already in memory, XGBoost’s own xgb.QuantileDMatrix over a numpy array grows the same trees as sample_rows=None here. For LightGBM, use lightgbm_dataset().

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, XGBoost’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.

max_bin

Bins per feature, XGBoost’s max_bin, 256 by default as in XGBoost. Pass the same to xgb.train.

sample_rows

The rows of the sample the cuts are placed from, 200,000 by default. None lets XGBoost sketch every row, and grows XGBoost’s own trees at about twice the time before the first round (Notes). Not read with ref.

ref

The training matrix, for a validation or test matrix binned on its cuts (xgb.train refuses a QuantileDMatrix evaluation set without it). It must have the same features in order, and a ref 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 ref built elsewhere is checked by its feature names alone. The matrix returned keeps a weak reference to it.

base_margin

The column of each row’s margin, XGBoost’s base_margin: the raw score the row’s prediction starts from, in place of XGBoost’s constant base_score, so that the trees fit what the margin leaves of the label. 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 (XGBoost keeps it as float32). Each chunk’s margin goes to XGBoost with its labels, so the margin is never held whole. The cuts 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 XGBoost does not warn. Build the matrix to predict on with its rows’ margin too, as xgb.DMatrix(X, base_margin=m) or a matrix built here with ref and base_margin. So a ref built with a margin needs one here, with as many values a row, and a ref built without one needs none.

threads

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

seed

The seed of the sample, 0 by default: the same seed and rows give the same cuts.

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 XGBoost. Both grow the same trees. The module’s The native engine says how each reads the rows.

Returns

An xgboost.QuantileDMatrix: the features binned, the labels, the weights and the margin. It records each pl.Enum feature’s categories and the margin’s width, for the checks of a matrix built later with it as ref.

Raises

WrongTypeError

max_bin, threads, sample_rows or seed is not a whole number; or a feature, the label, the weight or the margin is of a type XGBoost does not read, a pl.Categorical among them. 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

ref is not an xgboost.DMatrix, source is of another type, or features 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 or sample_rows below 1, a threads above its bound, a seed outside 0 to 2**64 - 1, or an engine not one of the three;

  • 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 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 ref’s margin;

  • an empty source, or one whose passes give different rows;

  • a ref binned on other features, or built here on a pl.Enum of other categories;

  • a ref built with a margin and no base_margin here, or base_margin here and a ref built without one;

  • under engine="native", an XGBoost the native engine cannot load.

UserWarning

Under engine="auto", the native engine cannot load XGBoost, and the Python engine builds the matrix.

UnstableWarning

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

Examples

This code reads df from Example data, and writes it to Arrow IPC files, which the native engine reads itself:

import xgboost as xgb

df.head(300).write_ipc("train.arrow")              # the example data, as two Arrow files
df.tail(100).write_ipc("valid.arrow")
features = ["x0", "x1", "x2", "signal_a", "signal_b"]
train = po.gbdt.xgboost_matrix("train.arrow", label="y", features=features)
valid = po.gbdt.xgboost_matrix("valid.arrow", label="y", features=features, ref=train)
booster = xgb.train({"tree_method": "hist", "max_bin": 256}, train, 500,
                    evals=[(valid, "valid")], early_stopping_rounds=20, verbose_eval=False)
rows, cols = train.num_row(), train.num_col()
print(f"{rows} rows of {cols} features, {valid.num_row()} to validate")
300 rows of 5 features, 100 to validate

See also

Notes

XGBoost places each feature’s bins at its quantiles and reads the input in passes: it counts the values, sketches the quantiles over every row, indexes each value into its bin and builds the column matrix.

The cuts. With sample_rows, one pass first draws a sample of that many rows. Row i has a hash h, SplitMix64 of i and seed, and the priority w / u, where w is its weight (1 without weight) and u = (2h + 1) / 2**65. The sample_rows rows of largest priority are kept. Without weights these are the rows of smallest hash, a uniform sample. With weights it is priority sampling: a row heavier than tau, the largest priority not kept, is always kept and counts its own weight, and any other kept row counts tau. Summed over any set of rows, these counts estimate the set’s weight without bias, so the sample’s weighted quantiles estimate the source’s. A row of weight 0 counts for nothing and places no cut. The sample is drawn in proportion to the weights, not uniformly, because a uniform sample loses heavy rows. Under a weight of 1e9 on one row in a million, a uniform sample of 200,000 rows misses that row four times in five, and its cuts ignore it.

Each feature’s bin edges sit at the sample’s weighted quantiles. A feature with at most max_bin distinct sample values gets a bin per value. Any other gets max_bin bins of equal weight. Edge j is the first sorted sample value whose running weight exceeds j / max_bin of the total. Without weights that is the value of rank floor(j m / max_bin) for m values. At the quantile q, a cut’s share of the weight then errs by about sqrt(q (1 - q) / sample_rows), 0.11% at the median for 200,000 rows. Over ten seeds on a million rows, its standard deviation measured 0.29% to 0.46% with 20,000 rows, where the formula gives 0.35%, and 0.04% with 200,000 rows under weight 50 on a sixth of them. The cuts reach XGBoost as a ref, which removes its sketch pass. The sample is the same rows however the source is batched and whichever engine reads it. sample_rows=None lets XGBoost sketch every row, and grows XGBoost’s own trees.

Measured as polars_online.gbdt describes, on 10 million rows of 50 features: the time before the first round, and the peak memory. Reading ahead, Polars holds 7.2 GB at the peak on the query route, and Bound a run’s memory cuts it.

route

seconds

peak, GB

this, from Arrow IPC files

4.0

3.6

this, from a LazyFrame over them

4.2

7.2

this, engine="python"

5.5

7.1

this, sample_rows=None

8.0

3.6

XGBoost’s own DataIter over Polars’ chunks

8.7

4.8

collect() and numpy

7.0

8.7