The lares
package has multiple families of functions to
help the analyst or data scientist achieve quality robust analysis
without the need of much coding. One of the most complex but valuable
functions we have is h2o_automl
, which semi-automatically
runs the whole pipeline of a Machine Learning model given a dataset and
some customizable parameters. AutoML enables you to
train high-quality models specific to your needs and accelerate the
research and development process.
HELP: Before getting to the code, I recommend
checking h2o_automl
’s full documentation here
or within your R session by running ?lares::h2o_automl
. In
it you’ll find a brief description of all the parameters you can set
into the function to get exactly what you need and control how it
behaves.
In short, these are some of the things that happen on its backend:
Input a dataframe df
and choose which one is the
independent variable (y
) you’d like to predict. You may
set/change the seed
argument to guarantee reproducibility
of your results.
The function decides if it’s a classification (categorical) or
regression (continuous) model looking at the independent variable’s
(y
) class and number of unique values, which can be control
with the thresh
parameter.
The dataframe will be split in two: test and train datasets. The
proportion of this split can be control with the split
argument. This can be replicated with the msplit()
function.
You could also center
and scale
your
numerical values before you continue, use the no_outliers
to exclude some outliers, and/or impute
missing values with
MICE
. If it’s a classification model, the function can
balance (under-sample) your training data. You can control this behavior
with the balance
argument. Until here, you can replicate
the whole process with the model_preprocess()
function.
Runs h2o::h2o.automl(...)
to train multiple models
and generate a leaderboard with the top (max_models
or
max_time
) models trained, sorted by their performance. You
can also customize some additional arguments such as nfolds
for k-fold cross-validations, exclude_algos
and
include_algos
to exclude or include some algorithms, and
any other additional argument you wish to pass to the mother
function.
The best model given the default performance metric (which can be
changed with stopping_metric
parameter) evaluated with
cross-validation (customize it with nfolds
), will be
selected to continue. You can also use the function
h2o_selectmodel()
to select another model and
recalculate/plot everything again using this alternate model.
Performance metrics and plots will be calculated and rendered
given the test predictions and test actual values (which were NOT passed
to the models as inputs to be trained with). That way, your model’s
performance metrics shouldn’t be biased. You can replicate these
calculations with the model_metrics()
function.
A list with all the inputs, leaderboard results, best selected
model, performance metrics, and plots. You can either (play) see the
results on console or export them using the
export_results()
function.
Now, let’s (install and) load the library, the data, and dig in:
# install.packages("lares")
library(lares)
# The data we'll use is the Titanic dataset
data(dft)
<- subset(dft, select = -c(Ticket, PassengerId, Cabin)) df
NOTE: I’ll randomly set some parameters on each example to give visibility on some of the arguments you can set to your models. Be sure to also check all the print, warnings, and messages shown throughout the process as they may have relevant information regarding your inputs and the backend operations.
Let’s have a look at three specific examples: classification models (binary and multiple categories) and a regression model. Also, let’s see how we can export our models and put them to work on any environment.
Let’s begin with a binary (TRUE/FALSE) model to predict if each
passenger Survived
:
<- h2o_automl(df, y = Survived, max_models = 1, impute = FALSE, target = "TRUE")
r #> 2022-09-08 11:55:16 | Started process...
#> Warning in h2o.clusterInfo():
#> Your H2O cluster version is too old (3 months and 12 days)!
#> Please download and install the latest version from http://h2o.ai/download/
#> - INDEPENDENT VARIABLE: Survived
#> - MODEL TYPE: Classification
#> # A tibble: 2 × 5
#> tag n p order pcum
#> <lgl> <int> <dbl> <int> <dbl>
#> 1 FALSE 549 61.6 1 61.6
#> 2 TRUE 342 38.4 2 100
#> - MISSINGS: The following variables contain missing observations: Age (19.87%). Consider using the impute parameter.
#> - CATEGORICALS: There are 3 non-numerical features. Consider using ohse() or equivalent prior to encode categorical variables.
#> >>> Splitting data: train = 0.7 & test = 0.3
#> train_size test_size
#> 623 268
#> - REPEATED: There were 65 repeated rows which are being suppressed from the train dataset
#> - ALGORITHMS: excluded 'StackedEnsemble', 'DeepLearning'
#> - CACHE: Previous models are not being erased. You may use 'start_clean' [clear] or 'project_name' [join]
#> - UI: You may check results using H2O Flow's interactive platform: http://localhost:54321/flow/index.html
#> >>> Iterating until 1 models or 600 seconds...
#>
|
| | 0%
|
|======================================================================| 100%
#> - EUREKA: Succesfully generated 1 models
#> model_id auc logloss aucpr
#> 1 XGBoost_1_AutoML_1_20220908_115517 0.8324358 0.465688 0.8040614
#> mean_per_class_error rmse mse
#> 1 0.2212218 0.3848639 0.1481202
#> SELECTED MODEL: XGBoost_1_AutoML_1_20220908_115517
#> - NOTE: The following variables were the least important: SibSp, Embarked.C, Pclass.2
#> >>> Running predictions for Survived...
#>
|
| | 0%
|
|======================================================================| 100%
#>
|
| | 0%
|
|======================================================================| 100%
#> Target value: TRUE
#> >>> Generating plots...
#> Model (1/1): XGBoost_1_AutoML_1_20220908_115517
#> Independent Variable: Survived
#> Type: Classification (2 classes)
#> Algorithm: XGBOOST
#> Split: 70% training data (of 891 observations)
#> Seed: 0
#>
#> Test metrics:
#> AUC = 0.87276
#> ACC = 0.19403
#> PRC = 0.20856
#> TPR = 0.36449
#> TNR = 0.080745
#>
#> Most important variables:
#> Sex.female (40.5%)
#> Fare (16.5%)
#> Age (13.9%)
#> Pclass.3 (12.3%)
#> Sex.male (7.7%)
#> Process duration: 5.9s
Let’s take a look at the plots generated into a single dashboard:
plot(r)
We also have several calculations for our model’s performance that may come useful such as a confusion matrix, gain and lift by percentile, area under the curve (AUC), accuracy (ACC), recall or true positive rate (TPR), cross-validation metrics, exact thresholds to maximize each metric, and others:
$metrics
r#> $dictionary
#> [1] "AUC: Area Under the Curve"
#> [2] "ACC: Accuracy"
#> [3] "PRC: Precision = Positive Predictive Value"
#> [4] "TPR: Sensitivity = Recall = Hit rate = True Positive Rate"
#> [5] "TNR: Specificity = Selectivity = True Negative Rate"
#> [6] "Logloss (Error): Logarithmic loss [Neutral classification: 0.69315]"
#> [7] "Gain: When best n deciles selected, what % of the real target observations are picked?"
#> [8] "Lift: When best n deciles selected, how much better than random is?"
#>
#> $confusion_matrix
#> Pred
#> Real FALSE TRUE
#> FALSE 13 148
#> TRUE 68 39
#>
#> $gain_lift
#> # A tibble: 10 × 10
#> percentile value random target total gain optimal lift response score
#> <fct> <chr> <dbl> <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 TRUE 10.1 26 27 24.3 25.2 141. 24.3 88.9
#> 2 2 TRUE 20.9 28 29 50.5 52.3 142. 26.2 75.2
#> 3 3 TRUE 30.6 15 26 64.5 76.6 111. 14.0 49.5
#> 4 4 TRUE 40.7 12 27 75.7 100 86.1 11.2 33.3
#> 5 5 TRUE 50 10 25 85.0 100 70.1 9.35 26.2
#> 6 6 TRUE 60.1 4 27 88.8 100 47.8 3.74 14.9
#> 7 7 TRUE 69.8 4 26 92.5 100 32.6 3.74 11.9
#> 8 8 TRUE 79.9 3 27 95.3 100 19.4 2.80 10.5
#> 9 9 TRUE 89.9 4 27 99.1 100 10.2 3.74 7.33
#> 10 10 TRUE 100 1 27 100 100 0 0.935 3.30
#>
#> $metrics
#> AUC ACC PRC TPR TNR
#> 1 0.87276 0.19403 0.20856 0.36449 0.080745
#>
#> $cv_metrics
#> # A tibble: 20 × 8
#> metric mean sd cv_1_…¹ cv_2_…² cv_3_…³ cv_4_…⁴ cv_5_…⁵
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 accuracy 0.798 0.0451 0.8 0.872 0.792 0.766 0.758
#> 2 auc 0.837 0.0225 0.849 0.859 0.835 0.842 0.800
#> 3 err 0.202 0.0451 0.2 0.128 0.208 0.234 0.242
#> 4 err_count 25.2 5.54 25 16 26 29 30
#> 5 f0point5 0.736 0.0867 0.703 0.864 0.781 0.687 0.646
#> 6 f1 0.746 0.0294 0.742 0.778 0.764 0.748 0.7
#> 7 f2 0.765 0.0424 0.786 0.707 0.747 0.821 0.764
#> 8 lift_top_group 2.68 0.322 2.84 2.98 2.19 2.53 2.88
#> 9 logloss 0.466 0.0462 0.439 0.405 0.516 0.464 0.505
#> 10 max_per_class_error 0.277 0.0469 0.210 0.333 0.263 0.307 0.272
#> 11 mcc 0.591 0.0721 0.588 0.711 0.580 0.559 0.518
#> 12 mean_per_class_accuracy 0.794 0.0193 0.804 0.821 0.788 0.785 0.771
#> 13 mean_per_class_error 0.206 0.0193 0.196 0.179 0.212 0.215 0.229
#> 14 mse 0.148 0.0179 0.139 0.124 0.169 0.147 0.162
#> 15 pr_auc 0.813 0.0398 0.817 0.846 0.828 0.830 0.744
#> 16 precision 0.734 0.130 0.679 0.933 0.792 0.652 0.614
#> 17 r2 0.365 0.0630 0.391 0.443 0.320 0.387 0.284
#> 18 recall 0.783 0.0819 0.818 0.667 0.737 0.878 0.814
#> 19 rmse 0.384 0.0234 0.373 0.352 0.411 0.383 0.403
#> 20 specificity 0.805 0.111 0.790 0.976 0.838 0.693 0.728
#> # … with abbreviated variable names ¹cv_1_valid, ²cv_2_valid, ³cv_3_valid,
#> # ⁴cv_4_valid, ⁵cv_5_valid
#>
#> $max_metrics
#> metric threshold value idx
#> 1 max f1 0.39763027 0.7245763 175
#> 2 max f2 0.25187784 0.7834646 247
#> 3 max f0point5 0.64930636 0.7774968 100
#> 4 max accuracy 0.58539319 0.8025682 115
#> 5 max precision 0.96406724 1.0000000 0
#> 6 max recall 0.05734112 1.0000000 390
#> 7 max specificity 0.96406724 1.0000000 0
#> 8 max absolute_mcc 0.58539319 0.5721717 115
#> 9 max min_per_class_accuracy 0.33894163 0.7659574 200
#> 10 max mean_per_class_accuracy 0.39763027 0.7787782 175
#> 11 max tns 0.96406724 388.0000000 0
#> 12 max fns 0.96406724 232.0000000 0
#> 13 max fps 0.02691792 388.0000000 399
#> 14 max tps 0.05734112 235.0000000 390
#> 15 max tnr 0.96406724 1.0000000 0
#> 16 max fnr 0.96406724 0.9872340 0
#> 17 max fpr 0.02691792 1.0000000 399
#> 18 max tpr 0.05734112 1.0000000 390
The same goes for the plots generated for these metrics. We have the gains and response plots on test data-set, confusion matrix, and ROC curves.
$plots$metrics
r#> $gains
#>
#> $response
#>
#> $conf_matrix
#>
#> $ROC
For all models, regardless of their type (classification or regression), you can check the importance of each variable as well:
head(r$importance)
#> variable relative_importance scaled_importance importance
#> 1 Sex.female 199.02261 1.00000000 0.4054076
#> 2 Fare 80.80907 0.40602961 0.1646075
#> 3 Age 68.23053 0.34282803 0.1389851
#> 4 Pclass.3 60.39945 0.30348033 0.1230332
#> 5 Sex.male 37.77034 0.18977912 0.0769379
#> 6 Parch 15.58557 0.07831056 0.0317477
$plots$importance r
Now, let’s run a multi-categorical (+2 labels) model to predict
Pclass
of each passenger:
<- h2o_automl(df, Pclass, ignore = c("Fare", "Cabin"), max_time = 30, plots = FALSE)
r #> 2022-09-08 11:55:25 | Started process...
#> Warning in h2o.clusterInfo():
#> Your H2O cluster version is too old (3 months and 12 days)!
#> Please download and install the latest version from http://h2o.ai/download/
#> - INDEPENDENT VARIABLE: Pclass
#> - MODEL TYPE: Classification
#> # A tibble: 3 × 5
#> tag n p order pcum
#> <fct> <int> <dbl> <int> <dbl>
#> 1 n_3 491 55.1 1 55.1
#> 2 n_1 216 24.2 2 79.4
#> 3 n_2 184 20.6 3 100
#> - MISSINGS: The following variables contain missing observations: Age (19.87%). Consider using the impute parameter.
#> - CATEGORICALS: There are 3 non-numerical features. Consider using ohse() or equivalent prior to encode categorical variables.
#> >>> Splitting data: train = 0.7 & test = 0.3
#> train_size test_size
#> 623 268
#> - REPEATED: There were 65 repeated rows which are being suppressed from the train dataset
#> - ALGORITHMS: excluded 'StackedEnsemble', 'DeepLearning'
#> - CACHE: Previous models are not being erased. You may use 'start_clean' [clear] or 'project_name' [join]
#> - UI: You may check results using H2O Flow's interactive platform: http://localhost:54321/flow/index.html
#> >>> Iterating until 3 models or 30 seconds...
#> - EUREKA: Succesfully generated 3 models
#> model_id mean_per_class_error logloss rmse
#> 1 GLM_1_AutoML_2_20220908_115526 0.4742325 0.8170807 0.5409388
#> 2 XGBoost_1_AutoML_2_20220908_115526 0.4946035 0.8255072 0.5392879
#> 3 GBM_1_AutoML_2_20220908_115526 0.5046914 0.8579317 0.5592290
#> mse
#> 1 0.2926147
#> 2 0.2908315
#> 3 0.3127371
#> SELECTED MODEL: GLM_1_AutoML_2_20220908_115526
#> - NOTE: The following variables were the least important: Sex.male, Sex.female, Parch
#> >>> Running predictions for Pclass...
#>
|
| | 0%
|
|======================================================================| 100%
#>
|
| | 0%
|
|======================================================================| 100%
#> Model (1/3): GLM_1_AutoML_2_20220908_115526
#> Independent Variable: Pclass
#> Type: Classification (3 classes)
#> Algorithm: GLM
#> Split: 70% training data (of 891 observations)
#> Seed: 0
#>
#> Test metrics:
#> AUC = 0.76337
#> ACC = 0.64179
#>
#> Most important variables:
#> Embarked.Q (25.3%)
#> Embarked.C (13.5%)
#> Embarked.S (13.3%)
#> Age (11.9%)
#> Survived.FALSE (10.6%)
#> Process duration: 7.29s
Let’s take a look at the plots generated into a single dashboard:
plot(r)
Finally, a regression model with continuous values to predict
Fare
payed by passenger:
<- h2o_automl(df, y = "Fare", ignore = "Pclass", exclude_algos = NULL, quiet = TRUE)
r #> Warning in h2o.clusterInfo():
#> Your H2O cluster version is too old (3 months and 12 days)!
#> Please download and install the latest version from http://h2o.ai/download/
print(r)
#> Model (1/4): StackedEnsemble_BestOfFamily_1_AutoML_3_20220908_115534
#> Independent Variable: Fare
#> Type: Regression
#> Algorithm: STACKEDENSEMBLE
#> Split: 70% training data (of 871 observations)
#> Seed: 0
#>
#> Test metrics:
#> rmse = 20.055
#> mae = 14.026
#> mape = 0.069591
#> mse = 402.2
#> rsq = 0.3691
#> rsqa = 0.3667
Let’s take a look at the plots generated into a single dashboard:
plot(r)
Once you have you model trained and picked, you can export the model
and it’s results, so you can put it to work in a production environment
(doesn’t have to be R). There is a function that does all that for you:
export_results()
. Simply pass your h2o_automl
list object into this function and that’s it! You can select which
formats will be exported using the which
argument.
Currently we support: txt
, csv
,
rds
, binary
, mojo
[best format
for production], and plots
. There are also 2 quick options
(dev
and production
) to export some or all the
files. Lastly, you can set a custom subdir
to gather
everything into a new sub-directory; I’d recommend using the model’s
name or any other convention that helps you know which one’s which.
If you’d like to re-use your exported models to predict new datasets, you have several options:
h2o_predict_MOJO()
[recommended]: This
function lets the user predict using h2o
’s
.zip
file containing the MOJO files. These files are also
the ones used when putting the model into production on any other
environment. Also, MOJO let’s you change h2o
’s versions
without issuesh2o_predict_binary()
: This function lets the user
predict using the h2o binary file. The h2o
version/build
must match for it to work.h2o_predict_model()
: This function lets the user run
predictions from a H2O Model Object
same as you’d use the
predict
base function. Will probably only work in your
current session as you must have the actual trained object to use
it.