Skip to content

Reference#

Use this page to look up the signature, arguments, and return value of any public bonsai function or class. If you are new, start with the Quickstart. The training parameters, with their types, defaults, and effects, are on Parameters; this page lists the functions and classes that take them. The docs build generates each entry from the docstrings in the code.

Training#

train(params, dataset, eval_set=None, init_model=None) #

train(params: bonsai.params.Params | Mapping[str, object] | None, dataset: Dataset, eval_set: tuple[Annotated[NDArray[numpy.float32], dict(shape=(None, None), order=C, device=cpu, writable=False)], Annotated[NDArray[numpy.float32], dict(shape=(None,), order=C, device=cpu, writable=False)]] | Dataset | None = None, init_model: str | None = None) -> Model
train(params: bonsai.params.Params | Mapping[str, object] | None, X: object, y: object, eval_set: tuple[Annotated[NDArray[numpy.float32], dict(shape=(None, None), order=C, device=cpu, writable=False)], Annotated[NDArray[numpy.float32], dict(shape=(None,), order=C, device=cpu, writable=False)]] | Dataset | None = None, init_model: str | None = None, sample_weight: object | None = None, feature_names: Sequence[str] | None = None) -> Model

Train on a prebuilt Dataset, reusing its binning across calls.

Parameters:

Name Type Description Default
params Params, Mapping, or None

Overrides over the library defaults: a bonsai.Params, a {'tree.max_depth': 8} dotted-key mapping, or None for no overrides. A TOML base composes here too, Params.from_toml(path) | overrides. bin_mapper.* overrides are rejected: binning is fixed by the Dataset.

tree.monotone_constraints also takes a mapping keyed by feature name, {'age': 1, 'debt': -1}, resolved against the Dataset's feature_names. Features the mapping leaves out are free (0); a name the data does not carry raises.

required
dataset Dataset

The pre-binned training data.

required
eval_set tuple of (Xv, yv), Dataset, or None

Enables per-iteration eval and early stopping; yv is 1-D (a K-target fit flattens its (n_rows, K) labels row-major). Arrays are binned by the fit itself once its rounds have paid for the pass; a Dataset built with reference= this one is binned once.

None
init_model str

Continue training from this saved model (warm start). The fit owns its rounds, early stopping, logging, data, metrics, and parallel keys; any other key must equal the loaded model's.

None

Returns:

Type Description
Model

The trained booster.

Dataset #

A pre-binned dataset, reusable across fits.

device property #

Where the binned columns live: "cuda" for a device-binned dataset, "cpu" otherwise.

n_rows property #

Rows a fit visits: the binned matrix's, or the selection's on a view.

n_targets property #

Targets per row: 1 for a vector y, the columns of a 2-D one.

n_features property #

Feature columns in the binned matrix.

feature_names property #

One name per column, in column order: the feature_names= given here, or the synthesized f0..fN.

shape property #

(n_rows, n_features), the way an array reports it. IDE variable explorers read it for their size column.

base property #

The Dataset whose binned plane this one selects rows out of, or None when it owns its own, the way numpy.ndarray.base reads. A chained view names the root, not the view it was taken from.

subset(rows=None, columns=None) #

Select rows and/or columns out of this Dataset.

Rows share the parent's binned plane and cost nothing: a view of a device-resident parent predicts, explains and scores on the device, in place. Columns rewrite it: the kept columns are gathered into a plane the result owns, renumbered from zero, which packs them into full device tiles; rows apply first, so it gathers only survivors.

The result is a Dataset that train fits on the selected rows, that eval_set scores over exactly those rows, and that predict and its family answer one row per selected row in the selection's order. Nothing is copied: the bins, the cut points and the row-major mirror stay with the parent, so k folds cost one plane rather than k. Selections compose, and positions are always into the Dataset they are given to.

A fit over a view is about the selected rows and no others. It does not carry the rows left out through each finished tree the way a subsampled fit carries the rows its draw dropped, since those rejoin the next tree and a view's never do. So the rows outside the selection keep stale training scores. Nothing the view's fit produces reads them, and predict recomputes from the trees regardless.

Parameters:

Name Type Description Default
rows integer array, slice, or boolean mask

Which rows to keep. The order is kept as given and duplicates count once each, so a bootstrap draw weighs the way the materialized copy of it would. Out-of-range and negative indices raise: row ids index the binned plane and do not wrap.

None
columns integer array, slice, boolean mask, or feature names

Which features to keep, in the order given. Unlike rows this copies: the bins are gathered into a new plane, so the result owns its columns and its base is None. The gather stays wherever the parent's bins were: a device-resident parent is rewritten on the device and the result reports that device, so a feature-selection loop never round-trips through the host. Out-of-range, negative and repeated columns raise, and an unknown name raises KeyError.

None

Returns:

Type Description
Dataset

With rows= alone, a view whose base is the Dataset that owns the plane. With columns=, a Dataset that owns its own plane and whose base is None.

reorder(rows=None) #

The same rows in a different order, laid out that way.

Unlike subset(rows=), which describes an order and leaves the bins where they are, this rewrites the plane so the order is the storage. That is worth doing when the same selections will be fit repeatedly: a scattered fold costs a gather on every histogram fill of every tree, while a fold laid out contiguously is a range the fill reads as a subspan and the device reads fully coalesced.

The usual arrangement is to sort rows into group order once, after which each fold is a slice::

order = np.argsort(groups, kind="stable")
ds = bonsai.Dataset(X, y).reorder(rows=order)
fold = ds.subset(rows=slice(0, n_first_group))

