mljar-supervised 1.2.1__py3-none-any.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.
Files changed (94) hide show
  1. mljar_supervised-1.2.1.dist-info/METADATA +657 -0
  2. mljar_supervised-1.2.1.dist-info/RECORD +94 -0
  3. mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
  4. mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
  5. mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
  6. supervised/__init__.py +14 -0
  7. supervised/algorithms/__init__.py +0 -0
  8. supervised/algorithms/algorithm.py +151 -0
  9. supervised/algorithms/baseline.py +90 -0
  10. supervised/algorithms/catboost.py +436 -0
  11. supervised/algorithms/decision_tree.py +305 -0
  12. supervised/algorithms/extra_trees.py +176 -0
  13. supervised/algorithms/factory.py +28 -0
  14. supervised/algorithms/knn.py +137 -0
  15. supervised/algorithms/lightgbm.py +406 -0
  16. supervised/algorithms/linear.py +211 -0
  17. supervised/algorithms/nn.py +180 -0
  18. supervised/algorithms/random_forest.py +181 -0
  19. supervised/algorithms/registry.py +76 -0
  20. supervised/algorithms/sklearn.py +197 -0
  21. supervised/algorithms/xgboost.py +413 -0
  22. supervised/automl.py +568 -0
  23. supervised/base_automl.py +2542 -0
  24. supervised/callbacks/__init__.py +0 -0
  25. supervised/callbacks/callback.py +25 -0
  26. supervised/callbacks/callback_list.py +33 -0
  27. supervised/callbacks/early_stopping.py +213 -0
  28. supervised/callbacks/learner_time_constraint.py +47 -0
  29. supervised/callbacks/max_iters_constraint.py +16 -0
  30. supervised/callbacks/metric_logger.py +48 -0
  31. supervised/callbacks/terminate_on_nan.py +28 -0
  32. supervised/callbacks/total_time_constraint.py +79 -0
  33. supervised/ensemble.py +583 -0
  34. supervised/exceptions.py +21 -0
  35. supervised/fairness/__init__.py +0 -0
  36. supervised/fairness/metrics.py +654 -0
  37. supervised/fairness/optimization.py +414 -0
  38. supervised/fairness/plots.py +131 -0
  39. supervised/fairness/report.py +116 -0
  40. supervised/fairness/utils.py +40 -0
  41. supervised/model_framework.py +734 -0
  42. supervised/preprocessing/__init__.py +0 -0
  43. supervised/preprocessing/datetime_transformer.py +106 -0
  44. supervised/preprocessing/encoding_selector.py +30 -0
  45. supervised/preprocessing/exclude_missing_target.py +46 -0
  46. supervised/preprocessing/goldenfeatures_transformer.py +310 -0
  47. supervised/preprocessing/kmeans_transformer.py +115 -0
  48. supervised/preprocessing/label_binarizer.py +81 -0
  49. supervised/preprocessing/label_encoder.py +54 -0
  50. supervised/preprocessing/preprocessing.py +652 -0
  51. supervised/preprocessing/preprocessing_categorical.py +117 -0
  52. supervised/preprocessing/preprocessing_missing.py +97 -0
  53. supervised/preprocessing/preprocessing_utils.py +136 -0
  54. supervised/preprocessing/scale.py +92 -0
  55. supervised/preprocessing/text_transformer.py +73 -0
  56. supervised/tuner/__init__.py +0 -0
  57. supervised/tuner/data_info.py +64 -0
  58. supervised/tuner/hill_climbing.py +80 -0
  59. supervised/tuner/mljar_tuner.py +1501 -0
  60. supervised/tuner/optuna/__init__.py +0 -0
  61. supervised/tuner/optuna/catboost.py +148 -0
  62. supervised/tuner/optuna/extra_trees.py +80 -0
  63. supervised/tuner/optuna/knn.py +64 -0
  64. supervised/tuner/optuna/lightgbm.py +165 -0
  65. supervised/tuner/optuna/nn.py +66 -0
  66. supervised/tuner/optuna/random_forest.py +77 -0
  67. supervised/tuner/optuna/tuner.py +335 -0
  68. supervised/tuner/optuna/xgboost.py +130 -0
  69. supervised/tuner/preprocessing_tuner.py +137 -0
  70. supervised/tuner/random_parameters.py +22 -0
  71. supervised/tuner/time_controller.py +273 -0
  72. supervised/utils/__init__.py +11 -0
  73. supervised/utils/additional_metrics.py +955 -0
  74. supervised/utils/additional_plots.py +228 -0
  75. supervised/utils/automl_plots.py +368 -0
  76. supervised/utils/common.py +39 -0
  77. supervised/utils/config.py +25 -0
  78. supervised/utils/constants.py +4 -0
  79. supervised/utils/data_validation.py +48 -0
  80. supervised/utils/importance.py +93 -0
  81. supervised/utils/jsonencoder.py +33 -0
  82. supervised/utils/leaderboard_plots.py +137 -0
  83. supervised/utils/learning_curves.py +145 -0
  84. supervised/utils/metric.py +450 -0
  85. supervised/utils/report_structured.py +525 -0
  86. supervised/utils/shap.py +373 -0
  87. supervised/utils/subsample.py +17 -0
  88. supervised/utils/utils.py +29 -0
  89. supervised/validation/__init__.py +0 -0
  90. supervised/validation/validation_step.py +37 -0
  91. supervised/validation/validator_base.py +17 -0
  92. supervised/validation/validator_custom.py +112 -0
  93. supervised/validation/validator_kfold.py +153 -0
  94. supervised/validation/validator_split.py +143 -0
