Introduction to AutoML using lares

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.

Pipeline

In short, these are some of the things that happen on its backend:

Mapping h2o_automl

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

Load the library

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)
df <- subset(dft, select = -c(Ticket, PassengerId, Cabin))

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.

Modeling examples

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.

Classification: Binary

Let’s begin with a binary (TRUE/FALSE) model to predict if each passenger Survived:

r <- h2o_automl(df, y = Survived, max_models = 1, impute = FALSE, target = "TRUE")
#> 2021-12-03 15:10:07 | Started process...
#> - 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 64 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_6_20211203_151007 0.841748 0.4600598 0.817467
#>   mean_per_class_error      rmse       mse
#> 1            0.2348472 0.3842575 0.1476538
#> SELECTED MODEL: XGBoost_1_AutoML_6_20211203_151007
#> - NOTE: The following variables were the least important: SibSp, Parch, Pclass.1, Embarked.C
#> >>> Running predictions for Survived...
#> 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
#> 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
#> Target value: TRUE
#> >>> Generating plots...
#> Model (1/1): XGBoost_1_AutoML_6_20211203_151007
#> Independent Variable: Survived
#> Type: Classification (2 classes)
#> Algorithm: XGBOOST
#> Split: 70% training data (of 891 observations)
#> Seed: 0
#> 
#> Test metrics:
#>    AUC = 0.84351
#>    ACC = 0.19776
#>    PRC = 0.19355
#>    TPR = 0.35644
#>    TNR = 0.1018
#> 
#> Most important variables:
#>    Sex.female (37.9%)
#>    Fare (16.9%)
#>    Age (15.2%)
#>    Pclass.3 (13.4%)
#>    Sex.male (8.3%)
#> Process duration: 16.8s

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:

r$metrics
#> $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    17  150
#>   TRUE     65   36
#> 
#> $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.4     28    28  27.7    27.7 165.     27.7   87.6 
#>  2 2          TRUE    20.9     25    28  52.5    55.4 151.     24.8   73.3 
#>  3 3          TRUE    30.2     12    25  64.4    80.2 113.     11.9   50.4 
#>  4 4          TRUE    39.9      9    26  73.3   100    83.5     8.91  34.9 
#>  5 5          TRUE    50        7    27  80.2   100    60.4     6.93  22.8 
#>  6 6          TRUE    60.1      8    27  88.1   100    46.7     7.92  15.9 
#>  7 7          TRUE    69.8      3    26  91.1   100    30.5     2.97  12.7 
#>  8 8          TRUE    81.7      4    32  95.0   100    16.3     3.96   7.94
#>  9 9          TRUE    89.9      1    22  96.0   100     6.80    0.990  6.26
#> 10 10         TRUE   100        4    27 100     100     0       3.96   2.67
#> 
#> $metrics
#>       AUC     ACC     PRC     TPR    TNR
#> 1 0.84351 0.19776 0.19355 0.35644 0.1018
#> 
#> $cv_metrics
#> # A tibble: 20 × 8
#>    metric    mean      sd cv_1_valid cv_2_valid cv_3_valid cv_4_valid cv_5_valid
#>    <chr>    <dbl>   <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
#>  1 accura…  0.804 0.0422       0.768      0.84       0.824      0.75       0.839
#>  2 auc      0.852 0.0166       0.843      0.834      0.87       0.843      0.869
#>  3 err      0.196 0.0422       0.232      0.16       0.176      0.25       0.161
#>  4 err_co… 24.4   5.22        29         20         22         31         20    
#>  5 f0poin…  0.752 0.0719       0.655      0.806      0.817      0.696      0.785
#>  6 f1       0.751 0.0319       0.707      0.773      0.788      0.735      0.75 
#>  7 f2       0.754 0.0241       0.768      0.742      0.762      0.779      0.718
#>  8 lift_t…  2.61  0.297        2.91       2.66       2.27       2.34       2.88 
#>  9 logloss  0.460 0.0225       0.442      0.459      0.472      0.491      0.436
#> 10 max_pe…  0.277 0.0220       0.256      0.277      0.255      0.296      0.302
#> 11 mcc      0.595 0.0677       0.533      0.654      0.642      0.510      0.636
#> 12 mean_p…  0.795 0.0258       0.779      0.817      0.816      0.758      0.806
#> 13 mean_p…  0.205 0.0258       0.221      0.183      0.184      0.242      0.194
#> 14 mse      0.148 0.00787      0.143      0.142      0.153      0.159      0.142
#> 15 pr_auc   0.832 0.0324       0.796      0.808      0.877      0.834      0.847
#> 16 precis…  0.755 0.0989       0.625      0.829      0.837      0.672      0.811
#> 17 r2       0.373 0.0159       0.368      0.393      0.380      0.350      0.375
#> 18 recall   0.758 0.0524       0.814      0.723      0.745      0.811      0.698
#> 19 rmse     0.384 0.0102       0.378      0.377      0.391      0.399      0.376
#> 20 specif…  0.832 0.0997       0.744      0.910      0.886      0.704      0.914
#> 
#> $max_metrics
#>                         metric  threshold       value idx
#> 1                       max f1 0.33189946   0.7172676 218
#> 2                       max f2 0.20588823   0.8012094 276
#> 3                 max f0point5 0.70915049   0.7938540 102
#> 4                 max accuracy 0.61029190   0.8073836 129
#> 5                max precision 0.97336936   1.0000000   0
#> 6                   max recall 0.04285963   1.0000000 397
#> 7              max specificity 0.97336936   1.0000000   0
#> 8             max absolute_mcc 0.61029190   0.5892866 129
#> 9   max min_per_class_accuracy 0.37319173   0.7643979 209
#> 10 max mean_per_class_accuracy 0.61029190   0.7709478 129
#> 11                     max tns 0.97336936 382.0000000   0
#> 12                     max fns 0.97336936 240.0000000   0
#> 13                     max fps 0.03630845 382.0000000 399
#> 14                     max tps 0.04285963 241.0000000 397
#> 15                     max tnr 0.97336936   1.0000000   0
#> 16                     max fnr 0.97336936   0.9958506   0
#> 17                     max fpr 0.03630845   1.0000000 399
#> 18                     max tpr 0.04285963   1.0000000 397

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.

