Skip to contents

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")
#> 2022-06-01 17:01:35 | Started process...
#> - INDEPENDENT VARIABLE: Survived
#> - MODEL TYPE: Classification
#> 
[38;5;246m# A tibble: 2 × 5
[39m
#>   tag       n     p order  pcum
#>   
[3m
[38;5;246m<lgl>
[39m
[23m 
[3m
[38;5;246m<int>
[39m
[23m 
[3m
[38;5;246m<dbl>
[39m
[23m 
[3m
[38;5;246m<int>
[39m
[23m 
[3m
[38;5;246m<dbl>
[39m
[23m
#> 
[38;5;250m1
[39m FALSE   549  61.6     1  61.6
#> 
[38;5;250m2
[39m 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 58 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_20220601_170136 0.8363389 0.4619035 0.8069542
#>   mean_per_class_error      rmse       mse
#> 1            0.2233445 0.3841742 0.1475898
#> SELECTED MODEL: XGBoost_1_AutoML_1_20220601_170136
#> - NOTE: The following variables were the least important: Embarked.C, Parch, Pclass.2
#> >>> Running predictions for Survived...
#> 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
#> 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
#> Target value: TRUE
#> >>> Generating plots...
#> Model (1/1): XGBoost_1_AutoML_1_20220601_170136
#> Independent Variable: Survived
#> Type: Classification (2 classes)
#> Algorithm: XGBOOST
#> Split: 70% training data (of 891 observations)
#> Seed: 0
#> 
#> Test metrics:
#>    AUC = 0.86359
#>    ACC = 0.1903
#>    PRC = 0.19672
#>    TPR = 0.33962
#>    TNR = 0.092593
#> 
#> Most important variables:
#>    Sex.female (33.6%)
#>    Fare (17.9%)
#>    Age (16.7%)
#>    Pclass.3 (10.9%)
#>    Sex.male (8.4%)
#> Process duration: 8.12s

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    15  147
#>   TRUE     70   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.1     27    27  25.5    25.5 153.      25.5  85.2 
#>  2 2          TRUE    20.1     24    27  48.1    50.9 139.      22.6  67.4 
#>  3 3          TRUE    30.2     16    27  63.2    76.4 109.      15.1  53.4 
#>  4 4          TRUE    39.9     13    26  75.5   100    89.0     12.3  36.5 
#>  5 5          TRUE    50        7    27  82.1   100    64.2      6.60 26.8 
#>  6 6          TRUE    60.1      6    27  87.7   100    46.0      5.66 21.3 
#>  7 7          TRUE    69.8      5    26  92.5   100    32.5      4.72 15.1 
#>  8 8          TRUE    79.9      2    27  94.3   100    18.1      1.89 10.7 
#>  9 9          TRUE    89.9      4    27  98.1   100     9.11     3.77  7.97
#> 10 10         TRUE   100        2    27 100     100     0        1.89  5.60
#> 
#> $metrics
#>       AUC    ACC     PRC     TPR      TNR
#> 1 0.86359 0.1903 0.19672 0.33962 0.092593
#> 
#> $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 accuracy  0.804 0.0483      0.832      0.856      0.736      0.823      0.774
#>  2 auc       0.840 0.0420      0.872      0.876      0.773      0.828      0.849
#>  3 err       0.196 0.0483      0.168      0.144      0.264      0.177      0.226
#>  4 err_cou… 24.4   6.02       21         18         33         22         28    
#>  5 f0point5  0.742 0.0621      0.790      0.820      0.668      0.707      0.724
#>  6 f1        0.745 0.0478      0.804      0.769      0.680      0.718      0.754
#>  7 f2        0.750 0.0511      0.817      0.725      0.692      0.729      0.788
#>  8 lift_to…  2.68  0.392       2.40       2.91       2.5        3.26       2.34 
#>  9 logloss   0.462 0.0620      0.439      0.396      0.561      0.439      0.474
#> 10 max_per…  0.258 0.0524      0.173      0.302      0.3        0.263      0.254
#> 11 mcc       0.586 0.0879      0.658      0.674      0.456      0.589      0.552
#> 12 mean_pe…  0.791 0.0397      0.831      0.818      0.73       0.799      0.779
#> 13 mean_pe…  0.209 0.0397      0.169      0.182      0.27       0.201      0.221
#> 14 mse       0.148 0.0254      0.139      0.122      0.188      0.134      0.155
#> 15 pr_auc    0.817 0.0519      0.863      0.852      0.734      0.803      0.834
#> 16 precisi…  0.741 0.0785      0.782      0.857      0.660      0.7        0.705
#> 17 r2        0.368 0.0931      0.428      0.460      0.218      0.369      0.366
#> 18 recall    0.755 0.0612      0.827      0.698      0.7        0.737      0.811
#> 19 rmse      0.383 0.0324      0.373      0.349      0.433      0.366      0.394
#> 20 specifi…  0.828 0.0786      0.836      0.939      0.76       0.860      0.746
#> 
#> $max_metrics
#>                         metric  threshold       value idx
#> 1                       max f1 0.43715739   0.7222222 175
#> 2                       max f2 0.11679161   0.7804878 336
#> 3                 max f0point5 0.72127157   0.7786885  94
#> 4                 max accuracy 0.46230718   0.7945425 166
#> 5                max precision 0.97245646   1.0000000   0
#> 6                   max recall 0.04442137   1.0000000 398
#> 7              max specificity 0.97245646   1.0000000   0
#> 8             max absolute_mcc 0.46230718   0.5584419 166
#> 9   max min_per_class_accuracy 0.35420930   0.7669492 204
#> 10 max mean_per_class_accuracy 0.43715739   0.7766555 175
#> 11                     max tns 0.97245646 387.0000000   0
#> 12                     max fns 0.97245646 235.0000000   0
#> 13                     max fps 0.03055004 387.0000000 399
#> 14                     max tps 0.04442137 236.0000000 398
#> 15                     max tnr 0.97245646   1.0000000   0
#> 16                     max fnr 0.97245646   0.9957627   0
#> 17                     max fpr 0.03055004   1.0000000 399
#> 18                     max tpr 0.04442137   1.0000000 398

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           156.29817         1.0000000 0.33574571
#> 2       Fare            83.43919         0.5338463 0.17923659
#> 3        Age            77.69765         0.4971117 0.16690313
#> 4   Pclass.3            50.77672         0.3248709 0.10907400
#> 5   Sex.male            39.16495         0.2505784 0.08413063
#> 6   Pclass.1            26.88816         0.1720312 0.05775873

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)
#> 2022-06-01 17:01:47 | Started process...
#> - INDEPENDENT VARIABLE: Pclass
#> - MODEL TYPE: Classification
#> 
[38;5;246m# A tibble: 3 × 5
[39m
#>   tag       n     p order  pcum
#>   
[3m
[38;5;246m<fct>
[39m
[23m 
[3m
[38;5;246m<int>
[39m
[23m 
[3m
[38;5;246m<dbl>
[39m
[23m 
[3m
[38;5;246m<int>
[39m
[23m 
[3m
[38;5;246m<dbl>
[39m
[23m
#> 
[38;5;250m1
[39m n_3     491  55.1     1  55.1
#> 
[38;5;250m2
[39m n_1     216  24.2     2  79.4
#> 
[38;5;250m3
[39m 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_20220601_170148            0.4742325 0.8170807 0.5409388
#> 2 XGBoost_1_AutoML_2_20220601_170148            0.4946035 0.8255072 0.5392879
#> 3     GBM_1_AutoML_2_20220601_170148            0.5046914 0.8579317 0.5592290
#>         mse
#> 1 0.2926147
#> 2 0.2908315
#> 3 0.3127371
#> SELECTED MODEL: GLM_1_AutoML_2_20220601_170148
#> - 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_20220601_170148
#> 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: 8.75s

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/4): StackedEnsemble_BestOfFamily_1_AutoML_3_20220601_170158
#> 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)

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:

  • 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 issues
  • h2o_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.