supervised/automl.py ADDED
@@ -0,0 +1,568 @@
1
+ import logging
2
+
3
+ import matplotlib
4
+
5
+ import warnings
6
+
7
+ warnings.filterwarnings("ignore", message=".*The 'nopython' keyword.*")
8
+
9
+ from collections.abc import Iterable
10
+
11
+ # libraries for type hints
12
+ from typing import List, Optional, Union
13
+
14
+ import numpy
15
+ import pandas
16
+ from typing_extensions import (
17
+ Literal,
18
+ ) # typing_extensions is used for using Literal from python 3.7
19
+
20
+ from supervised.base_automl import BaseAutoML
21
+ from supervised.utils.config import LOG_LEVEL
22
+
23
+ logging.basicConfig(
24
+ format="%(asctime)s %(name)s %(levelname)s %(message)s", level=logging.ERROR
25
+ )
26
+ logger = logging.getLogger(__name__)
27
+ logger.setLevel(LOG_LEVEL)
28
+
29
+
30
+ class AutoML(BaseAutoML):
31
+
32
+ """
33
+ Automated Machine Learning for supervised tasks (binary classification, multiclass classification, regression).
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ results_path: Optional[str] = None,
39
+ total_time_limit: int = 60 * 60,
40
+ mode: Literal["Explain", "Perform", "Compete", "Optuna"] = "Explain",
41
+ ml_task: Literal[
42
+ "auto", "binary_classification", "multiclass_classification", "regression"
43
+ ] = "auto",
44
+ model_time_limit: Optional[int] = None,
45
+ algorithms: Union[
46
+ Literal["auto"],
47
+ List[
48
+ Literal[
49
+ "Baseline",
50
+ "Linear",
51
+ "Decision Tree",
52
+ "Random Forest",
53
+ "Extra Trees",
54
+ "LightGBM",
55
+ "Xgboost",
56
+ "CatBoost",
57
+ "Neural Network",
58
+ "Nearest Neighbors",
59
+ ]
60
+ ],
61
+ ] = "auto",
62
+ train_ensemble: bool = True,
63
+ stack_models: Union[Literal["auto"], bool] = "auto",
64
+ eval_metric: str = "auto",
65
+ validation_strategy: Union[Literal["auto"], dict] = "auto",
66
+ explain_level: Union[Literal["auto"], Literal[0, 1, 2]] = "auto",
67
+ golden_features: Union[Literal["auto"], bool, int] = "auto",
68
+ features_selection: Union[Literal["auto"], bool] = "auto",
69
+ start_random_models: Union[Literal["auto"], int] = "auto",
70
+ hill_climbing_steps: Union[Literal["auto"], int] = "auto",
71
+ top_models_to_improve: Union[Literal["auto"], int] = "auto",
72
+ boost_on_errors: Union[Literal["auto"], bool] = "auto",
73
+ kmeans_features: Union[Literal["auto"], bool] = "auto",
74
+ mix_encoding: Union[Literal["auto"], bool] = "auto",
75
+ max_single_prediction_time: Optional[Union[int, float]] = None,
76
+ optuna_time_budget: Optional[int] = None,
77
+ optuna_init_params: dict = {},
78
+ optuna_verbose: bool = True,
79
+ fairness_metric: str = "auto",
80
+ fairness_threshold: Union[Literal["auto"], float] = "auto",
81
+ privileged_groups: Union[Literal["auto"], list] = "auto",
82
+ underprivileged_groups: Union[Literal["auto"], list] = "auto",
83
+ n_jobs: int = -1,
84
+ verbose: int = 1,
85
+ random_state: int = 1234,
86
+ ):
87
+ """
88
+ Initialize `AutoML` object.
89
+
90
+ Arguments:
91
+ results_path (str): The path with results. If None, then the name of directory will be generated with the template: AutoML_{number},
92
+ where the number can be from 1 to 1,000 - depends which direcory name will be available.
93
+ If the `results_path` will point to directory with AutoML results (`params.json` must be present),
94
+ then all models will be loaded.
95
+
96
+ total_time_limit (int): The total time limit in seconds for AutoML training.
97
+ It is not used when `model_time_limit` is not `None`.
98
+
99
+ mode (str): Can be {`Explain`, `Perform`, `Compete`, `Optuna`}. This parameter defines the goal of AutoML and how intensive the AutoML search will be.
100
+
101
+ - `Explain` : To to be used when the user wants to explain and understand the data.
102
+ - Uses 75%/25% train/test split.
103
+ - Uses the following models: `Baseline`, `Linear`, `Decision Tree`, `Random Forest`, `XGBoost`, `Neural Network`, and `Ensemble`.
104
+ - Has full explanations in reports: learning curves, importance plots, and SHAP plots.
105
+ - `Perform` : To be used when the user wants to train a model that will be used in real-life use cases.
106
+ - Uses 5-fold CV (Cross-Validation).
107
+ - Uses the following models: `Linear`, `Random Forest`, `LightGBM`, `XGBoost`, `CatBoost`, `Neural Network`, and `Ensemble`.
108
+ - Has learning curves and importance plots in reports.
109
+ - `Compete` : To be used for machine learning competitions (maximum performance).
110
+ - Uses 80/20 train/test split, or 5-fold CV, or 10-fold CV (Cross-Validation) - it depends on `total_time_limit`. If not set directly, AutoML will select validation automatically.
111
+ - Uses the following models: `Decision Tree`, `Random Forest`, `Extra Trees`, `LightGBM`, `XGBoost`, `CatBoost`, `Neural Network`,
112
+ `Nearest Neighbors`, `Ensemble`, and `Stacking`.
113
+ - It has only learning curves in the reports.
114
+ - `Optuna` : To be used for creating highly-tuned machine learning models.
115
+ - Uses 10-fold CV (Cross-Validation).
116
+ - It tunes with Optuna the following algorithms: `Random Forest`, `Extra Trees`, `LightGBM`, `XGBoost`, `CatBoost`, `Neural Network`.
117
+ - It applies `Ensemble` and `Stacking` for trained models.
118
+ - It has only learning curves in the reports.
119
+
120
+ ml_task (str): Can be {"auto", "binary_classification", "multiclass_classification", "regression"}.
121
+
122
+ - If left `auto` AutoML will try to guess the task based on target values.
123
+ - If there will be only 2 values in the target, then task will be set to `"binary_classification"`.
124
+ - If number of values in the target will be between 2 and 20 (included), then task will be set to `"multiclass_classification"`.
125
+ - In all other casses, the task is set to `"regression"`.
126
+
127
+ model_time_limit (int): The time limit for training a single model, in seconds.
128
+ If `model_time_limit` is set, the `total_time_limit` is not respected.
129
+ The single model can contain several learners. The time limit for subsequent learners is computed based on `model_time_limit`.
130
+
131
+ For example, in the case of 10-fold cross-validation, one model will have 10 learners.
132
+ The `model_time_limit` is the time for all 10 learners.
133
+
134
+ algorithms (list of str): The list of algorithms that will be used in the training.
135
+ The algorithms can be:
136
+
137
+ - `Baseline`,
138
+ - `Linear`,
139
+ - `Decision Tree`,
140
+ - `Random Forest`,
141
+ - `Extra Trees`,
142
+ - `LightGBM`,
143
+ - `Xgboost`,
144
+ - `CatBoost`,
145
+ - `Neural Network`,
146
+ - `Nearest Neighbors`,
147
+
148
+
149
+ train_ensemble (boolean): Whether an ensemble gets created at the end of the training.
150
+
151
+ stack_models (boolean): Whether a models stack gets created at the end of the training. Stack level is 1.
152
+
153
+ eval_metric (str): The metric to be used in early stopping and to compare models.
154
+
155
+ - for binary classification: `logloss`, `auc`, `f1`, `average_precision`, `accuracy` - default is logloss (if left "auto")
156
+ - for mutliclass classification: `logloss`, `f1`, `accuracy` - default is `logloss` (if left "auto")
157
+ - for regression: `rmse`, `mse`, `mae`, `r2`, `mape`, `spearman`, `pearson` - default is `rmse` (if left "auto")
158
+
159
+ validation_strategy (dict): Dictionary with validation type. Right now train/test split and cross-validation are supported.
160
+
161
+ Example:
162
+
163
+ Cross-validation exmaple:
164
+ {
165
+ "validation_type": "kfold",
166
+ "k_folds": 5,
167
+ "shuffle": True,
168
+ "stratify": True,
169
+ "random_seed": 123
170
+ }
171
+
172
+ Train/test example:
173
+ {
174
+ "validation_type": "split",
175
+ "train_ratio": 0.75,
176
+ "shuffle": True,
177
+ "stratify": True
178
+ }
179
+
180
+ explain_level (int): The level of explanations included to each model:
181
+
182
+ - if `explain_level` is `0` no explanations are produced.
183
+ - if `explain_level` is `1` the following explanations are produced: importance plot (with permutation method), for decision trees produce tree plots, for linear models save coefficients.
184
+ - if `explain_level` is `2` the following explanations are produced: the same as `1` plus SHAP explanations.
185
+
186
+ If left `auto` AutoML will produce explanations based on the selected `mode`.
187
+
188
+ golden_features (boolean or int): Whether to use golden features (and how many should be added)
189
+ If left `auto` AutoML will use golden features based on the selected `mode`:
190
+
191
+ - If `mode` is "Explain", `golden_features` = False.
192
+ - If `mode` is "Perform", `golden_features` = True.
193
+ - If `mode` is "Compete", `golden_features` = True.
194
+
195
+ If `boolean` value is set then the number of Golden Features is set automatically.
196
+ It is set to min(100, max(10, 0.1*number_of_input_features)).
197
+
198
+ If `int` value is set, the number of Golden Features is set to this value.
199
+
200
+ features_selection (boolean): Whether to do features_selection
201
+ If left `auto` AutoML will do feature selection based on the selected `mode`:
202
+
203
+ - If `mode` is "Explain", `features_selection` = False.
204
+ - If `mode` is "Perform", `features_selection` = True.
205
+ - If `mode` is "Compete", `features_selection` = True.
206
+
207
+ start_random_models (int): Number of starting random models to try.
208
+ If left `auto` AutoML will select it based on the selected `mode`:
209
+
210
+ - If `mode` is "Explain", `start_random_models` = 1.
211
+ - If `mode` is "Perform", `start_random_models` = 5.
212
+ - If `mode` is "Compete", `start_random_models` = 10.
213
+
214
+ hill_climbing_steps (int): Number of steps to perform during hill climbing.
215
+ If left `auto` AutoML will select it based on the selected `mode`:
216
+
217
+ - If `mode` is "Explain", `hill_climbing_steps` = 0.
218
+ - If `mode` is "Perform", `hill_climbing_steps` = 2.
219
+ - If `mode` is "Compete", `hill_climbing_steps` = 2.
220
+
221
+ top_models_to_improve (int): Number of best models to improve in `hill_climbing` steps.
222
+ If left `auto` AutoML will select it based on the selected `mode`:
223
+
224
+ - If `mode` is "Explain", `top_models_to_improve` = 0.
225
+ - If `mode` is "Perform", `top_models_to_improve` = 2.
226
+ - If `mode` is "Compete", `top_models_to_improve` = 3.
227
+
228
+ boost_on_errors (boolean): Whether a model with boost on errors from previous best model should be trained. By default available in the `Compete` mode.
229
+
230
+ kmeans_features (boolean): Whether a model with k-means generated features should be trained. By default available in the `Compete` mode.
231
+
232
+ mix_encoding (boolean): Whether a model with mixed encoding should be trained. Mixed encoding is the encoding that uses label encoding
233
+ for categoricals with more than 25 categories, and one-hot binary encoding for other categoricals. It is only applied if there are
234
+ categorical features with cardinality smaller than 25. By default it is available in the `Compete` mode.
235
+
236
+ max_single_prediction_time (int or float): The limit for prediction time for single sample. Use it if you want to have a model with fast predictions.
237
+ Ideal for creating ML pipelines used as REST API. Time is in seconds. By default (`max_single_prediction_time=None`) models are not optimized for fast predictions,
238
+ except the mode `Perform`. For the mode `Perform` the default is `0.5` seconds.
239
+
240
+ optuna_time_budget (int): The time in seconds which should be used by Optuna to tune each algorithm. It is time for tuning single algorithm.
241
+ If you select two algorithms: Xgboost and CatBoost, and set optuna_time_budget=1000, then Xgboost will be tuned for 1000 seconds and CatBoost will be tuned for 1000 seconds.
242
+ What is more, the tuning is made for each data type, for example for raw data and for data with inserted Golden Features.
243
+ This parameter is only used when `mode="Optuna"`. If you set `mode="Optuna"` and forget to set this parameter, it will be set to 3600 seconds.
244
+
245
+ optuna_init_params (dict): If you have already tuned parameters from Optuna you can reuse them by setting this parameter.
246
+ This parameter is only used when `mode="Optuna"`. The dict should have structure and params as specified in the MLJAR AutoML .
247
+
248
+ optuna_verbose (boolean): If true the Optuna tuning details are displayed. Set to `True` by default.
249
+
250
+ fairness_metric (string): Name of fairness metric that will be used for assessing fairness criteria.
251
+ Available metrics for binary and multiclass classification:
252
+
253
+ - `demographic_parity_difference`,
254
+ - `demographic_parity_ratio` - default metric,
255
+ - `equalized_odds_difference`,
256
+ - `equalized_odds_ratio`.
257
+
258
+ Metrics for regression:
259
+
260
+ - `group_loss_difference`,
261
+ - `group_loss_ratio` - default metric.
262
+
263
+
264
+ fairness_threshold (float): The treshold value for fairness metric.
265
+ The direction optimization (below or above threshold) of fairness metric is determined automatically.
266
+
267
+ Default values:
268
+
269
+ - for `demographic_parity_difference` the metric value should be below 0.1,
270
+ - for `demographic_parity_ratio` the metric value should be above 0.8,
271
+ - for `equalized_odds_difference` the metric value should be below 0.1,
272
+ - for `equalized_odds_ratio` the metric value shoule be above 0.8.
273
+ - for `group_loss_ratio` the metric value shoule be above 0.8.
274
+
275
+ For `group_loss_difference` the default threshold value can't be set because it depends on the dataset.
276
+ If `group_loss_difference` metric is used and `fairness_threshold` is not specified manually, then an exception will be raised.
277
+
278
+ privileged_groups (list): The list of privileged groups.
279
+
280
+ By default, list of privileged groups are automatically detected based on fairness metrics.
281
+ For example, in binary classification task, a privileged group is the one with the highest selection rate.
282
+
283
+ Example value: `[{"sex": "Male"}]`
284
+
285
+ underprivileged_groups (list): The list of underprivileged groups.
286
+
287
+ By default, list of underprivileged groups are automatically detected based on fairness metrics.
288
+ For example, in binary classification task, an underprivileged group is the one with the lowest selection rate.
289
+
290
+ Example value: `[{"sex": "Female"}]`
291
+
292
+ n_jobs (int): Number of CPU cores to be used. By default is set to `-1` which means using all processors.
293
+
294
+ verbose (int): Controls the verbosity when fitting and predicting.
295
+
296
+ Note:
297
+ Still not implemented, please left `1`
298
+
299
+ random_state (int): Controls the randomness of the `AutoML`
300
+
301
+
302
+ Examples:
303
+
304
+ Binary Classification Example:
305
+
306
+ >>> import pandas as pd
307
+ >>> from sklearn.model_selection import train_test_split
308
+ >>> from sklearn.metrics import roc_auc_score
309
+ >>> from supervised import AutoML
310
+ >>> df = pd.read_csv(
311
+ ... "https://raw.githubusercontent.com/pplonski/datasets-for-start/master/adult/data.csv",
312
+ ... skipinitialspace=True
313
+ ... )
314
+ >>> X_train, X_test, y_train, y_test = train_test_split(
315
+ ... df[df.columns[:-1]], df["income"], test_size=0.25
316
+ ... )
317
+ >>> automl = AutoML()
318
+ >>> automl.fit(X_train, y_train)
319
+ >>> y_pred_prob = automl.predict_proba(X_test)
320
+ >>> print(f"AUROC: {roc_auc_score(y_test, y_pred_prob):.2f}%")
321
+
322
+
323
+ Multi-Class Classification Example:
324
+
325
+ >>> import pandas as pd
326
+ >>> from sklearn.datasets import load_digits
327
+ >>> from sklearn.metrics import accuracy_score
328
+ >>> from sklearn.model_selection import train_test_split
329
+ >>> from supervised import AutoML
330
+ >>> digits = load_digits()
331
+ >>> X_train, X_test, y_train, y_test = train_test_split(
332
+ ... digits.data, digits.target, stratify=digits.target, test_size=0.25,
333
+ ... random_state=123
334
+ ... )
335
+ >>> automl = AutoML(mode="Perform")
336
+ >>> automl.fit(X_train, y_train)
337
+ >>> y_pred = automl.predict(X_test)
338
+ >>> print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}%")
339
+
340
+ Regression Example:
341
+
342
+ >>> import pandas as pd
343
+ >>> from sklearn.datasets import fetch_california_housing
344
+ >>> from sklearn.model_selection import train_test_split
345
+ >>> from sklearn.metrics import mean_squared_error
346
+ >>> from supervised import AutoML
347
+ >>> housing = fetch_california_housing()
348
+ >>> X_train, X_test, y_train, y_test = train_test_split(
349
+ ... pd.DataFrame(housing.data, columns=housing.feature_names),
350
+ ... housing.target,
351
+ ... test_size=0.25,
352
+ ... random_state=123,
353
+ ... )
354
+ >>> automl = AutoML(mode="Compete")
355
+ >>> automl.fit(X_train, y_train)
356
+ >>> print("Test R^2:", automl.score(X_test, y_test))
357
+
358
+ Scikit-learn Pipeline Integration Example:
359
+
360
+ >>> from imblearn.over_sampling import RandomOverSampler
361
+ >>> from sklearn.pipeline import make_pipeline
362
+ >>> from sklearn.datasets import make_classification
363
+ >>> from sklearn.model_selection import train_test_split
364
+ >>> from supervised import AutoML
365
+ >>> X, y = make_classification()
366
+ >>> X_train, X_test, y_train, y_test = train_test_split(X,y)
367
+ >>> pipeline = make_pipeline(RandomOverSampler(), AutoML())
368
+ >>> print(pipeline.fit(X_train, y_train).score(X_test, y_test))
369
+
370
+ """
371
+ super(AutoML, self).__init__()
372
+ # Set user arguments
373
+ self.mode = mode
374
+ self.ml_task = ml_task
375
+ self.results_path = results_path
376
+ self.total_time_limit = total_time_limit
377
+ self.model_time_limit = model_time_limit
378
+ self.algorithms = algorithms
379
+ self.train_ensemble = train_ensemble
380
+ self.stack_models = stack_models
381
+ self.eval_metric = eval_metric
382
+ self.validation_strategy = validation_strategy
383
+ self.verbose = verbose
384
+ self.explain_level = explain_level
385
+ self.golden_features = golden_features
386
+ self.features_selection = features_selection
387
+ self.start_random_models = start_random_models
388
+ self.hill_climbing_steps = hill_climbing_steps
389
+ self.top_models_to_improve = top_models_to_improve
390
+ self.boost_on_errors = boost_on_errors
391
+ self.kmeans_features = kmeans_features
392
+ self.mix_encoding = mix_encoding
393
+ self.max_single_prediction_time = max_single_prediction_time
394
+ self.optuna_time_budget = optuna_time_budget
395
+ self.optuna_init_params = optuna_init_params
396
+ self.optuna_verbose = optuna_verbose
397
+ self.fairness_metric = fairness_metric
398
+ self.fairness_threshold = fairness_threshold
399
+ self.privileged_groups = privileged_groups
400
+ self.underprivileged_groups = underprivileged_groups
401
+ self.n_jobs = n_jobs
402
+ self.random_state = random_state
403
+
404
+ def fit(
405
+ self,
406
+ X: Union[numpy.ndarray, pandas.DataFrame],
407
+ y: Union[numpy.ndarray, pandas.Series],
408
+ sample_weight: Optional[Union[numpy.ndarray, pandas.Series]] = None,
409
+ cv: Optional[Union[Iterable, List]] = None,
410
+ sensitive_features: Optional[
411
+ Union[numpy.ndarray, pandas.Series, pandas.DataFrame]
412
+ ] = None,
413
+ ):
414
+ """Fit the AutoML model.
415
+
416
+ Arguments:
417
+ X (numpy.ndarray or pandas.DataFrame): Training data
418
+
419
+ y (numpy.ndarray or pandas.Series): Training targets
420
+
421
+ sample_weight (numpy.ndarray or pandas.Series): Training sample weights
422
+
423
+ cv (iterable or list): List or iterable with (train, validation) splits representing array of indices.
424
+ It is used only with custom validation (`validation_strategy={'validation_type': 'custom'}`).
425
+
426
+ sensitive_features (pandas.Series or pandas.DataFrame): Sensitive features to learn fair models
427
+
428
+ Returns:
429
+ AutoML object: Returns `self`
430
+ """
431
+ try:
432
+ original_backend = matplotlib.get_backend()
433
+ matplotlib.use("Agg")
434
+ return self._fit(X, y, sample_weight, cv, sensitive_features)
435
+ except Exception as e:
436
+ raise e
437
+ finally:
438
+ matplotlib.use(original_backend)
439
+ try:
440
+ if 'inline' in original_backend:
441
+ import matplotlib_inline
442
+ matplotlib_inline.backend_inline._enable_matplotlib_integration()
443
+ except:
444
+ pass
445
+
446
+
447
+ def predict(self, X: Union[List, numpy.ndarray, pandas.DataFrame]) -> numpy.ndarray:
448
+ """
449
+ Computes predictions from AutoML best model.
450
+
451
+ Arguments:
452
+ X (list or numpy.ndarray or pandas.DataFrame):
453
+ Input values to make predictions on.
454
+
455
+ Returns:
456
+ numpy.ndarray:
457
+
458
+ - One-dimensional array of class labels for classification.
459
+ - One-dimensional array of predictions for regression.
460
+
461
+ Raises:
462
+ AutoMLException: Model has not yet been fitted.
463
+ """
464
+ return self._predict(X)
465
+
466
+ def predict_proba(
467
+ self, X: Union[List, numpy.ndarray, pandas.DataFrame]
468
+ ) -> numpy.ndarray:
469
+ """
470
+ Computes class probabilities from AutoML best model.
471
+ This method can only be used for classification tasks.
472
+
473
+ Arguments:
474
+ X (list or numpy.ndarray or pandas.DataFrame):
475
+ Input values to make predictions on.
476
+
477
+ Returns:
478
+ numpy.ndarray of shape (n_samples, n_classes):
479
+ Matrix of containing class probabilities of the input samples
480
+
481
+ Raises:
482
+ AutoMLException: Model has not yet been fitted.
483
+
484
+ """
485
+ return self._predict_proba(X)
486
+
487
+ def predict_all(
488
+ self, X: Union[List, numpy.ndarray, pandas.DataFrame]
489
+ ) -> pandas.DataFrame:
490
+ """
491
+ Computes both class probabilities and class labels for classification tasks.
492
+ Computes predictions for regression tasks.
493
+
494
+ Arguments:
495
+ X (list or numpy.ndarray or pandas.DataFrame):
496
+ Input values to make predictions on.
497
+
498
+ Returns:
499
+ pandas.Dataframe:
500
+ Dataframe (n_samples, n_classes + 1) containing both class probabilities and class
501
+ labels of the input samples for classification tasks.
502
+ Dataframe with predictions for regression tasks.
503
+
504
+ Raises:
505
+ AutoMLException: Model has not yet been fitted.
506
+
507
+ """
508
+ return self._predict_all(X)
509
+
510
+ def score(
511
+ self,
512
+ X: Union[numpy.ndarray, pandas.DataFrame],
513
+ y: Optional[Union[numpy.ndarray, pandas.Series]] = None,
514
+ sample_weight: Optional[Union[numpy.ndarray, pandas.Series]] = None,
515
+ ) -> float:
516
+ """Calculates a goodness of `fit` for an AutoML instance.
517
+
518
+ Arguments:
519
+ X (numpy.ndarray or pandas.DataFrame):
520
+ Test values to make predictions on.
521
+
522
+ y (numpy.ndarray or pandas.Series):
523
+ True labels for X.
524
+
525
+ sample_weight (numpy.ndarray or pandas.Series):
526
+ Sample weights.
527
+ Returns:
528
+ float: Returns a goodness of fit measure (higher is better):
529
+
530
+ - For classification tasks: returns the mean accuracy on the given test data and labels.
531
+ - For regression tasks: returns the R^2 (coefficient of determination) on the given test data and labels.
532
+ """
533
+ return self._score(X, y, sample_weight)
534
+
535
+ def report(self, width=900, height=1200):
536
+ return self._report(width, height)
537
+
538
+ def report_structured(self, format="markdown", model_details=True):
539
+ return self._report_structured(format, model_details)
540
+
541
+ def need_retrain(
542
+ self,
543
+ X: Union[numpy.ndarray, pandas.DataFrame],
544
+ y: Union[numpy.ndarray, pandas.Series],
545
+ sample_weight: Optional[Union[numpy.ndarray, pandas.Series]] = None,
546
+ decrease: float = 0.1,
547
+ ) -> bool:
548
+ """Decides about model retraining based on new data.
549
+
550
+ Arguments:
551
+ X (numpy.ndarray or pandas.DataFrame):
552
+ New data.
553
+
554
+ y (numpy.ndarray or pandas.Series):
555
+ True labels for X.
556
+
557
+ sample_weight (numpy.ndarray or pandas.Series):
558
+ Sample weights.
559
+
560
+ decrease (float): The ratio of change in the performance used as a threshold for retraining decision.
561
+ By default, it is set to `0.1` which means that if the performance of AutoML will decrease by 10%
562
+ on new data then there is a need to retrain. This value should be set depending on your project needs.
563
+ Sometimes, 10% is enough, but for some projects, it can be even lower than 1%.
564
+
565
+ Returns:
566
+ boolean: Decides if there is a need to retrain the AutoML.
567
+ """
568
+ return self._need_retrain(X, y, sample_weight, decrease)