perpetual 0.7.11__cp313-cp313-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of perpetual might be problematic. Click here for more details.

perpetual/booster.py ADDED
@@ -0,0 +1,958 @@
1
+ import json
2
+ import inspect
3
+ import warnings
4
+ from typing_extensions import Self
5
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union, cast
6
+
7
+ import numpy as np
8
+
9
+ from perpetual.perpetual import PerpetualBooster as CratePerpetualBooster # type: ignore
10
+ from perpetual.perpetual import MultiOutputBooster as CrateMultiOutputBooster # type: ignore
11
+ from perpetual.serialize import BaseSerializer, ObjectSerializer
12
+ from perpetual.types import BoosterType, MultiOutputBoosterType
13
+ from perpetual.data import Node
14
+ from perpetual.utils import (
15
+ CONTRIBUTION_METHODS,
16
+ convert_input_array,
17
+ convert_input_frame,
18
+ transform_input_frame,
19
+ type_df,
20
+ )
21
+
22
+
23
+ class PerpetualBooster:
24
+ # Define the metadata parameters
25
+ # that are present on all instances of this class
26
+ # this is useful for parameters that should be
27
+ # attempted to be loaded in and set
28
+ # as attributes on the booster after it is loaded.
29
+ meta_data_attributes: Dict[str, BaseSerializer] = {
30
+ "feature_names_in_": ObjectSerializer(),
31
+ "n_features_": ObjectSerializer(),
32
+ "feature_importance_method": ObjectSerializer(),
33
+ "cat_mapping": ObjectSerializer(),
34
+ "classes_": ObjectSerializer(),
35
+ }
36
+
37
+ def __init__(
38
+ self,
39
+ *,
40
+ objective: str = "LogLoss",
41
+ num_threads: Optional[int] = None,
42
+ monotone_constraints: Union[Dict[Any, int], None] = None,
43
+ force_children_to_bound_parent: bool = False,
44
+ missing: float = np.nan,
45
+ allow_missing_splits: bool = True,
46
+ create_missing_branch: bool = False,
47
+ terminate_missing_features: Optional[Iterable[Any]] = None,
48
+ missing_node_treatment: str = "None",
49
+ log_iterations: int = 0,
50
+ feature_importance_method: str = "Gain",
51
+ budget: Optional[float] = None,
52
+ alpha: Optional[float] = None,
53
+ reset: Optional[bool] = None,
54
+ categorical_features: Union[Iterable[int], Iterable[str], str, None] = "auto",
55
+ timeout: Optional[float] = None,
56
+ iteration_limit: Optional[int] = None,
57
+ memory_limit: Optional[float] = None,
58
+ stopping_rounds: Optional[int] = None,
59
+ max_bin: int = 256,
60
+ max_cat: int = 1000,
61
+ ):
62
+ """PerpetualBooster class, used to generate gradient boosted decision tree ensembles.
63
+ The following parameters can also be specified in the fit method to override the values in the constructor:
64
+ budget, alpha, reset, categorical_features, timeout, iteration_limit, memory_limit, and stopping_rounds.
65
+
66
+ Args:
67
+ objective (str, optional): Learning objective function to be used for optimization.
68
+ Valid options include "LogLoss" to use logistic loss (classification),
69
+ "SquaredLoss" to use squared error (regression),
70
+ "QuantileLoss" to use quantile error (regression).
71
+ Defaults to "LogLoss".
72
+ num_threads (int, optional): Number of threads to be used during training.
73
+ monotone_constraints (Dict[Any, int], optional): Constraints that are used to enforce a
74
+ specific relationship between the training features and the target variable. A dictionary
75
+ should be provided where the keys are the feature index value if the model will be fit on
76
+ a numpy array, or a feature name if it will be fit on a Dataframe. The values of
77
+ the dictionary should be an integer value of -1, 1, or 0 to specify the relationship
78
+ that should be estimated between the respective feature and the target variable.
79
+ Use a value of -1 to enforce a negative relationship, 1 a positive relationship,
80
+ and 0 will enforce no specific relationship at all. Features not included in the
81
+ mapping will not have any constraint applied. If `None` is passed, no constraints
82
+ will be enforced on any variable. Defaults to `None`.
83
+ force_children_to_bound_parent (bool, optional): Setting this parameter to `True` will restrict children nodes, so that they always contain the parent node inside of their range. Without setting this it's possible that both, the left and the right nodes could be greater, than or less than, the parent node. Defaults to `False`.
84
+ missing (float, optional): Value to consider missing, when training and predicting
85
+ with the booster. Defaults to `np.nan`.
86
+ allow_missing_splits (bool, optional): Allow for splits to be made such that all missing values go
87
+ down one branch, and all non-missing values go down the other, if this results
88
+ in the greatest reduction of loss. If this is false, splits will only be made on non
89
+ missing values. If `create_missing_branch` is set to `True` having this parameter be
90
+ set to `True` will result in the missing branch further split, if this parameter
91
+ is `False` then in that case the missing branch will always be a terminal node.
92
+ Defaults to `True`.
93
+ create_missing_branch (bool, optional): An experimental parameter, that if `True`, will
94
+ create a separate branch for missing, creating a ternary tree, the missing node will be given the same
95
+ weight value as the parent node. If this parameter is `False`, missing will be sent
96
+ down either the left or right branch, creating a binary tree. Defaults to `False`.
97
+ terminate_missing_features (Set[Any], optional): An optional iterable of features
98
+ (either strings, or integer values specifying the feature indices if numpy arrays are used for fitting),
99
+ for which the missing node will always be terminated, even if `allow_missing_splits` is set to true.
100
+ This value is only valid if `create_missing_branch` is also True.
101
+ missing_node_treatment (str, optional): Method for selecting the `weight` for the missing node, if `create_missing_branch` is set to `True`. Defaults to "None". Valid options are:
102
+ - "None": Calculate missing node weight values without any constraints.
103
+ - "AssignToParent": Assign the weight of the missing node to that of the parent.
104
+ - "AverageLeafWeight": After training each tree, starting from the bottom of the tree, assign the missing node weight to the weighted average of the left and right child nodes. Next assign the parent to the weighted average of the children nodes. This is performed recursively up through the entire tree. This is performed as a post processing step on each tree after it is built, and prior to updating the predictions for which to train the next tree.
105
+ - "AverageNodeWeight": Set the missing node to be equal to the weighted average weight of the left and the right nodes.
106
+ log_iterations (int, optional): Setting to a value (N) other than zero will result in information being logged about ever N iterations, info can be interacted with directly with the python [`logging`](https://docs.python.org/3/howto/logging.html) module. For an example of how to utilize the logging information see the example [here](/#logging-output).
107
+ feature_importance_method (str, optional): The feature importance method type that will be used to calculate the `feature_importances_` attribute on the booster.
108
+ budget (float, optional): a positive number for fitting budget. Increasing this number will more
109
+ likely result in more boosting rounds and more increased predictive power.
110
+ Default value is 1.0.
111
+ alpha (float, optional): only used in quantile regression.
112
+ reset (bool, optional): whether to reset the model or continue training.
113
+ categorical_features (Union[Iterable[int], Iterable[str], str, None], optional): The names or indices for categorical features.
114
+ Defaults to `auto` for Polars or Pandas categorical data types.
115
+ timeout (float, optional): optional fit timeout in seconds
116
+ iteration_limit (int, optional): optional limit for the number of boosting rounds. The default value is 1000 boosting rounds.
117
+ The algorithm automatically stops for most of the cases before hitting this limit.
118
+ If you want to experiment with very high budget (>2.0), you can also increase this limit.
119
+ memory_limit (float, optional): optional limit for memory allocation in GB. If not set, the memory will be allocated based on
120
+ available memory and the algorithm requirements.
121
+ stopping_rounds (int, optional): optional limit for auto stopping.
122
+ max_bin (int, optional): maximum number of bins for feature discretization. Defaults to 256.
123
+ max_cat (int, optional): Maximum number of unique categories for a categorical feature.
124
+ Features with more categories will be treated as numerical.
125
+ Defaults to 1000.
126
+
127
+ Raises:
128
+ TypeError: Raised if an invalid dtype is passed.
129
+
130
+ Example:
131
+ Once, the booster has been initialized, it can be fit on a provided dataset, and performance field. After fitting, the model can be used to predict on a dataset.
132
+ In the case of this example, the predictions are the log odds of a given record being 1.
133
+
134
+ ```python
135
+ # Small example dataset
136
+ from seaborn import load_dataset
137
+
138
+ df = load_dataset("titanic")
139
+ X = df.select_dtypes("number").drop(columns=["survived"])
140
+ y = df["survived"]
141
+
142
+ # Initialize a booster with defaults.
143
+ from perpetual import PerpetualBooster
144
+ model = PerpetualBooster(objective="LogLoss")
145
+ model.fit(X, y)
146
+
147
+ # Predict on data
148
+ model.predict(X.head())
149
+ # array([-1.94919663, 2.25863229, 0.32963671, 2.48732194, -3.00371813])
150
+
151
+ # predict contributions
152
+ model.predict_contributions(X.head())
153
+ # array([[-0.63014213, 0.33880048, -0.16520798, -0.07798772, -0.85083578,
154
+ # -1.07720813],
155
+ # [ 1.05406709, 0.08825999, 0.21662544, -0.12083538, 0.35209258,
156
+ # -1.07720813],
157
+ ```
158
+
159
+ """
160
+
161
+ terminate_missing_features_ = (
162
+ set() if terminate_missing_features is None else terminate_missing_features
163
+ )
164
+ monotone_constraints_ = (
165
+ {} if monotone_constraints is None else monotone_constraints
166
+ )
167
+
168
+ self.objective = objective
169
+ self.num_threads = num_threads
170
+ self.monotone_constraints = monotone_constraints_
171
+ self.force_children_to_bound_parent = force_children_to_bound_parent
172
+ self.allow_missing_splits = allow_missing_splits
173
+ self.missing = missing
174
+ self.create_missing_branch = create_missing_branch
175
+ self.terminate_missing_features = terminate_missing_features_
176
+ self.missing_node_treatment = missing_node_treatment
177
+ self.log_iterations = log_iterations
178
+ self.feature_importance_method = feature_importance_method
179
+ self.budget = budget
180
+ self.alpha = alpha
181
+ self.reset = reset
182
+ self.categorical_features = categorical_features
183
+ self.timeout = timeout
184
+ self.iteration_limit = iteration_limit
185
+ self.memory_limit = memory_limit
186
+ self.stopping_rounds = stopping_rounds
187
+ self.max_bin = max_bin
188
+ self.max_cat = max_cat
189
+
190
+ booster = CratePerpetualBooster(
191
+ objective=self.objective,
192
+ max_bin=self.max_bin,
193
+ num_threads=self.num_threads,
194
+ monotone_constraints=dict(),
195
+ force_children_to_bound_parent=self.force_children_to_bound_parent,
196
+ missing=self.missing,
197
+ allow_missing_splits=self.allow_missing_splits,
198
+ create_missing_branch=self.create_missing_branch,
199
+ terminate_missing_features=set(),
200
+ missing_node_treatment=self.missing_node_treatment,
201
+ log_iterations=self.log_iterations,
202
+ )
203
+ self.booster = cast(BoosterType, booster)
204
+
205
+ def fit(
206
+ self,
207
+ X,
208
+ y,
209
+ sample_weight=None,
210
+ budget: Optional[float] = None,
211
+ alpha: Optional[float] = None,
212
+ reset: Optional[bool] = None,
213
+ categorical_features: Union[Iterable[int], Iterable[str], str, None] = "auto",
214
+ timeout: Optional[float] = None,
215
+ iteration_limit: Optional[int] = None,
216
+ memory_limit: Optional[float] = None,
217
+ stopping_rounds: Optional[int] = None,
218
+ ) -> Self:
219
+ """Fit the gradient booster on a provided dataset.
220
+
221
+ Args:
222
+ X (FrameLike): Either a Polars or Pandas DataFrame, or a 2 dimensional Numpy array.
223
+ y (Union[FrameLike, ArrayLike]): Either a Polars or Pandas DataFrame or Series,
224
+ or a 1 or 2 dimensional Numpy array.
225
+ sample_weight (Union[ArrayLike, None], optional): Instance weights to use when
226
+ training the model. If None is passed, a weight of 1 will be used for every record.
227
+ Defaults to None.
228
+ budget (float, optional): a positive number for fitting budget. Increasing this number will more
229
+ likely result in more boosting rounds and more increased predictive power.
230
+ Defaults to 1.0.
231
+ alpha (float, optional): only used in quantile regression.
232
+ reset (bool, optional): whether to reset the model or continue training.
233
+ categorical_features (Union[Iterable[int], Iterable[str], str, None], optional): The names or indices for categorical features.
234
+ Defaults to `auto` for Polars or Pandas categorical data types.
235
+ timeout (float, optional): optional fit timeout in seconds
236
+ iteration_limit (int, optional): optional limit for the number of boosting rounds. The default value is 1000 boosting rounds.
237
+ The algorithm automatically stops for most of the cases before hitting this limit.
238
+ If you want to experiment with very high budget (>2.0), you can also increase this limit.
239
+ memory_limit (float, optional): optional limit for memory allocation in GB. If not set, the memory will be allocated based on
240
+ available memory and the algorithm requirements.
241
+ stopping_rounds (int, optional): optional limit for auto stopping. Defaults to 3.
242
+ """
243
+
244
+ features_, flat_data, rows, cols, categorical_features_, cat_mapping = (
245
+ convert_input_frame(
246
+ X, categorical_features or self.categorical_features, self.max_cat
247
+ )
248
+ )
249
+ self.n_features_ = cols
250
+ self.cat_mapping = cat_mapping
251
+ self.feature_names_in_ = features_
252
+
253
+ y_, classes_ = convert_input_array(y, self.objective)
254
+ self.classes_ = np.array(classes_).tolist()
255
+
256
+ if sample_weight is None:
257
+ sample_weight_ = None
258
+ else:
259
+ sample_weight_, _ = convert_input_array(sample_weight, self.objective)
260
+
261
+ # Convert the monotone constraints into the form needed
262
+ # by the rust code.
263
+ crate_mc = self._standardize_monotonicity_map(X)
264
+ crate_tmf = self._standardize_terminate_missing_features(X)
265
+
266
+ if (len(classes_) <= 2) or (
267
+ len(classes_) > 1 and self.objective == "SquaredLoss"
268
+ ):
269
+ booster = CratePerpetualBooster(
270
+ objective=self.objective,
271
+ max_bin=self.max_bin,
272
+ num_threads=self.num_threads,
273
+ monotone_constraints=crate_mc,
274
+ force_children_to_bound_parent=self.force_children_to_bound_parent,
275
+ missing=self.missing,
276
+ allow_missing_splits=self.allow_missing_splits,
277
+ create_missing_branch=self.create_missing_branch,
278
+ terminate_missing_features=crate_tmf,
279
+ missing_node_treatment=self.missing_node_treatment,
280
+ log_iterations=self.log_iterations,
281
+ )
282
+ self.booster = cast(BoosterType, booster)
283
+ else:
284
+ booster = CrateMultiOutputBooster(
285
+ n_boosters=len(classes_),
286
+ objective=self.objective,
287
+ max_bin=self.max_bin,
288
+ num_threads=self.num_threads,
289
+ monotone_constraints=crate_mc,
290
+ force_children_to_bound_parent=self.force_children_to_bound_parent,
291
+ missing=self.missing,
292
+ allow_missing_splits=self.allow_missing_splits,
293
+ create_missing_branch=self.create_missing_branch,
294
+ terminate_missing_features=crate_tmf,
295
+ missing_node_treatment=self.missing_node_treatment,
296
+ log_iterations=self.log_iterations,
297
+ )
298
+ self.booster = cast(MultiOutputBoosterType, booster)
299
+
300
+ self._set_metadata_attributes("n_features_", self.n_features_)
301
+ self._set_metadata_attributes("cat_mapping", self.cat_mapping)
302
+ self._set_metadata_attributes("feature_names_in_", self.feature_names_in_)
303
+ self._set_metadata_attributes(
304
+ "feature_importance_method", self.feature_importance_method
305
+ )
306
+ self._set_metadata_attributes("classes_", self.classes_)
307
+
308
+ self.booster.fit(
309
+ flat_data=flat_data,
310
+ rows=rows,
311
+ cols=cols,
312
+ y=y_,
313
+ budget=budget or self.budget,
314
+ sample_weight=sample_weight_, # type: ignore
315
+ alpha=alpha or self.alpha,
316
+ reset=reset or self.reset,
317
+ categorical_features=categorical_features_, # type: ignore
318
+ timeout=timeout or self.timeout,
319
+ iteration_limit=iteration_limit or self.iteration_limit,
320
+ memory_limit=memory_limit or self.memory_limit,
321
+ stopping_rounds=stopping_rounds or self.stopping_rounds,
322
+ )
323
+
324
+ return self
325
+
326
+ def _validate_features(self, features: List[str]):
327
+ if len(features) > 0 and hasattr(self, "feature_names_in_"):
328
+ if features[0] != "0" and self.feature_names_in_[0] != "0":
329
+ if features != self.feature_names_in_:
330
+ raise ValueError(
331
+ f"Columns mismatch between data {features} passed, and data {self.feature_names_in_} used at fit."
332
+ )
333
+
334
+ def predict(self, X, parallel: Union[bool, None] = None) -> np.ndarray:
335
+ """Predict with the fitted booster on new data.
336
+
337
+ Args:
338
+ X (FrameLike): Either a Polars or Pandas DataFrame, or a 2 dimensional Numpy array.
339
+ parallel (Union[bool, None], optional): Optionally specify if the predict
340
+ function should run in parallel on multiple threads. If `None` is
341
+ passed, the `parallel` attribute of the booster will be used.
342
+ Defaults to `None`.
343
+
344
+ Returns:
345
+ np.ndarray: Returns a numpy array of the predictions.
346
+ """
347
+ features_, flat_data, rows, cols = transform_input_frame(X, self.cat_mapping)
348
+ self._validate_features(features_)
349
+
350
+ if len(self.classes_) == 0:
351
+ return self.booster.predict(
352
+ flat_data=flat_data,
353
+ rows=rows,
354
+ cols=cols,
355
+ parallel=parallel,
356
+ )
357
+ elif len(self.classes_) == 2:
358
+ return np.rint(
359
+ self.booster.predict_proba(
360
+ flat_data=flat_data,
361
+ rows=rows,
362
+ cols=cols,
363
+ parallel=parallel,
364
+ )
365
+ )
366
+ else:
367
+ preds = self.booster.predict(
368
+ flat_data=flat_data,
369
+ rows=rows,
370
+ cols=cols,
371
+ parallel=parallel,
372
+ )
373
+ preds_matrix = preds.reshape((-1, len(self.classes_)), order="F")
374
+ indices = np.argmax(preds_matrix, axis=1)
375
+ return np.array([self.classes_[i] for i in indices])
376
+
377
+ def predict_proba(self, X, parallel: Union[bool, None] = None) -> np.ndarray:
378
+ """Predict probabilities with the fitted booster on new data.
379
+
380
+ Args:
381
+ X (FrameLike): Either a Polars or Pandas DataFrame, or a 2 dimensional Numpy array.
382
+ parallel (Union[bool, None], optional): Optionally specify if the predict
383
+ function should run in parallel on multiple threads. If `None` is
384
+ passed, the `parallel` attribute of the booster will be used.
385
+ Defaults to `None`.
386
+
387
+ Returns:
388
+ np.ndarray, shape (n_samples, n_classes): Returns a numpy array of the class probabilities.
389
+ """
390
+ features_, flat_data, rows, cols = transform_input_frame(X, self.cat_mapping)
391
+ self._validate_features(features_)
392
+
393
+ if len(self.classes_) > 2:
394
+ probabilities = self.booster.predict_proba(
395
+ flat_data=flat_data,
396
+ rows=rows,
397
+ cols=cols,
398
+ parallel=parallel,
399
+ )
400
+ return probabilities.reshape((-1, len(self.classes_)), order="C")
401
+ elif len(self.classes_) == 2:
402
+ probabilities = self.booster.predict_proba(
403
+ flat_data=flat_data,
404
+ rows=rows,
405
+ cols=cols,
406
+ parallel=parallel,
407
+ )
408
+ return np.concatenate(
409
+ [(1.0 - probabilities).reshape(-1, 1), probabilities.reshape(-1, 1)],
410
+ axis=1,
411
+ )
412
+ else:
413
+ raise NotImplementedError(
414
+ f"predict_proba not implemented for regression. n_classes = {len(self.classes_)}"
415
+ )
416
+
417
+ def predict_log_proba(self, X, parallel: Union[bool, None] = None) -> np.ndarray:
418
+ """Predict class log-probabilities with the fitted booster on new data.
419
+
420
+ Args:
421
+ X (FrameLike): Either a Polars or Pandas DataFrame, or a 2 dimensional Numpy array.
422
+ parallel (Union[bool, None], optional): Optionally specify if the predict
423
+ function should run in parallel on multiple threads. If `None` is
424
+ passed, the `parallel` attribute of the booster will be used.
425
+ Defaults to `None`.
426
+
427
+ Returns:
428
+ np.ndarray: Returns a numpy array of the predictions.
429
+ """
430
+ features_, flat_data, rows, cols = transform_input_frame(X, self.cat_mapping)
431
+ self._validate_features(features_)
432
+
433
+ if len(self.classes_) > 2:
434
+ preds = self.booster.predict(
435
+ flat_data=flat_data,
436
+ rows=rows,
437
+ cols=cols,
438
+ parallel=parallel,
439
+ )
440
+ return preds.reshape((-1, len(self.classes_)), order="F")
441
+ elif len(self.classes_) == 2:
442
+ return self.booster.predict(
443
+ flat_data=flat_data,
444
+ rows=rows,
445
+ cols=cols,
446
+ parallel=parallel,
447
+ )
448
+ else:
449
+ raise NotImplementedError(
450
+ "predict_log_proba not implemented for regression."
451
+ )
452
+
453
+ @property
454
+ def feature_importances_(self) -> np.ndarray:
455
+ vals = self.calculate_feature_importance(
456
+ method=self.feature_importance_method, normalize=True
457
+ )
458
+ if hasattr(self, "feature_names_in_"):
459
+ vals = cast(Dict[str, float], vals)
460
+ return np.array([vals.get(ft, 0.0) for ft in self.feature_names_in_])
461
+ else:
462
+ vals = cast(Dict[int, float], vals)
463
+ return np.array([vals.get(ft, 0.0) for ft in range(self.n_features_)])
464
+
465
+ def predict_contributions(
466
+ self, X, method: str = "Average", parallel: Union[bool, None] = None
467
+ ) -> np.ndarray:
468
+ """Predict with the fitted booster on new data, returning the feature
469
+ contribution matrix. The last column is the bias term.
470
+
471
+
472
+ Args:
473
+ X (FrameLike): Either a pandas DataFrame, or a 2 dimensional numpy array.
474
+ method (str, optional): Method to calculate the contributions, available options are:
475
+
476
+ - "Average": If this option is specified, the average internal node values are calculated.
477
+ - "Shapley": Using this option will calculate contributions using the tree shap algorithm.
478
+ - "Weight": This method will use the internal leaf weights, to calculate the contributions. This is the same as what is described by Saabas [here](https://blog.datadive.net/interpreting-random-forests/).
479
+ - "BranchDifference": This method will calculate contributions by subtracting the weight of the node the record will travel down by the weight of the other non-missing branch. This method does not have the property where the contributions summed is equal to the final prediction of the model.
480
+ - "MidpointDifference": This method will calculate contributions by subtracting the weight of the node the record will travel down by the mid-point between the right and left node weighted by the cover of each node. This method does not have the property where the contributions summed is equal to the final prediction of the model.
481
+ - "ModeDifference": This method will calculate contributions by subtracting the weight of the node the record will travel down by the weight of the node with the largest cover (the mode node). This method does not have the property where the contributions summed is equal to the final prediction of the model.
482
+ - "ProbabilityChange": This method is only valid when the objective type is set to "LogLoss". This method will calculate contributions as the change in a records probability of being 1 moving from a parent node to a child node. The sum of the returned contributions matrix, will be equal to the probability a record will be 1. For example, given a model, `model.predict_contributions(X, method="ProbabilityChange") == 1 / (1 + np.exp(-model.predict(X)))`
483
+ parallel (Union[bool, None], optional): Optionally specify if the predict
484
+ function should run in parallel on multiple threads. If `None` is
485
+ passed, the `parallel` attribute of the booster will be used.
486
+ Defaults to `None`.
487
+
488
+ Returns:
489
+ np.ndarray: Returns a numpy array of the predictions.
490
+ """
491
+ features_, flat_data, rows, cols = transform_input_frame(X, self.cat_mapping)
492
+ self._validate_features(features_)
493
+
494
+ contributions = self.booster.predict_contributions(
495
+ flat_data=flat_data,
496
+ rows=rows,
497
+ cols=cols,
498
+ method=CONTRIBUTION_METHODS.get(method, method),
499
+ parallel=parallel,
500
+ )
501
+ return np.reshape(contributions, (rows, cols + 1))
502
+
503
+ def partial_dependence(
504
+ self,
505
+ X,
506
+ feature: Union[str, int],
507
+ samples: Optional[int] = 100,
508
+ exclude_missing: bool = True,
509
+ percentile_bounds: Tuple[float, float] = (0.2, 0.98),
510
+ ) -> np.ndarray:
511
+ """Calculate the partial dependence values of a feature. For each unique
512
+ value of the feature, this gives the estimate of the predicted value for that
513
+ feature, with the effects of all features averaged out. This information gives
514
+ an estimate of how a given feature impacts the model.
515
+
516
+ Args:
517
+ X (FrameLike): Either a pandas DataFrame, or a 2 dimensional numpy array.
518
+ This should be the same data passed into the models fit, or predict,
519
+ with the columns in the same order.
520
+ feature (Union[str, int]): The feature for which to calculate the partial
521
+ dependence values. This can be the name of a column, if the provided
522
+ X is a pandas DataFrame, or the index of the feature.
523
+ samples (Optional[int]): Number of evenly spaced samples to select. If None
524
+ is passed all unique values will be used. Defaults to 100.
525
+ exclude_missing (bool, optional): Should missing excluded from the features? Defaults to True.
526
+ percentile_bounds (Tuple[float, float], optional): Upper and lower percentiles to start at
527
+ when calculating the samples. Defaults to (0.2, 0.98) to cap the samples selected
528
+ at the 5th and 95th percentiles respectively.
529
+
530
+ Raises:
531
+ ValueError: An error will be raised if the provided X parameter is not a
532
+ pandas DataFrame, and a string is provided for the feature.
533
+
534
+ Returns:
535
+ np.ndarray: A 2 dimensional numpy array, where the first column is the
536
+ sorted unique values of the feature, and then the second column
537
+ is the partial dependence values for each feature value.
538
+
539
+ Example:
540
+ This information can be plotted to visualize how a feature is used in the model, like so.
541
+
542
+ ```python
543
+ from seaborn import lineplot
544
+ import matplotlib.pyplot as plt
545
+
546
+ pd_values = model.partial_dependence(X=X, feature="age", samples=None)
547
+
548
+ fig = lineplot(x=pd_values[:,0], y=pd_values[:,1],)
549
+ plt.title("Partial Dependence Plot")
550
+ plt.xlabel("Age")
551
+ plt.ylabel("Log Odds")
552
+ ```
553
+ <img height="340" src="https://github.com/jinlow/forust/raw/main/resources/pdp_plot_age.png">
554
+
555
+ We can see how this is impacted if a model is created, where a specific constraint is applied to the feature using the `monotone_constraint` parameter.
556
+
557
+ ```python
558
+ model = PerpetualBooster(
559
+ objective="LogLoss",
560
+ monotone_constraints={"age": -1},
561
+ )
562
+ model.fit(X, y)
563
+
564
+ pd_values = model.partial_dependence(X=X, feature="age")
565
+ fig = lineplot(
566
+ x=pd_values[:, 0],
567
+ y=pd_values[:, 1],
568
+ )
569
+ plt.title("Partial Dependence Plot with Monotonicity")
570
+ plt.xlabel("Age")
571
+ plt.ylabel("Log Odds")
572
+ ```
573
+ <img height="340" src="https://github.com/jinlow/forust/raw/main/resources/pdp_plot_age_mono.png">
574
+ """
575
+ if isinstance(feature, str):
576
+ if not (type_df(X) == "pandas_df" or type_df(X) == "polars_df"):
577
+ raise ValueError(
578
+ "If `feature` is a string, then the object passed as `X` must be a pandas DataFrame."
579
+ )
580
+ values = X.loc[:, feature].to_numpy()
581
+ if hasattr(self, "feature_names_in_") and self.feature_names_in_[0] != "0":
582
+ [feature_idx] = [
583
+ i for i, v in enumerate(self.feature_names_in_) if v == feature
584
+ ]
585
+ else:
586
+ w_msg = (
587
+ "No feature names were provided at fit, but feature was a string, attempting to "
588
+ + "determine feature index from DataFrame Column, "
589
+ + "ensure columns are the same order as data passed when fit."
590
+ )
591
+ warnings.warn(w_msg)
592
+ [feature_idx] = [i for i, v in enumerate(X.columns) if v == feature]
593
+ elif isinstance(feature, int):
594
+ feature_idx = feature
595
+ if type_df(X) == "pandas_df":
596
+ values = X.to_numpy()[:, feature]
597
+ elif type_df(X) == "polars_df":
598
+ values = X.to_numpy(allow_copy=False)[:, feature]
599
+ else:
600
+ values = X[:, feature]
601
+ else:
602
+ raise ValueError(
603
+ f"The parameter `feature` must be a string, or an int, however an object of type {type(feature)} was passed."
604
+ )
605
+ min_p, max_p = percentile_bounds
606
+ values = values[~(np.isnan(values) | (values == self.missing))]
607
+ if samples is None:
608
+ search_values = np.sort(np.unique(values))
609
+ else:
610
+ # Exclude missing from this calculation.
611
+ search_values = np.quantile(values, np.linspace(min_p, max_p, num=samples))
612
+
613
+ # Add missing back, if they wanted it...
614
+ if not exclude_missing:
615
+ search_values = np.append([self.missing], search_values)
616
+
617
+ res = []
618
+ for v in search_values:
619
+ res.append(
620
+ (v, self.booster.value_partial_dependence(feature=feature_idx, value=v))
621
+ )
622
+ return np.array(res)
623
+
624
+ def calculate_feature_importance(
625
+ self, method: str = "Gain", normalize: bool = True
626
+ ) -> Union[Dict[int, float], Dict[str, float]]:
627
+ """Feature importance values can be calculated with the `calculate_feature_importance` method. This function will return a dictionary of the features and their importance values. It should be noted that if a feature was never used for splitting it will not be returned in importance dictionary.
628
+
629
+ Args:
630
+ method (str, optional): Variable importance method. Defaults to "Gain". Valid options are:
631
+
632
+ - "Weight": The number of times a feature is used to split the data across all trees.
633
+ - "Gain": The average split gain across all splits the feature is used in.
634
+ - "Cover": The average coverage across all splits the feature is used in.
635
+ - "TotalGain": The total gain across all splits the feature is used in.
636
+ - "TotalCover": The total coverage across all splits the feature is used in.
637
+ normalize (bool, optional): Should the importance be normalized to sum to 1? Defaults to `True`.
638
+
639
+ Returns:
640
+ Dict[str, float]: Variable importance values, for features present in the model.
641
+
642
+ Example:
643
+ ```python
644
+ model.calculate_feature_importance("Gain")
645
+ # {
646
+ # 'parch': 0.0713072270154953,
647
+ # 'age': 0.11609109491109848,
648
+ # 'sibsp': 0.1486879289150238,
649
+ # 'fare': 0.14309120178222656,
650
+ # 'pclass': 0.5208225250244141
651
+ # }
652
+ ```
653
+ """
654
+ importance_: Dict[int, float] = self.booster.calculate_feature_importance(
655
+ method=method,
656
+ normalize=normalize,
657
+ )
658
+ if hasattr(self, "feature_names_in_"):
659
+ feature_map: Dict[int, str] = {
660
+ i: f for i, f in enumerate(self.feature_names_in_)
661
+ }
662
+ return {feature_map[i]: v for i, v in importance_.items()}
663
+ return importance_
664
+
665
+ def text_dump(self) -> List[str]:
666
+ """Return all of the trees of the model in text form.
667
+
668
+ Returns:
669
+ List[str]: A list of strings, where each string is a text representation
670
+ of the tree.
671
+ Example:
672
+ ```python
673
+ model.text_dump()[0]
674
+ # 0:[0 < 3] yes=1,no=2,missing=2,gain=91.50833,cover=209.388307
675
+ # 1:[4 < 13.7917] yes=3,no=4,missing=4,gain=28.185467,cover=94.00148
676
+ # 3:[1 < 18] yes=7,no=8,missing=8,gain=1.4576768,cover=22.090348
677
+ # 7:[1 < 17] yes=15,no=16,missing=16,gain=0.691266,cover=0.705011
678
+ # 15:leaf=-0.15120,cover=0.23500
679
+ # 16:leaf=0.154097,cover=0.470007
680
+ ```
681
+ """
682
+ return self.booster.text_dump()
683
+
684
+ def json_dump(self) -> str:
685
+ """Return the booster object as a string.
686
+
687
+ Returns:
688
+ str: The booster dumped as a json object in string form.
689
+ """
690
+ return self.booster.json_dump()
691
+
692
+ @classmethod
693
+ def load_booster(cls, path: str) -> Self:
694
+ """Load a booster object that was saved with the `save_booster` method.
695
+
696
+ Args:
697
+ path (str): Path to the saved booster file.
698
+
699
+ Returns:
700
+ PerpetualBooster: An initialized booster object.
701
+ """
702
+ booster = CratePerpetualBooster.load_booster(str(path))
703
+
704
+ params = booster.get_params()
705
+ with warnings.catch_warnings():
706
+ warnings.simplefilter("ignore")
707
+ c = cls(**params)
708
+ c.booster = booster
709
+ for m in c.meta_data_attributes:
710
+ try:
711
+ m_ = c._get_metadata_attributes(m)
712
+ setattr(c, m, m_)
713
+ # If "feature_names_in_" is present, we know a
714
+ # pandas dataframe was used for fitting, in this case
715
+ # get back the original monotonicity map, with the
716
+ # feature names as keys.
717
+ if m == "feature_names_in_" and c.feature_names_in_[0] != "0":
718
+ if c.monotone_constraints is not None:
719
+ c.monotone_constraints = {
720
+ ft: c.monotone_constraints[i]
721
+ for i, ft in enumerate(c.feature_names_in_)
722
+ }
723
+ except KeyError:
724
+ pass
725
+ return c
726
+
727
+ def save_booster(self, path: str):
728
+ """Save a booster object, the underlying representation is a json file.
729
+
730
+ Args:
731
+ path (str): Path to save the booster object.
732
+ """
733
+ self.booster.save_booster(str(path))
734
+
735
+ def _standardize_monotonicity_map(
736
+ self,
737
+ X,
738
+ ) -> Dict[int, Any]:
739
+ if isinstance(X, np.ndarray):
740
+ return self.monotone_constraints
741
+ else:
742
+ feature_map = {f: i for i, f in enumerate(X.columns)}
743
+ return {feature_map[f]: v for f, v in self.monotone_constraints.items()}
744
+
745
+ def _standardize_terminate_missing_features(
746
+ self,
747
+ X,
748
+ ) -> Set[int]:
749
+ if isinstance(X, np.ndarray):
750
+ return set(self.terminate_missing_features)
751
+ else:
752
+ feature_map = {f: i for i, f in enumerate(X.columns)}
753
+ return set(feature_map[f] for f in self.terminate_missing_features)
754
+
755
+ def insert_metadata(self, key: str, value: str):
756
+ """Insert data into the models metadata, this will be saved on the booster object.
757
+
758
+ Args:
759
+ key (str): Key to give the inserted value in the metadata.
760
+ value (str): String value to assign to the key.
761
+ """ # noqa: E501
762
+ self.booster.insert_metadata(key=key, value=value)
763
+
764
+ def get_metadata(self, key: str) -> str:
765
+ """Get the value associated with a given key, on the boosters metadata.
766
+
767
+ Args:
768
+ key (str): Key of item in metadata.
769
+
770
+ Returns:
771
+ str: Value associated with the provided key in the boosters metadata.
772
+ """
773
+ v = self.booster.get_metadata(key=key)
774
+ return v
775
+
776
+ def _set_metadata_attributes(self, key: str, value: Any) -> None:
777
+ value_ = self.meta_data_attributes[key].serialize(value)
778
+ self.insert_metadata(key=key, value=value_)
779
+
780
+ def _get_metadata_attributes(self, key: str) -> Any:
781
+ value = self.get_metadata(key)
782
+ return self.meta_data_attributes[key].deserialize(value)
783
+
784
+ @property
785
+ def base_score(self) -> Union[float, Iterable[float]]:
786
+ """Base score of the model.
787
+
788
+ Returns:
789
+ Union[float, Iterable[float]]: Base score(s) of the model.
790
+ """
791
+ return self.booster.base_score
792
+
793
+ @property
794
+ def number_of_trees(self) -> Union[int, Iterable[int]]:
795
+ """The number of trees in the model.
796
+
797
+ Returns:
798
+ int: The total number of trees in the model.
799
+ """
800
+ return self.booster.number_of_trees
801
+
802
+ # Make picklable with getstate and setstate
803
+ def __getstate__(self) -> Dict[Any, Any]:
804
+ booster_json = self.json_dump()
805
+ # Delete booster
806
+ # Doing it like this, so it doesn't delete it globally.
807
+ res = {k: v for k, v in self.__dict__.items() if k != "booster"}
808
+ res["__booster_json_file__"] = booster_json
809
+ return res
810
+
811
+ def __setstate__(self, d: Dict[Any, Any]) -> None:
812
+ # Load the booster object the pickled JSon string.
813
+ booster_object = CratePerpetualBooster.from_json(d["__booster_json_file__"])
814
+ d["booster"] = booster_object
815
+ # Are there any new parameters, that need to be added to the python object,
816
+ # that would have been loaded in as defaults on the json object?
817
+ # This makes sure that defaults set with a serde default function get
818
+ # carried through to the python object.
819
+ for p, v in booster_object.get_params().items():
820
+ if p not in d:
821
+ d[p] = v
822
+ del d["__booster_json_file__"]
823
+ self.__dict__ = d
824
+
825
+ # Functions for scikit-learn compatibility, will feel out adding these manually,
826
+ # and then if that feels too unwieldy will add scikit-learn as a dependency.
827
+ def get_params(self, deep=True) -> Dict[str, Any]:
828
+ """Get all of the parameters for the booster.
829
+
830
+ Args:
831
+ deep (bool, optional): This argument does nothing, and is simply here for scikit-learn compatibility.. Defaults to True.
832
+
833
+ Returns:
834
+ Dict[str, Any]: The parameters of the booster.
835
+ """
836
+ args = inspect.getfullargspec(PerpetualBooster).kwonlyargs
837
+ return {param: getattr(self, param) for param in args}
838
+
839
+ def set_params(self, **params: Any) -> Self:
840
+ """Set the parameters of the booster, this has the same effect as reinstating the booster.
841
+
842
+ Returns:
843
+ PerpetualBooster: Booster with new parameters.
844
+ """
845
+ old_params = self.get_params()
846
+ old_params.update(params)
847
+ PerpetualBooster.__init__(self, **old_params)
848
+ return self
849
+
850
+ def get_node_lists(self, map_features_names: bool = True) -> List[List[Node]]:
851
+ """Return the tree structures representation as a list of python objects.
852
+
853
+ Args:
854
+ map_features_names (bool, optional): Should the feature names tried to be mapped to a string, if a pandas dataframe was used. Defaults to True.
855
+
856
+ Returns:
857
+ List[List[Node]]: A list of lists where each sub list is a tree, with all of it's respective nodes.
858
+
859
+ Example:
860
+ This can be run directly to get the tree structure as python objects.
861
+
862
+ ```python
863
+ model = PerpetualBooster()
864
+ model.fit(X, y)
865
+
866
+ model.get_node_lists()[0]
867
+
868
+ # [Node(num=0, weight_value...,
869
+ # Node(num=1, weight_value...,
870
+ # Node(num=2, weight_value...,
871
+ # Node(num=3, weight_value...,
872
+ # Node(num=4, weight_value...,
873
+ # Node(num=5, weight_value...,
874
+ # Node(num=6, weight_value...,]
875
+ ```
876
+ """
877
+ model = json.loads(self.json_dump())["trees"]
878
+ feature_map: Union[Dict[int, str], Dict[int, int]]
879
+ leaf_split_feature: Union[str, int]
880
+ if map_features_names and hasattr(self, "feature_names_in_"):
881
+ feature_map = {i: ft for i, ft in enumerate(self.feature_names_in_)}
882
+ leaf_split_feature = ""
883
+ else:
884
+ feature_map = {i: i for i in range(self.n_features_)}
885
+ leaf_split_feature = -1
886
+
887
+ trees = []
888
+ for t in model:
889
+ nodes = []
890
+ for node in t["nodes"].values():
891
+ if not node["is_leaf"]:
892
+ node["split_feature"] = feature_map[node["split_feature"]]
893
+ else:
894
+ node["split_feature"] = leaf_split_feature
895
+ nodes.append(Node(**node))
896
+ trees.append(nodes)
897
+ return trees
898
+
899
+ def trees_to_dataframe(self):
900
+ """Return the tree structure as a Polars or Pandas DataFrame object.
901
+
902
+ Returns:
903
+ DataFrame: Trees in a Polars or Pandas DataFrame.
904
+
905
+ Example:
906
+ This can be used directly to print out the tree structure as a dataframe. The Leaf values will have the "Gain" column replaced with the weight value.
907
+
908
+ ```python
909
+ model.trees_to_dataframe().head()
910
+ ```
911
+
912
+ | | Tree | Node | ID | Feature | Split | Yes | No | Missing | Gain | Cover |
913
+ |---:|-------:|-------:|:-----|:----------|--------:|:------|:-----|:----------|--------:|---------:|
914
+ | 0 | 0 | 0 | 0-0 | pclass | 3 | 0-1 | 0-2 | 0-2 | 91.5083 | 209.388 |
915
+ | 1 | 0 | 1 | 0-1 | fare | 13.7917 | 0-3 | 0-4 | 0-4 | 28.1855 | 94.0015 |
916
+ """
917
+
918
+ def node_to_row(
919
+ n: Node,
920
+ tree_n: int,
921
+ ) -> Dict[str, Any]:
922
+ def _id(i: int) -> str:
923
+ return f"{tree_n}-{i}"
924
+
925
+ return dict(
926
+ Tree=tree_n,
927
+ Node=n.num,
928
+ ID=_id(n.num),
929
+ Feature="Leaf" if n.is_leaf else str(n.split_feature),
930
+ Split=None if n.is_leaf else n.split_value,
931
+ Yes=None if n.is_leaf else _id(n.left_child),
932
+ No=None if n.is_leaf else _id(n.right_child),
933
+ Missing=None if n.is_leaf else _id(n.missing_node),
934
+ Gain=n.weight_value if n.is_leaf else n.split_gain,
935
+ Cover=n.hessian_sum,
936
+ Left_Cats=n.left_cats,
937
+ Right_Cats=n.right_cats,
938
+ )
939
+
940
+ # Flatten list of lists using list comprehension
941
+ vals = [
942
+ node_to_row(n, i)
943
+ for i, tree in enumerate(self.get_node_lists())
944
+ for n in tree
945
+ ]
946
+
947
+ try:
948
+ import polars as pl
949
+
950
+ return pl.from_records(vals).sort(
951
+ ["Tree", "Node"], descending=[False, False]
952
+ )
953
+ except ImportError:
954
+ import pandas as pd
955
+
956
+ return pd.DataFrame.from_records(vals).sort_values(
957
+ ["Tree", "Node"], ascending=[True, True]
958
+ )