r$plots$metrics
#> $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           200.82881        1.00000000 0.37921203
#> 2       Fare            89.74341        0.44686521 0.16945666
#> 3        Age            80.46456        0.40066244 0.15193602
#> 4   Pclass.3            71.07552        0.35391095 0.13420729
#> 5   Sex.male            43.91920        0.21868972 0.08292977
#> 6 Embarked.S            16.28304        0.08107921 0.03074621

r$plots$importance

Classification: Multi-Categorical

Now, let’s run a multi-categorical (+2 labels) model to predict Pclass of each passenger:

r <- h2o_automl(df, Pclass, ignore = c("Fare", "Cabin"), max_time = 30, plots = FALSE)
#> 2021-12-03 15:10:27 | Started process...
#> - 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_7_20211203_151028            0.4742325 0.8170807 0.5409388
#> 2 XGBoost_1_AutoML_7_20211203_151028            0.4946035 0.8255072 0.5392879
#> 3     GBM_1_AutoML_7_20211203_151028            0.5037168 0.8620436 0.5616772
#>         mse
#> 1 0.2926147
#> 2 0.2908315
#> 3 0.3154812
#> SELECTED MODEL: GLM_1_AutoML_7_20211203_151028
#> - 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_7_20211203_151028
#> 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: 29.2s

Let’s take a look at the plots generated into a single dashboard:

plot(r)

Regression

Finally, a regression model with continuous values to predict Fare payed by passenger:

r <- h2o_automl(df, y = "Fare", ignore = "Pclass", exclude_algos = NULL, quiet = TRUE)
print(r)
#> Model (1/7): StackedEnsemble_BestOfFamily_1_AutoML_8_20211203_151059
#> Independent Variable: Fare
#> Type: Regression
#> Algorithm: STACKEDENSEMBLE
#> Split: 70% training data (of 871 observations)
#> Seed: 0
#> 
#> Test metrics:
#>    rmse = 20.17
#>    mae = 14.079
#>    mape = 0.068862
#>    mse = 406.82
#>    rsq = 0.367
#>    rsqa = 0.3645

Let’s take a look at the plots generated into a single dashboard:

plot(r)

Export models and results

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.

Import and use your models

If you’d like to re-use your exported models to predict new datasets, you have several options:

Addittional Posts