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
QuantileDMatrixfrom 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.traintakes the matrix as it is, with its evaluation sets, early stopping and callbacks. For data already in memory, XGBoost’s ownxgb.QuantileDMatrixover a numpy array grows the same trees assample_rows=Nonehere. For LightGBM, uselightgbm_dataset().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, 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.
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.max_binBins per feature, XGBoost’s
max_bin, 256 by default as in XGBoost. Pass the same toxgb.train.sample_rowsThe rows of the sample the cuts are placed from, 200,000 by default.
Nonelets XGBoost sketch every row, and grows XGBoost’s own trees at about twice the time before the first round (Notes). Not read withref.refThe training matrix, for a validation or test matrix binned on its cuts (
xgb.trainrefuses aQuantileDMatrixevaluation set without it). It must have the same features in order, and arefbuilt here must have eachpl.Enumfeature of the same categories in order, since a code is read as the training level at that position. Arefbuilt elsewhere is checked by its feature names alone. The matrix returned keeps a weak reference to it.base_marginThe column of each row’s margin, XGBoost’s
base_margin: the raw score the row’s prediction starts from, in place of XGBoost’s constantbase_score, so that the trees fit what the margin leaves of the label.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 (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, asxgb.DMatrix(X, base_margin=m)or a matrix built here withrefandbase_margin. So arefbuilt with a margin needs one here, with as many values a row, and arefbuilt without one needs none.threadsThe 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.seedThe 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 eachpl.Enumfeature’s categories and the margin’s width, for the checks of a matrix built later with it asref.Raises
WrongTypeErrormax_bin,threads,sample_rowsorseedis not a whole number; or a feature, the label, the weight or the margin is of a type XGBoost does not read, apl.Categoricalamong them. It is both aTypeErrorand aValueError.ColumnNotFoundErrorA column named is not in the source. It is both Polars’
ColumnNotFoundErrorand aValueError.TypeErrorrefis not anxgboost.DMatrix,sourceis of another type, orfeaturesis one name in place of a list.FileNotFoundErrorA glob of local files matches nothing.
ValueErrorWhen, each named in the message:
max_binbelow 2,threadsorsample_rowsbelow 1, athreadsabove its bound, aseedoutside 0 to2**64 - 1, or anenginenot 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
featuresleft 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
refbinned on other features, or built here on apl.Enumof other categories;a
refbuilt with a margin and nobase_marginhere, orbase_marginhere and arefbuilt without one;under
engine="native", an XGBoost the native engine cannot load.
UserWarningUnder
engine="auto", the native engine cannot load XGBoost, and the Python engine builds the matrix.UnstableWarningUnder
POLARS_ONLINE_WARN_UNSTABLE=1, on each call (the module’s warning says why).
Examples
This code reads
dffrom 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
lightgbm_dataset(), LightGBM’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
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. Rowihas a hashh, SplitMix64 ofiandseed, and the priorityw / u, wherewis its weight (1 withoutweight) andu = (2h + 1) / 2**65. Thesample_rowsrows 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 thantau, the largest priority not kept, is always kept and counts its own weight, and any other kept row countstau. 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_bindistinct sample values gets a bin per value. Any other getsmax_binbins of equal weight. Edgejis the first sorted sample value whose running weight exceedsj / max_binof the total. Without weights that is the value of rankfloor(j m / max_bin)formvalues. At the quantileq, a cut’s share of the weight then errs by aboutsqrt(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 aref, which removes its sketch pass. The sample is the same rows however the source is batched and whichever engine reads it.sample_rows=Nonelets XGBoost sketch every row, and grows XGBoost’s own trees.Measured as
polars_online.gbdtdescribes, 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
LazyFrameover them4.2
7.2
this,
engine="python"5.5
7.1
this,
sample_rows=None8.0
3.6
XGBoost’s own
DataIterover Polars’ chunks8.7
4.8
collect()and numpy7.0
8.7