The result is an ordinary Dataset in the new order: row i is the row rows[i] named, and labels, predictions and contributions all follow that order, the way X[order] would. Nothing is un-permuted behind the caller's back, because the contiguity is the thing being bought and hiding it would put it out of reach.

Parameters:

Name Type Description Default
rows integer array or slice

A permutation of this Dataset's rows: every row exactly once. To keep only some of them, use subset(rows=...).

None

Returns:

Type Description
Dataset

A Dataset that owns its own plane; its base is None.

Model #

A trained booster: predict, explain, save.

n_iters property #

Boosting rounds this model carries.

eval_history property #

Per-round valid loss from fit (objective's own eval metric); empty without an eval set or after load(). Indexed by absolute model round: after an init_model warm start the pre-existing rounds appear as NaN placeholders.

config_toml property #

The resolved training config, rendered as TOML.

objective_name property #

The objective this model was trained with (e.g. mse, logloss, softmax).

n_targets property #

Targets per row of a multi-target regression; 1 otherwise.

n_classes property #

Class count for softmax models; 0 for every other objective (including binary logloss).

feature_names property #

One name per feature, in column order: the names the fit was given, or the synthesized f0..fN. Survives save/load, and its length is the model's feature count.

dump() #

The trees as human-readable text, with feature names.

Returns:

Type Description
str

One block per tree.

feature_importance(type='gain') #

Per-feature importance, padded to the trained feature count.

Parameters:

Name Type Description Default
type (gain, split)

'gain' is total loss reduction; 'split' is split count.

'gain'

Returns:

Type Description
float64 array, shape (n_features,)

Importance per feature; features never split score 0.

Raises:

Type Description
ValueError

For any other type string.

save(path) #

Save the model (MessagePack) with its bin mappers and config.

Parameters:

Name Type Description Default
path str

Output file; bonsai.load(path) restores the model.

required

predict(X, num_iteration=0) #

predict(X: Annotated[NDArray[numpy.float32], dict(shape=(None, None), order=C, device=cpu, writable=False)], num_iteration: int = 0) -> NDArray[numpy.float32]
predict(X: Dataset, num_iteration: int = 0) -> NDArray[numpy.float32]

Predict on the response scale (the objective's link inverse applied).

Parameters:

Name Type Description Default
X float32 array, shape (n_rows, n_features), or Dataset

Row-major features. A Dataset carrying this model's cuts routes in bin space (device-resident builds included), bit-identical to the raw walk; other Datasets read the matrix they retained.

required
num_iteration int

Predict with only the first num_iteration boosting rounds; 0 uses all.

0

Returns:

Type Description
float32 array, shape (n_rows,) or (n_rows, n_targets)

One prediction per row; a multi-target model returns one column per target. A softmax model returns the argmax class id of each row; predict_proba gives the probabilities.

predict_proba(X) #

predict_proba(X: Annotated[NDArray[numpy.float32], dict(shape=(None, None), order=C, device=cpu, writable=False)]) -> NDArray[numpy.float64]
predict_proba(X: Dataset) -> NDArray[numpy.float64]

Per-class probabilities for classification models.

Parameters:

Name Type Description Default
X float32 array, shape (n_rows, n_features), or Dataset

Row-major features; a Dataset with this model's cuts routes in bin space, others read the matrix they retained.

required

Returns:

Type Description
float64 array

Softmax models return (n_rows, n_classes), a row-wise softmax of the class logits; logloss returns (n_rows,) with P(class 1) via the link inverse.

Raises:

Type Description
ValueError

For non-classification objectives: the mse link inverse is the identity, so raw margins would be silently mislabeled as probabilities.

staged_predict(X) #

staged_predict(X: Annotated[NDArray[numpy.float32], dict(shape=(None, None), order=C, device=cpu, writable=False)]) -> NDArray[numpy.float32]
staged_predict(X: Dataset) -> NDArray[numpy.float32]

Predictions after each boosting iteration.

Parameters:

Name Type Description Default
X float32 array, shape (n_rows, n_features), or Dataset

Row-major features; a Dataset with this model's cuts routes in bin space, others read the matrix they retained.

required

Returns:

Type Description
float32 array, shape (n_iters, n_rows) or (n_iters, n_rows, n_targets)

Entry t is the response-scale prediction using rounds 0..t, shaped as predict returns it (argmax class ids for a softmax model).

predict_leaf(X) #

predict_leaf(X: Annotated[NDArray[numpy.float32], dict(shape=(None, None), order=C, device=cpu, writable=False)]) -> NDArray[numpy.uint32]
predict_leaf(X: Dataset) -> NDArray[numpy.uint32]

The leaf each row lands in, one column per tree.

Width-1 objectives have one tree per round, so the columns are the boosting rounds in order. Softmax models grow one tree per class per round and the columns stay in that order, so column t is round t // n_classes, class t % n_classes.

Parameters:

Name Type Description Default
X float32 array, shape (n_rows, n_features), or Dataset

Row-major features; a Dataset with this model's cuts routes in bin space, others read the matrix they retained.

required

Returns:

Type Description
uint32 array, shape (n_rows, n_trees)

Leaf node id per (row, tree).

pred_contribs(X) #

pred_contribs(X: Annotated[NDArray[numpy.float32], dict(shape=(None, None), order=C, device=cpu, writable=False)]) -> NDArray[numpy.float64]
pred_contribs(X: Dataset) -> NDArray[numpy.float64]

TreeSHAP feature contributions, last column the bias.

Each row sums to the raw (pre-link) prediction exactly.

Parameters:

Name Type Description Default
X float32 array, shape (n_rows, n_features), or Dataset

Row-major features; a Dataset with this model's cuts routes in bin space, others read the matrix they retained.

required

Returns:

Type Description
float64 array

(n_rows, n_features + 1); multiclass models return (n_rows, n_classes, n_features + 1) and multi-target models (n_rows, n_targets, n_features + 1).

load(path) #

Load a model saved by Model.save.

Parameters:

Name Type Description Default
path str

A .msgpack model file.

required

Returns:

Type Description
Model

The restored booster, with its bin mappers and config.

Configuration#

Params dataclass #

Bases: ParamsOps

Typed overrides over the library defaults, one field per config key.

Unset (None) fields leave the library default, so a section names only what it changes. Renders to the same dotted-key pairs train() always accepted.

Examples:

>>> p = Params(tree=Tree(max_depth=8), booster=Booster(n_iters=200))
>>> bonsai.train(p, ds)
>>> sweep = p | {"tree.max_depth": 10}               # dict-style merge

to_dict() #

The set overrides as {dotted.key: value} with Python types.

The form optuna/MLflow log well, and the inverse of from_dict.

from_toml(path) classmethod #

Build a Params from the keys a TOML config file explicitly sets.

The C++ config layer does the parsing (no TOML dependency, any Python), strict like the CLI's -c: unknown sections or keys raise. Only stated keys are carried, so the result stays a sparse overrides object: train(Params.from_toml(p) | sweep, ds) is the file-base-plus-overrides layering config= used to express.

from_model(model) classmethod #

The config a trained Model resolved, as a fully-set Params.

Every key is set (a model's config is fully determined), so this is for inspection and reproduction, not sparse layering; drop sections with dataclasses.replace(p, bin_mapper=None) where a consumer rejects them.

from_dict(mapping) classmethod #

Build a Params from {dotted.key: value}.

Parameters:

Name Type Description Default
mapping Mapping[str, object]

Dotted keys exactly as train() pairs spell them ("tree.max_depth"); values keep their Python types.

required

Raises:

Type Description
ValueError

On a key with no dot, an unknown section, or an unknown leaf, named in the message next to the legal choices.

Dispatch dataclass #

Bases: SparseRepr

[dispatch] overrides; None = library default.

objective_name : str, default 'mse' grower_name : str, default 'depthwise' sampler_name : str, default 'all_rows'

Booster dataclass #

Bases: SparseRepr

[booster] overrides; None = library default.

n_iters : int, default 100 learning_rate : float, default 0.05 random_seed : int, default 42 log_intervals : int, default 0 early_stopping_rounds : int, default 0 dart_drop_rate : float, default 0.0

Tree dataclass #

Bases: SparseRepr

[tree] overrides; None = library default.

min_child_hess : float, default 1.0 min_gain_to_split : float, default 0.0 lambda_l2 : float, default 1.0 lambda_l1 : float, default 0.0 max_depth : int, default 6 min_data_in_leaf : int, default 20 max_leaves : int, default 31 feature_fraction : float, default 1.0 feature_seed : int, default 2 monotone_constraints : list[int], default [] interaction_constraints : list[str], default []

Sampler dataclass #

Bases: SparseRepr

[sampler] overrides; None = library default.

subsample : float, default 1.0 top_rate : float, default 0.2 other_rate : float, default 0.1

BinMapper dataclass #

Bases: SparseRepr

[bin_mapper] overrides; None = library default.

max_bin : int, default 255 n_samples : int, default 200000 seed : int, default 0 min_data_in_bin : int, default 1

Objective dataclass #

Bases: SparseRepr

[objective] overrides; None = library default.

huber_delta : float, default 1.0 quantile_alpha : float, default 0.5 n_classes : int, default 3 n_targets : int, default 1

Metrics dataclass #

Bases: SparseRepr

[metrics] overrides; None = library default.

fit : list[str], default [] eval : list[str], default []

Data dataclass #

Bases: SparseRepr

[data] overrides; None = library default.

train : str, default '' test : str, default '' format : str, default 'csv' header : bool, default true label_column : int, default 0 weight_column : int, default -1 valid : list[str], default [] ignore_columns : list[int], default [] libsvm_n_features : int, default 0

Parallel dataclass #

Bases: SparseRepr

[parallel] overrides; None = library default.

n_threads : int, default 0 device_id : int, default 0

default_config_toml() #

The library's default config, rendered as TOML.

interop #

Parameter translation between bonsai and the reference libraries.

This module is the repo's single source of truth for cross-library knob mapping. One table per library drives both directions, so a rename can never drift between the estimator layer, the benchmark harness, and the docs.

from_xgboost / from_lightgbm / from_catboost turn a reference library's parameter dict into a bonsai.Params, ready for bonsai.train. to_xgboost / to_lightgbm / to_catboost go the other way, returning that library's parameter dict.

>>> import bonsai
>>> p = bonsai.interop.from_lightgbm({"num_leaves": 63, "max_depth": -1})
>>> p
Params(tree=Tree(max_depth=255, max_leaves=63), dispatch=Dispatch(grower_name='leafwise'))

Translation is not equivalence. Every mapping whose two sides mean different things carries a note at its table row, and the module-level notes below collect the ones that change what a fit does rather than what it is called. Read them before trusting a translated config to reproduce a number.

from_xgboost(params, *, strict=True) #

Translate XGBoost parameters into a bonsai Params.

A max_leaves above 0 selects the leafwise grower whatever the grow_policy: XGBoost enforces the cap under depthwise growth too, and bonsai's depthwise grower ignores it. The leaf budget matches; the split order becomes best-first.

Parameters#

params XGBoost parameter names to values, under any spelling the library documents. A None value leaves that parameter unset, the way the library's scikit-learn wrapper means it, so an estimator's get_params() translates directly. strict True raises on any parameter with no bonsai counterpart, naming every one. False drops them and translates the rest, which loses whatever they configured.

Returns#

Params The translated overrides, ready for bonsai.train (compose with | to layer more).

Raises#

ValueError Under strict, when any parameter has no bonsai counterpart. Always, when a mapped parameter carries a value bonsai cannot express.

Examples#

import bonsai bonsai.interop.from_xgboost({"n_estimators": 300, "reg_lambda": 2.0}) Params(tree=Tree(lambda_l2=2.0), booster=Booster(n_iters=300))

from_lightgbm(params, *, strict=True) #

Translate LightGBM parameters into a bonsai Params.

The translation always selects the leafwise grower, LightGBM's only growth policy, so num_leaves binds. max_depth <= 0 (LightGBM's uncapped growth) becomes tree.max_depth = 255: bonsai has no sentinel, and under leafwise growth num_leaves is the binding budget either way. bagging_fraction translates only with bagging_freq=1: LightGBM bags only above frequency 0, and bonsai draws for every tree. boosting='goss' selects the goss sampler, 'dart' sets booster.dart_drop_rate (LightGBM's 0.1 unless drop_rate is given), and 'rf' raises. alpha becomes objective.quantile_alpha or objective.huber_delta by objective, at LightGBM's 0.9 when unset.

Parameters#

params LightGBM parameter names to values, under any spelling the library documents. A None value leaves that parameter unset, the way the library's scikit-learn wrapper means it, so an estimator's get_params() translates directly. strict True raises on any parameter with no bonsai counterpart, naming every one. False drops them and translates the rest, which loses whatever they configured.

Returns#

Params The translated overrides, ready for bonsai.train (compose with | to layer more).

Raises#

ValueError Under strict, when any parameter has no bonsai counterpart. Always, when a mapped parameter carries a value bonsai cannot express.

Examples#

import bonsai bonsai.interop.from_lightgbm({"num_leaves": 63, "max_depth": -1}) Params(tree=Tree(max_depth=255, max_leaves=63), dispatch=Dispatch(grower_name='leafwise'))

from_catboost(params, *, strict=True) #

Translate CatBoost parameters into a bonsai Params.

Without a grow_policy the translation selects the levelwise grower, CatBoost's default SymmetricTree policy. border_count counts splits where bin_mapper.max_bin counts bins, so the value gains one crossing over. CatBoost's parametrized losses (Huber:delta=..., Quantile:alpha=...) raise: set dispatch.objective_name and the loss parameter by hand. subsample translates only under bootstrap_type='Bernoulli', at CatBoost's 0.66 when unset: CatBoost's default MVS and Bayesian bootstraps weight rows by gradient, which no bonsai sampler does.

Parameters#

params CatBoost parameter names to values, under any spelling the library documents. A None value leaves that parameter unset, the way the library's scikit-learn wrapper means it, so an estimator's get_params() translates directly. strict True raises on any parameter with no bonsai counterpart, naming every one. False drops them and translates the rest, which loses whatever they configured.

Returns#

Params The translated overrides, ready for bonsai.train (compose with | to layer more).

Raises#

ValueError Under strict, when any parameter has no bonsai counterpart. Always, when a mapped parameter carries a value bonsai cannot express.

Examples#

import bonsai bonsai.interop.from_catboost({"depth": 6, "border_count": 254}) Params(bin_mapper=BinMapper(max_bin=255), tree=Tree(max_depth=6), dispatch=Dispatch(grower_name='levelwise'))

to_xgboost(pairs, *, strict=True) #

Translate bonsai parameters, a Params or dotted-key pairs, into XGBoost's.

bonsai's levelwise grower has no XGBoost policy and raises. A key bonsai reads only under one selector, such as tree.max_leaves under leafwise growth or sampler.subsample under the bernoulli sampler, is left out elsewhere, since bonsai ignores it there. DART goes out with booster='dart', the switch that turns rate_drop on, and the goss sampler, which XGBoost lacks, raises.

Parameters#

pairs (dotted.key, value) pairs, a mapping of the same, or a bonsai.Params. Values pass through with their Python type intact unless the mapping transforms them. strict True raises on any bonsai key with no XGBoost counterpart, naming every one. False drops them.

Returns#

dict[str, Any] XGBoost parameter names to values.

Raises#

ValueError Under strict, when any key has no XGBoost counterpart. Always, when a value has none.

Examples#

import bonsai bonsai.interop.to_xgboost([("tree.lambda_l2", 2.0)])

to_lightgbm(pairs, *, strict=True) #

Translate bonsai parameters, a Params or dotted-key pairs, into LightGBM's.

The bernoulli sampler goes out with bagging_freq=1 and DART with boosting='dart', the switches that turn their rates on. The goss sampler goes out as data_sample_strategy='goss'. The quantile and huber objectives carry their parameter as alpha, stated or at bonsai's default, since LightGBM's own default is 0.9.

Parameters#

pairs (dotted.key, value) pairs, a mapping of the same, or a bonsai.Params. Values pass through with their Python type intact unless the mapping transforms them. strict True raises on any bonsai key with no LightGBM counterpart, naming every one. False drops them.

Returns#

dict[str, Any] LightGBM parameter names to values.

Raises#

ValueError Under strict, when any key has no LightGBM counterpart. Always, when a value has none.

Examples#

import bonsai bonsai.interop.to_lightgbm([("tree.max_leaves", 63)])

to_catboost(pairs, *, strict=True) #

Translate bonsai parameters, a Params or dotted-key pairs, into CatBoost's.

bin_mapper.max_bin loses one crossing over: CatBoost's border_count counts splits, not bins. bonsai's huber and quantile objectives raise, since their CatBoost spellings carry a parameter. The bernoulli sampler goes out as bootstrap_type='Bernoulli' and all_rows as 'No'; the goss sampler, which CatBoost lacks, raises.

Parameters#

pairs (dotted.key, value) pairs, a mapping of the same, or a bonsai.Params. Values pass through with their Python type intact unless the mapping transforms them. strict True raises on any bonsai key with no CatBoost counterpart, naming every one. False drops them.

Returns#

dict[str, Any] CatBoost parameter names to values.

Raises#

ValueError Under strict, when any key has no CatBoost counterpart. Always, when a value has none.

Examples#

import bonsai bonsai.interop.to_catboost([("bin_mapper.max_bin", 255)])

Estimators#

BonsaiRegressor #

Bases: _BonsaiEstimator

sklearn-style wrapper around the native booster.

Every argument is a bonsai name. First-class arguments cover the common knobs; anything else can be set through params using dotted config keys, e.g. params={"tree.lambda_l1": 0.5, "sampler.top_rate": 0.2}, the same keys the CLI accepts via --set. A parameter dict written for another library goes through bonsai.interop first, which is where the knob mapping and its caveats live.

A TOML file routes through params (params=Params.from_toml(path).to_dict()) and therefore wins over the keyword arguments, the way params always has. For file-as-base layering below explicit overrides, use train() with Params.from_toml(path) | overrides.

Parameters:

Name Type Description Default
n_iters int

Number of boosting rounds.

100
learning_rate float

Shrinkage applied to each tree's contribution.

0.05
max_depth int

Maximum tree depth.

6
max_leaves int

Maximum leaves per tree, the leafwise growth budget.

31
grower str

Growth strategy name ("leafwise", "depthwise", "levelwise", ...); combined with device to pick the concrete grower.

'leafwise'
sampler str

Row sampler name; "all_rows" trains on every row.

'all_rows'
objective str

One of bonsai's own: "mse", "mae", "huber", "quantile" (with quantile_alpha), or "poisson".

'mse'
early_stopping_rounds int

Patience in rounds before stopping on eval-set loss. The fit keeps the rounds up to its best eval-set loss, whether it stopped or ran out its n_iters. 0 disables early stopping.

0
n_threads int

Worker thread count; 0 uses every available core.

0
random_seed int

Seed for every draw the fit makes: row sampling, DART drops and, with tree.feature_seed, the feature_fraction draws.

42
max_bin int | None

Histogram bin cap; None leaves the native default.

None
subsample float | None

Row-sampling fraction; switches the sampler to "bernoulli" when sampler is still at its default, as sampler.subsample in params does. None leaves sampling off.

None
device str | None

"cpu" or "cuda" (or "cuda:N"); "cuda" picks the CUDA grower matching the chosen grower, moving compute without changing the growth strategy, and "cuda:N" also sets parallel.device_id to N. None leaves the grower name as given.

None
quantile_alpha float | None

The quantile to fit when objective="quantile".

None
params dict | ParamsOps | None

Overrides beyond the first-class kwargs: a bonsai.Params or a dotted config-key dict; the power-user escape hatch, applied after the first-class kwargs and always wins.

None

feature_importances_ property #

numpy.ndarray: gain importance normalized to sum to 1 (sklearn convention).

best_iteration property #

int: 0-based absolute model round with the best eval-set loss.

Defined only when fit ran with early stopping and an eval_set: it is the last round the fit kept, whether patience fired or n_iters ended the fit first. After an init_model warm start the index counts the warm-start rounds too, so it lines up with n_iters_ and predict(num_iteration=best_iteration + 1).

Raises:

Type Description
AttributeError

If fit did not run with eval_set and early_stopping_rounds.

best_score property #

float: eval-set loss at best_iteration.

In the objective's own units (the same values evals_result reports).

Raises:

Type Description
AttributeError

If fit did not run with eval_set and early_stopping_rounds.

get_params(deep=True) #

Read back every constructor parameter, unchanged since construction.

Part of the sklearn estimator contract.

Parameters:

Name Type Description Default
deep bool

Accepted for API compatibility; these estimators have no nested estimators to recurse into, so it has no effect.

True

Returns:

Type Description
dict

One entry per __init__ parameter name.

set_params(**params) #

Set constructor attributes in place.

Part of the sklearn estimator contract.

Parameters:

Name Type Description Default
**params

Constructor parameter names to new values.

{}

Returns:

Type Description
_BonsaiEstimator

self, for chaining.

Raises:

Type Description
ValueError

If a name is not a constructor parameter (sklearn's own estimators do the same).

fit(X, y, sample_weight=None, eval_set=None, init_model=None, feature_names=None) #

Fit to training data.

BonsaiClassifier reads its classes off y here and picks logloss for two of them or softmax (with objective.n_classes set) for more.

Parameters:

Name Type Description Default
X ArrayLike

Feature matrix.

required
y ArrayLike

Regression targets, shape (n_rows,) or (n_rows, n_targets) for a multi-target fit (one tree per target per round, and predict returns one column per target); for BonsaiClassifier class labels, any hashable/orderable values (ints, strings, ...), encoded to 0..K-1 internally and decoded back to the original classes_ values by predict.

required
sample_weight ArrayLike | None

Per-row weights, finite and non-negative with at least one positive (sklearn's convention). A weight scales its row's gradient and hessian and counts the row in the base score and in the leaf values MAE, Huber and Quantile renew, so the label of a zero-weight row never reaches the fit. None weights every row equally.

None
eval_set tuple[ArrayLike, ArrayLike] | Dataset | None

One bare (X, y) tuple, Dataset, or None. A bonsai.Dataset must be built with reference= the training dataset, which bins the validation rows once and reuses them across fits; for a classifier its labels are already the encoded 0..K-1. bonsai tracks a single validation set, so a list of them is rejected rather than silently reduced to its last entry.

None
init_model str | None

Path to a saved .msgpack model to continue training from (warm start); binning reuses the loaded model's cut points. The fit keeps its own n_iters (the rounds to add), early_stopping_rounds, and n_threads. Every other argument describes the model: left at its default it takes the loaded model's value, and set to a value the model disagrees with it raises. None trains from scratch.

None
feature_names Sequence[str] | None

One name per column, overriding any string column names X carries. Fitted names land in feature_names_in_, dump prints them, and tree.monotone_constraints may be keyed by them. None with an unnamed X leaves the columns f0..fN. Rejected with init_model: a warm start keeps the loaded model's names, and holds the names X and the eval_set's X carry against them. Predict-time inputs and the eval_set's X are checked against the fitted names, sklearn's rule: names that go missing or appear warn, names that disagree raise.

None

Returns:

Type Description
_BonsaiEstimator

self, fitted.

Raises:

Type Description
ValueError

If eval_set is a list, or given at all with dart_drop_rate > 0; if X has no rows or no columns, y holds a non-finite value, or sample_weight a non-finite or negative one or no positive one; if X or the eval_set's X names its columns differently from init_model; for a classifier also if y contains NaN (in any dtype), holds floats that are not finite integers (a continuous target), or has fewer than 2 classes, or an eval-set label was not seen in the training classes.

predict(X, num_iteration=0) #

Predict with the fitted model.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

Feature matrix, or a bonsai.Dataset: one carrying the model's cuts routes in bin space (device-resident builds included), others read the matrix they retained.

required
num_iteration int

Truncates the ensemble to its first n trees, as on Model.predict; 0 uses every tree. A prefix always starts at the head, because a boosted sum has no meaning without it.

0

Returns:

Type Description
ndarray

Predictions, one per row of X, or (n_rows, n_targets) for a multi-target regressor; BonsaiClassifier returns the original class labels (from classes_), not the encoded 0..K-1 ids the native booster works in.

staged_predict(X) #

Predict after each boosting iteration.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

As for predict.

required

Returns:

Type Description
ndarray

Shape (n_iters, n_rows), or (n_iters, n_rows, n_targets) for a multi-target regressor: predictions after each boosting iteration, each stage what predict would return for that prefix (class labels for BonsaiClassifier).

predict_leaf(X) #

Predict per-tree leaf indices, for feature engineering / embedding.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

As for predict.

required

Returns:

Type Description
ndarray

Shape (n_rows, n_trees). One column per tree in training order, so a softmax model (one tree per class per round) has n_iters * n_classes columns and column t is round t // n_classes, class t % n_classes.

dump() #

Dump the model as text.

Returns:

Type Description
str

Every tree as indented text.

pred_contribs(X) #

Compute TreeSHAP contributions.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

As for predict.

required

Returns:

Type Description
ndarray

Shape (n_rows, n_features + 1); the last column is the bias. Rows sum to the raw (pre-link) prediction exactly.

importance(type='gain') #

Compute raw per-feature importance.

Parameters:

Name Type Description Default
type str

"gain" for total split gain, "split" for split count.

'gain'

Returns:

Type Description
ndarray

One value per feature, unnormalized.

save(path) #

Serialize the fitted model to a .msgpack file.

Parameters:

Name Type Description Default
path str

Destination file path.

required

evals_result() #

Read back the per-round eval-set loss history.

Requires a fit with an eval_set; empty after loading from a file. The metric is the objective's own loss under its bonsai name and its own units: the mse objective reports squared error, not its root. After an init_model warm start only the continuation's measured rounds are reported (the warm-start rounds were never evaluated; best_iteration still counts absolute rounds).

Returns:

Type Description
dict

{"valid": {objective_name: [...]}}. The outer key names the eval set, spelled the way the CLI labels its metric column and data.valid names the file. Empty if there is no eval-set history.

score(X, y, sample_weight=None) #

Compute R² (coefficient of determination) on held-out data.

Matches sklearn's RegressorMixin.score, computed by hand with no sklearn import.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

Feature matrix.

required
y ArrayLike

True regression targets.

required
sample_weight ArrayLike | None

Per-row weights for the R² computation. None weights every row equally.

None

Returns:

Type Description
float

The R² score.

Raises:

Type Description
ValueError

If y or sample_weight disagrees with the predictions in row count, or y in target count.

from_file(path) classmethod #

Load a saved regressor; n_outputs_ is read off the model.

BonsaiClassifier #

Bases: _BonsaiEstimator

sklearn-style classifier wrapping the native booster's logloss (binary) and softmax (multiclass) objectives.

Same first-class knobs as BonsaiRegressor except there is no objective argument: fit picks logloss for two classes or softmax (with objective.n_classes set) for more, based on np.unique(y). Labels may be any hashable/orderable values (ints, strings, ...); they're encoded to 0..K-1 internally and decoded back to the original classes_ values by predict.

predict_proba covers both cases: binary from the native logloss P(class 1), multiclass from the softmax booster's per-class probabilities; see its docstring.

Parameters:

Name Type Description Default
n_iters int

Number of boosting rounds.

100
learning_rate float

Shrinkage applied to each tree's contribution.

0.05
max_depth int

Maximum tree depth.

6
max_leaves int

Maximum leaves per tree, the leafwise growth budget.

31
grower str

Growth strategy name ("leafwise", "depthwise", "levelwise", ...); combined with device to pick the concrete grower.

'leafwise'
sampler str

Row sampler name; "all_rows" trains on every row.

'all_rows'
early_stopping_rounds int

Patience in rounds before stopping on eval-set loss. The fit keeps the rounds up to its best eval-set loss, whether it stopped or ran out its n_iters. 0 disables early stopping.

0
n_threads int

Worker thread count; 0 uses every available core.

0
random_seed int

Seed for every draw the fit makes: row sampling, DART drops and, with tree.feature_seed, the feature_fraction draws.

42
max_bin int | None

Histogram bin cap; None leaves the native default.

None
subsample float | None

Row-sampling fraction; switches the sampler to "bernoulli" when sampler is still at its default, as sampler.subsample in params does. None leaves sampling off.

None
device str | None

"cpu" or "cuda" (or "cuda:N"); "cuda" picks the CUDA grower matching the chosen grower, moving compute without changing the growth strategy, and "cuda:N" also sets parallel.device_id to N. None leaves the grower name as given.

None
params dict | ParamsOps | None

Overrides beyond the first-class kwargs: a bonsai.Params or a dotted config-key dict; the power-user escape hatch, applied after the first-class kwargs and always wins.

None

feature_importances_ property #

numpy.ndarray: gain importance normalized to sum to 1 (sklearn convention).

best_iteration property #

int: 0-based absolute model round with the best eval-set loss.

Defined only when fit ran with early stopping and an eval_set: it is the last round the fit kept, whether patience fired or n_iters ended the fit first. After an init_model warm start the index counts the warm-start rounds too, so it lines up with n_iters_ and predict(num_iteration=best_iteration + 1).

Raises:

Type Description
AttributeError

If fit did not run with eval_set and early_stopping_rounds.

best_score property #

float: eval-set loss at best_iteration.

In the objective's own units (the same values evals_result reports).

Raises:

Type Description
AttributeError

If fit did not run with eval_set and early_stopping_rounds.

get_params(deep=True) #

Read back every constructor parameter, unchanged since construction.

Part of the sklearn estimator contract.

Parameters:

Name Type Description Default
deep bool

Accepted for API compatibility; these estimators have no nested estimators to recurse into, so it has no effect.

True

Returns:

Type Description
dict

One entry per __init__ parameter name.

set_params(**params) #

Set constructor attributes in place.

Part of the sklearn estimator contract.

Parameters:

Name Type Description Default
**params

Constructor parameter names to new values.

{}

Returns:

Type Description
_BonsaiEstimator

self, for chaining.

Raises:

Type Description
ValueError

If a name is not a constructor parameter (sklearn's own estimators do the same).

fit(X, y, sample_weight=None, eval_set=None, init_model=None, feature_names=None) #

Fit to training data.

BonsaiClassifier reads its classes off y here and picks logloss for two of them or softmax (with objective.n_classes set) for more.

Parameters:

Name Type Description Default
X ArrayLike

Feature matrix.

required
y ArrayLike

Regression targets, shape (n_rows,) or (n_rows, n_targets) for a multi-target fit (one tree per target per round, and predict returns one column per target); for BonsaiClassifier class labels, any hashable/orderable values (ints, strings, ...), encoded to 0..K-1 internally and decoded back to the original classes_ values by predict.

required
sample_weight ArrayLike | None

Per-row weights, finite and non-negative with at least one positive (sklearn's convention). A weight scales its row's gradient and hessian and counts the row in the base score and in the leaf values MAE, Huber and Quantile renew, so the label of a zero-weight row never reaches the fit. None weights every row equally.

None
eval_set tuple[ArrayLike, ArrayLike] | Dataset | None

One bare (X, y) tuple, Dataset, or None. A bonsai.Dataset must be built with reference= the training dataset, which bins the validation rows once and reuses them across fits; for a classifier its labels are already the encoded 0..K-1. bonsai tracks a single validation set, so a list of them is rejected rather than silently reduced to its last entry.

None
init_model str | None

Path to a saved .msgpack model to continue training from (warm start); binning reuses the loaded model's cut points. The fit keeps its own n_iters (the rounds to add), early_stopping_rounds, and n_threads. Every other argument describes the model: left at its default it takes the loaded model's value, and set to a value the model disagrees with it raises. None trains from scratch.

None
feature_names Sequence[str] | None

One name per column, overriding any string column names X carries. Fitted names land in feature_names_in_, dump prints them, and tree.monotone_constraints may be keyed by them. None with an unnamed X leaves the columns f0..fN. Rejected with init_model: a warm start keeps the loaded model's names, and holds the names X and the eval_set's X carry against them. Predict-time inputs and the eval_set's X are checked against the fitted names, sklearn's rule: names that go missing or appear warn, names that disagree raise.

None

Returns:

Type Description
_BonsaiEstimator

self, fitted.

Raises:

Type Description
ValueError

If eval_set is a list, or given at all with dart_drop_rate > 0; if X has no rows or no columns, y holds a non-finite value, or sample_weight a non-finite or negative one or no positive one; if X or the eval_set's X names its columns differently from init_model; for a classifier also if y contains NaN (in any dtype), holds floats that are not finite integers (a continuous target), or has fewer than 2 classes, or an eval-set label was not seen in the training classes.

predict(X, num_iteration=0) #

Predict with the fitted model.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

Feature matrix, or a bonsai.Dataset: one carrying the model's cuts routes in bin space (device-resident builds included), others read the matrix they retained.

required
num_iteration int

Truncates the ensemble to its first n trees, as on Model.predict; 0 uses every tree. A prefix always starts at the head, because a boosted sum has no meaning without it.

0

Returns:

Type Description
ndarray

Predictions, one per row of X, or (n_rows, n_targets) for a multi-target regressor; BonsaiClassifier returns the original class labels (from classes_), not the encoded 0..K-1 ids the native booster works in.

staged_predict(X) #

Predict after each boosting iteration.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

As for predict.

required

Returns:

Type Description
ndarray

Shape (n_iters, n_rows), or (n_iters, n_rows, n_targets) for a multi-target regressor: predictions after each boosting iteration, each stage what predict would return for that prefix (class labels for BonsaiClassifier).

predict_leaf(X) #

Predict per-tree leaf indices, for feature engineering / embedding.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

As for predict.

required

Returns:

Type Description
ndarray

Shape (n_rows, n_trees). One column per tree in training order, so a softmax model (one tree per class per round) has n_iters * n_classes columns and column t is round t // n_classes, class t % n_classes.

dump() #

Dump the model as text.

Returns:

Type Description
str

Every tree as indented text.

pred_contribs(X) #

Compute TreeSHAP contributions.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

As for predict.

required

Returns:

Type Description
ndarray

Shape (n_rows, n_features + 1); the last column is the bias. Rows sum to the raw (pre-link) prediction exactly.

importance(type='gain') #

Compute raw per-feature importance.

Parameters:

Name Type Description Default
type str

"gain" for total split gain, "split" for split count.

'gain'

Returns:

Type Description
ndarray

One value per feature, unnormalized.

save(path) #

Serialize the fitted model to a .msgpack file.

Parameters:

Name Type Description Default
path str

Destination file path.

required

evals_result() #

Read back the per-round eval-set loss history.

Requires a fit with an eval_set; empty after loading from a file. The metric is the objective's own loss under its bonsai name and its own units: the mse objective reports squared error, not its root. After an init_model warm start only the continuation's measured rounds are reported (the warm-start rounds were never evaluated; best_iteration still counts absolute rounds).

Returns:

Type Description
dict

{"valid": {objective_name: [...]}}. The outer key names the eval set, spelled the way the CLI labels its metric column and data.valid names the file. Empty if there is no eval-set history.

predict_proba(X) #

Predict class probabilities with the fitted model.

A logloss model's P(class 1) becomes [1 - p, p]; a softmax model, two classes included, gives its per-class probabilities (a row-wise softmax of the class logits).

Parameters:

Name Type Description Default
X ArrayLike | Dataset

As for predict.

required

Returns:

Type Description
ndarray

Shape (n_rows, n_classes), columns in classes_ order.

score(X, y, sample_weight=None) #

Compute accuracy on held-out data.

Matches sklearn's ClassifierMixin.score, computed by hand with no sklearn import.

Parameters:

Name Type Description Default
X ArrayLike | Dataset

Feature matrix.

required
y ArrayLike

True class labels.

required
sample_weight ArrayLike | None

Per-row weights for the accuracy computation. None weights every row equally.

None

Returns:

Type Description
float

The accuracy score.

Raises:

Type Description
ValueError

If sample_weight sums to zero, or y or sample_weight disagrees with the predictions in row count.

from_file(path) classmethod #

Load a saved .msgpack classifier.

The native format stores only the booster, so classes_ comes back as the encoded ids 0..K-1, and predict returns those ids rather than the label values passed to fit. Pickle the estimator to preserve original labels.

Raises:

Type Description
ValueError

If the saved model's objective is not logloss or softmax.

OrderedTargetEncoder #

Replace categorical code columns with causal running target means.

Categories must arrive as numeric codes in float cells (.cat.codes for pandas users); NaN is treated as one shared "missing" category. fit_transform encodes the training set causally — each row sees the label mean of earlier rows only, under a seeded permutation — while transform applies full-training-set statistics, matching what a deployed model sees. Targets are binary {0, 1} or regression values.

Parameters:

Name Type Description Default
columns

Indices of the columns to encode.

required
prior_weight float

Pseudo-count of prior belief blended into every smoothed mean; larger values pull low-count categories harder toward the global mean.

10.0
n_permutations int

Number of seeded permutations averaged into the causal encoding (variance reduction).

1
keep_codes bool

If True, appends the raw code columns after the features, giving trees both views (measured worth +0.005 AUC on the amazon benchmark).

True
seed int

Base seed for the permutations; permutation p uses seed + p.

0
cross int

1 encodes single columns only. 2 additionally appends an ordered-TS column for every pair of encoded columns (codes must be integers below 2^31; pairs unseen in training resolve to the prior). Output layout is always [features with TS in place] + [kept codes] + [pair TS columns].

1

Raises:

Type Description
ValueError

If cross is not 1 or 2, n_permutations is below 1, or prior_weight is not a finite number above 0.

fit_transform(X, y) #

Causally encode the train fold and learn full-fold statistics.

Each row's encoding uses only rows before it in a seeded permutation (the CatBoost ordered-TS trick), so the train encoding leaks no row's own label. The statistics stored for transform use the whole fold.

Parameters:

Name Type Description Default
X

Feature matrix; the columns named in self.columns hold numeric category codes.

required
y

Target values, binary {0, 1} or regression.

required

Returns:

Type Description
ndarray

The encoded matrix, columns in the layout documented on the class.

transform(X) #

Encode new rows with the full-fold statistics learned in fit.

Parameters:

Name Type Description Default
X

Feature matrix; the columns named in self.columns hold numeric category codes.

required

Returns:

Type Description
ndarray

The encoded matrix, columns in the layout documented on the class.

Raises:

Type Description
RuntimeError

If called before fit_transform.

Build and device#

cuda_available() #

True when the binary carries the CUDA backend and a usable device is present (cuda_* growers can train).

__version__ = importlib.metadata.version('bonsai-gbt') module-attribute #