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
|
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; |
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 |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
With |
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 |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
A Dataset that owns its own plane; its |
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 |
save(path)
#
Save the model (MessagePack) with its bin mappers and config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Output file; |
required |
predict(X, num_iteration=0)
#
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 |
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(X)
#
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 |
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)
#
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_leaf(X)
#
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)
#
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
|
|
load(path)
#
Load a model saved by Model.save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
A |
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 |
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'
|
sampler
|
str
|
Row sampler name; |
'all_rows'
|
objective
|
str
|
One of bonsai's own: |
'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 |
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 |
42
|
max_bin
|
int | None
|
Histogram bin cap; None leaves the native default. |
None
|
subsample
|
float | None
|
Row-sampling fraction; switches the sampler to |
None
|
device
|
str | None
|
|
None
|
quantile_alpha
|
float | None
|
The quantile to fit when |
None
|
params
|
dict | ParamsOps | None
|
Overrides beyond the first-class kwargs: a |
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 |
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 |
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 |
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
|
|
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 |
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 |
None
|
init_model
|
str | None
|
Path to a saved |
None
|
feature_names
|
Sequence[str] | None
|
One name per column, overriding any string column names X
carries. Fitted names land in |
None
|
Returns:
| Type | Description |
|---|---|
_BonsaiEstimator
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
predict(X, num_iteration=0)
#
Predict with the fitted model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike | Dataset
|
Feature matrix, or a |
required |
num_iteration
|
int
|
Truncates the ensemble to its first |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predictions, one per row of |
staged_predict(X)
#
Predict after each boosting iteration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike | Dataset
|
As for |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
predict_leaf(X)
#
Predict per-tree leaf indices, for feature engineering / embedding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike | Dataset
|
As for |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
importance(type='gain')
#
Compute raw per-feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type
|
str
|
|
'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
|
|
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 |
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'
|
sampler
|
str
|
Row sampler name; |
'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 |
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 |
42
|
max_bin
|
int | None
|
Histogram bin cap; None leaves the native default. |
None
|
subsample
|
float | None
|
Row-sampling fraction; switches the sampler to |
None
|
device
|
str | None
|
|
None
|
params
|
dict | ParamsOps | None
|
Overrides beyond the first-class kwargs: a |
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 |
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 |
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 |
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
|
|
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 |
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 |
None
|
init_model
|
str | None
|
Path to a saved |
None
|
feature_names
|
Sequence[str] | None
|
One name per column, overriding any string column names X
carries. Fitted names land in |
None
|
Returns:
| Type | Description |
|---|---|
_BonsaiEstimator
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
predict(X, num_iteration=0)
#
Predict with the fitted model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike | Dataset
|
Feature matrix, or a |
required |
num_iteration
|
int
|
Truncates the ensemble to its first |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predictions, one per row of |
staged_predict(X)
#
Predict after each boosting iteration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike | Dataset
|
As for |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
predict_leaf(X)
#
Predict per-tree leaf indices, for feature engineering / embedding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike | Dataset
|
As for |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
importance(type='gain')
#
Compute raw per-feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type
|
str
|
|
'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
|
|
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
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 |
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 |
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 |
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
|
1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The encoded matrix, columns in the layout documented on the class. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called before |
Build and device#
cuda_available()
#
True when the binary carries the CUDA backend and a usable device is present (cuda_* growers can train).