Struct Booster

Source
pub struct Booster { /* private fields */ }
Expand description

Core model in XGBoost, containing functions for training, evaluating and predicting.

Usually created through the train function, which creates and trains a Booster in a single call.

For more fine grained usage, can be created using new or new_with_cached_dmats, then trained by calling update or update_custom in a loop.

Implementations§

Source§

impl Booster

Source

pub fn new(params: &BoosterParameters) -> XGBResult<Self>

Create a new Booster model with given parameters.

This model can then be trained using calls to update/boost as appropriate.

The train function is often a more convenient way of constructing, training and evaluating a Booster in a single call.

Source

pub fn new_with_json_config( dmats: &[&DMatrix], config: HashMap<String, String>, ) -> XGBResult<Self>

Source

pub fn new_with_cached_dmats( params: &BoosterParameters, dmats: &[&DMatrix], ) -> XGBResult<Self>

Create a new booster model with given parameters and list of DMatrix to cache.

Cached DMatrix can sometimes be used internally by XGBoost to speed up certain operations.

Source

pub fn save<P: AsRef<Path>>(&self, path: P) -> XGBResult<()>

Save this Booster as a binary file at given path.

§Panics

Will panic, if the model saving fails with an error not coming from XGBoost.

Source

pub fn save_to_buffer(&self, raw_format: String) -> XGBResult<String>

Save the model to a in memory buffer representation instead of file.

§Arguments

  • raw_format - Format of output buffer. Can be “json”, “ubj” or “deprecated”. Right now the default is “deprecated” but it will be changed to “ubj” (univeral binary json) in the future.
§Returns

An in memory buffer representation of the model

§Panics

Will panic, if the model saving fails with an error not coming from XGBoost.

Source

pub fn load<P: AsRef<Path>>(path: P) -> XGBResult<Self>

Load a Booster from a binary file at given path.

§Panics

Will panic, if the model couldn’t be loaded, because of an error not coming from XGBoost. Could also panic, if a Booster couldn’t be created because of an error not coming from XGBoost.

Source

pub fn load_buffer(bytes: &[u8]) -> XGBResult<Self>

Load a Booster directly from a buffer.

Source

pub fn train_increment( params: &TrainingParameters<'_>, model_name: &str, ) -> XGBResult<Self>

Trains the model incrementally.

§Panics

Will panic, if XGBoost fails to load the number of processes from Rabit.

Source

pub fn train_with_booster_params( evaluation_sets: Option<&[(&DMatrix, &str)]>, dtrain: &DMatrix, config: BoosterParameters, bst: Option<Booster>, ) -> XGBResult<Self>

Source

pub fn train( evaluation_sets: Option<&[(&DMatrix, &str)]>, dtrain: &DMatrix, config: HashMap<String, String>, bst: Option<Booster>, ) -> XGBResult<Self>

Source

pub fn save_config(&self) -> String

Saves the config as a json file.

§Panics

Will panic, if the config cant be created, because of an error not coming from XGBoost.

Source

pub fn set_params(&mut self, p: &BoosterParameters) -> XGBResult<()>

Update this Booster’s parameters.

Source

pub fn update(&mut self, dtrain: &DMatrix, iteration: i32) -> XGBResult<()>

Update this model by training it for one round with given training matrix.

Uses XGBoost’s objective function that was specificed in this Booster’s learning objective parameters.

  • dtrain - matrix to train the model with for a single iteration
  • iteration - current iteration number
Source

pub fn update_custom( &mut self, dtrain: &DMatrix, objective_fn: fn(&[f32], &DMatrix) -> (Vec<f32>, Vec<f32>), ) -> XGBResult<()>

Update this model by training it for one round with a custom objective function.

Source

pub fn evaluate( &self, dmat: &DMatrix, name: &str, ) -> XGBResult<HashMap<String, f32>>

Evaluate given matrix against this model using metrics defined in this model’s parameters.

See parameter::learning::EvaluationMetric for a full list.

Returns a map of evaluation metric name to score.

§Panics

Will panic, if the given matrix cannot be evaluated with the given metric.

Source

pub fn get_attribute(&self, key: &str) -> XGBResult<Option<String>>

Get a string attribute that was previously set for this model.

§Panics

Will panic, if the attribute can’t be retrieved, or the key can’t be represented as a CString.

Source

pub fn set_attribute(&mut self, key: &str, value: &str) -> XGBResult<()>

Store a string attribute in this model with given key.

§Panics

Will panic, if the attribute can’t be set by XGBoost.

Source

pub fn get_attribute_names(&self) -> XGBResult<Vec<String>>

Get names of all attributes stored in this model. Values can then be fetched with calls to get_attribute.

§Panics

Will panic, if the attribtue name cannot be retrieved from XGBoost.

Source

pub fn predict_from_dmat( &self, dmat: &DMatrix, out_shape: &[u64; 2], out_dim: &mut u64, ) -> XGBResult<Vec<f32>>

This method calculates the predicions from a given matrix.

§Panics

Will panic, if XGBoost cannot make predictions.

Source

pub fn predict(&self, dmat: &DMatrix) -> XGBResult<Vec<f32>>

Predict results for given data.

Returns an array containing one entry per row in the given data.

§Panics

Will panic, if the predictions aren’t possible for XGBoost or the results cannot be parsed.

Source

pub fn predict_margin(&self, dmat: &DMatrix) -> XGBResult<Vec<f32>>

Predict margin for given data.

Returns an array containing one entry per row in the given data.

§Panics

Will panic, if the predictions aren’t possible for XGBoost or the results cannot be parsed.

Source

pub fn predict_leaf( &self, dmat: &DMatrix, ) -> XGBResult<(Vec<f32>, (usize, usize))>

Get predicted leaf index for each sample in given data.

Returns an array of shape (number of samples, number of trees) as tuple of (data, num_rows).

Note: the leaf index of a tree is unique per tree, so e.g. leaf 1 could be found in both tree 1 and tree 0.

§Panics

Will panic, if the prediction of a leave isn’t possible for XGBoost or the data cannot be parsed.

Source

pub fn predict_contributions( &self, dmat: &DMatrix, ) -> XGBResult<(Vec<f32>, (usize, usize))>

Get feature contributions (SHAP values) for each prediction.

The sum of all feature contributions is equal to the run untransformed margin value of the prediction.

Returns an array of shape (number of samples, number of features + 1) as a tuple of (data, num_rows). The final column contains the bias term.

§Panics

Will panic, if XGBoost cannot predict the data or parse the result.

Source

pub fn predict_interactions( &self, dmat: &DMatrix, ) -> XGBResult<(Vec<f32>, (usize, usize, usize))>

Get SHAP interaction values for each pair of features for each prediction.

The sum of each row (or column) of the interaction values equals the corresponding SHAP value (from predict_contributions), and the sum of the entire matrix equals the raw untransformed margin value of the prediction.

Returns an array of shape (number of samples, number of features + 1, number of features + 1). The final row and column contain the bias terms.

§Panics

Will panic, if XGBoost cannot predict the data or parse the result.

Source

pub fn dump_model( &self, with_statistics: bool, feature_map: Option<&FeatureMap>, ) -> XGBResult<String>

Get a dump of this model as a string.

  • with_statistics - whether to include statistics in output dump
  • feature_map - if given, map feature IDs to feature names from given map

Trait Implementations§

Source§

impl Clone for Booster

Source§

fn clone(&self) -> Booster

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Drop for Booster

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Send for Booster

Source§

impl Sync for Booster

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.