Goal is to automate building and tuning a classification model to predict employee attrition, using the h2o::h2o.automl.

Set up

Import data

Import the cleaned data from Module 7.

library(h2o)
## Warning: package 'h2o' was built under R version 4.3.3
## 
## ----------------------------------------------------------------------
## 
## Your next step is to start H2O:
##     > h2o.init()
## 
## For H2O package documentation, ask for help:
##     > ??h2o
## 
## After starting H2O, you can use the Web UI at http://localhost:54321
## For more information visit https://docs.h2o.ai
## 
## ----------------------------------------------------------------------
## 
## Attaching package: 'h2o'
## The following objects are masked from 'package:stats':
## 
##     cor, sd, var
## The following objects are masked from 'package:base':
## 
##     %*%, %in%, &&, ||, apply, as.factor, as.numeric, colnames,
##     colnames<-, ifelse, is.character, is.factor, is.numeric, log,
##     log10, log1p, log2, round, signif, trunc
library(tidyverse)
## Warning: package 'ggplot2' was built under R version 4.3.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.5.0     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ lubridate::day()   masks h2o::day()
## ✖ dplyr::filter()    masks stats::filter()
## ✖ lubridate::hour()  masks h2o::hour()
## ✖ dplyr::lag()       masks stats::lag()
## ✖ lubridate::month() masks h2o::month()
## ✖ lubridate::week()  masks h2o::week()
## ✖ lubridate::year()  masks h2o::year()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tidymodels)
## Warning: package 'tidymodels' was built under R version 4.3.2
## ── Attaching packages ────────────────────────────────────── tidymodels 1.1.1 ──
## ✔ broom        1.0.5     ✔ rsample      1.2.0
## ✔ dials        1.2.0     ✔ tune         1.1.2
## ✔ infer        1.0.6     ✔ workflows    1.1.3
## ✔ modeldata    1.3.0     ✔ workflowsets 1.0.1
## ✔ parsnip      1.1.1     ✔ yardstick    1.3.0
## ✔ recipes      1.0.8
## Warning: package 'dials' was built under R version 4.3.2
## Warning: package 'scales' was built under R version 4.3.2
## Warning: package 'infer' was built under R version 4.3.2
## Warning: package 'modeldata' was built under R version 4.3.2
## Warning: package 'parsnip' was built under R version 4.3.2
## Warning: package 'tune' was built under R version 4.3.2
## Warning: package 'workflows' was built under R version 4.3.2
## Warning: package 'workflowsets' was built under R version 4.3.2
## Warning: package 'yardstick' was built under R version 4.3.2
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ scales::discard() masks purrr::discard()
## ✖ dplyr::filter()   masks stats::filter()
## ✖ recipes::fixed()  masks stringr::fixed()
## ✖ dplyr::lag()      masks stats::lag()
## ✖ yardstick::spec() masks readr::spec()
## ✖ recipes::step()   masks stats::step()
## • Learn how to get started at https://www.tidymodels.org/start/
library(tidyquant)
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## 
## Attaching package: 'PerformanceAnalytics'
## 
## The following object is masked from 'package:graphics':
## 
##     legend
## 
## Loading required package: quantmod
## Loading required package: TTR
## 
## Attaching package: 'TTR'
## 
## The following object is masked from 'package:dials':
## 
##     momentum
## 
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(readr)
data <- read_csv("C:/Users/Jstan/OneDrive/Desktop/Intermediate Data/PSUDAT3100/00_data/WA_Fn-UseC_-HR-Employee-Attrition.csv")
## Rows: 1470 Columns: 35
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (9): Attrition, BusinessTravel, Department, EducationField, Gender, Job...
## dbl (26): Age, DailyRate, DistanceFromHome, Education, EmployeeCount, Employ...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
data
## # A tibble: 1,470 × 35
##      Age Attrition BusinessTravel    DailyRate Department       DistanceFromHome
##    <dbl> <chr>     <chr>                 <dbl> <chr>                       <dbl>
##  1    41 Yes       Travel_Rarely          1102 Sales                           1
##  2    49 No        Travel_Frequently       279 Research & Deve…                8
##  3    37 Yes       Travel_Rarely          1373 Research & Deve…                2
##  4    33 No        Travel_Frequently      1392 Research & Deve…                3
##  5    27 No        Travel_Rarely           591 Research & Deve…                2
##  6    32 No        Travel_Frequently      1005 Research & Deve…                2
##  7    59 No        Travel_Rarely          1324 Research & Deve…                3
##  8    30 No        Travel_Rarely          1358 Research & Deve…               24
##  9    38 No        Travel_Frequently       216 Research & Deve…               23
## 10    36 No        Travel_Rarely          1299 Research & Deve…               27
## # ℹ 1,460 more rows
## # ℹ 29 more variables: Education <dbl>, EducationField <chr>,
## #   EmployeeCount <dbl>, EmployeeNumber <dbl>, EnvironmentSatisfaction <dbl>,
## #   Gender <chr>, HourlyRate <dbl>, JobInvolvement <dbl>, JobLevel <dbl>,
## #   JobRole <chr>, JobSatisfaction <dbl>, MaritalStatus <chr>,
## #   MonthlyIncome <dbl>, MonthlyRate <dbl>, NumCompaniesWorked <dbl>,
## #   Over18 <chr>, OverTime <chr>, PercentSalaryHike <dbl>, …
factors_vec <- data %>% select(Education, EnvironmentSatisfaction, JobInvolvement, JobSatisfaction, PerformanceRating, RelationshipSatisfaction, WorkLifeBalance) %>% names()

data_clean <- data %>%
    #Address factors imported as numeric
    mutate(across(all_of(factors_vec), as.factor)) %>%
    
    # Drop zero-variance variables
    select(-c(Over18, EmployeeCount, StandardHours)) %>%
    
    mutate(across(where(is.character), factor))

glimpse(data_clean)
## Rows: 1,470
## Columns: 32
## $ Age                      <dbl> 41, 49, 37, 33, 27, 32, 59, 30, 38, 36, 35, 2…
## $ Attrition                <fct> Yes, No, Yes, No, No, No, No, No, No, No, No,…
## $ BusinessTravel           <fct> Travel_Rarely, Travel_Frequently, Travel_Rare…
## $ DailyRate                <dbl> 1102, 279, 1373, 1392, 591, 1005, 1324, 1358,…
## $ Department               <fct> Sales, Research & Development, Research & Dev…
## $ DistanceFromHome         <dbl> 1, 8, 2, 3, 2, 2, 3, 24, 23, 27, 16, 15, 26, …
## $ Education                <fct> 2, 1, 2, 4, 1, 2, 3, 1, 3, 3, 3, 2, 1, 2, 3, …
## $ EducationField           <fct> Life Sciences, Life Sciences, Other, Life Sci…
## $ EmployeeNumber           <dbl> 1, 2, 4, 5, 7, 8, 10, 11, 12, 13, 14, 15, 16,…
## $ EnvironmentSatisfaction  <fct> 2, 3, 4, 4, 1, 4, 3, 4, 4, 3, 1, 4, 1, 2, 3, …
## $ Gender                   <fct> Female, Male, Male, Female, Male, Male, Femal…
## $ HourlyRate               <dbl> 94, 61, 92, 56, 40, 79, 81, 67, 44, 94, 84, 4…
## $ JobInvolvement           <fct> 3, 2, 2, 3, 3, 3, 4, 3, 2, 3, 4, 2, 3, 3, 2, …
## $ JobLevel                 <dbl> 2, 2, 1, 1, 1, 1, 1, 1, 3, 2, 1, 2, 1, 1, 1, …
## $ JobRole                  <fct> Sales Executive, Research Scientist, Laborato…
## $ JobSatisfaction          <fct> 4, 2, 3, 3, 2, 4, 1, 3, 3, 3, 2, 3, 3, 4, 3, …
## $ MaritalStatus            <fct> Single, Married, Single, Married, Married, Si…
## $ MonthlyIncome            <dbl> 5993, 5130, 2090, 2909, 3468, 3068, 2670, 269…
## $ MonthlyRate              <dbl> 19479, 24907, 2396, 23159, 16632, 11864, 9964…
## $ NumCompaniesWorked       <dbl> 8, 1, 6, 1, 9, 0, 4, 1, 0, 6, 0, 0, 1, 0, 5, …
## $ OverTime                 <fct> Yes, No, Yes, Yes, No, No, Yes, No, No, No, N…
## $ PercentSalaryHike        <dbl> 11, 23, 15, 11, 12, 13, 20, 22, 21, 13, 13, 1…
## $ PerformanceRating        <fct> 3, 4, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 3, …
## $ RelationshipSatisfaction <fct> 1, 4, 2, 3, 4, 3, 1, 2, 2, 2, 3, 4, 4, 3, 2, …
## $ StockOptionLevel         <dbl> 0, 1, 0, 0, 1, 0, 3, 1, 0, 2, 1, 0, 1, 1, 0, …
## $ TotalWorkingYears        <dbl> 8, 10, 7, 8, 6, 8, 12, 1, 10, 17, 6, 10, 5, 3…
## $ TrainingTimesLastYear    <dbl> 0, 3, 3, 3, 3, 2, 3, 2, 2, 3, 5, 3, 1, 2, 4, …
## $ WorkLifeBalance          <fct> 1, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3, 2, 3, 3, …
## $ YearsAtCompany           <dbl> 6, 10, 0, 8, 2, 7, 1, 1, 9, 7, 5, 9, 5, 2, 4,…
## $ YearsInCurrentRole       <dbl> 4, 7, 0, 7, 2, 7, 0, 0, 7, 7, 4, 5, 2, 2, 2, …
## $ YearsSinceLastPromotion  <dbl> 0, 1, 0, 3, 2, 3, 0, 0, 1, 7, 0, 0, 4, 1, 0, …
## $ YearsWithCurrManager     <dbl> 5, 7, 0, 0, 2, 6, 0, 0, 8, 7, 3, 8, 3, 2, 3, …

Split data

set.seed(1234)

data_split <- initial_split(data_clean, strata = "Attrition")
train_tbl <- training(data_split)
test_tbl <- testing(data_split)

Recipes

recipe_obj <- recipe(Attrition ~ ., data = train_tbl) %>%
    
    # Remove zero variance variables
    step_zv(all_predictors()) 

Model

# Initialize h2o
h2o.init()
## 
## H2O is not running yet, starting it now...
## 
## Note:  In case of errors look at the following log files:
##     C:\Users\Jstan\AppData\Local\Temp\RtmpOETykb\file6420765b1841/h2o_Jstan_started_from_r.out
##     C:\Users\Jstan\AppData\Local\Temp\RtmpOETykb\file6420655eb86/h2o_Jstan_started_from_r.err
## 
## 
## Starting H2O JVM and connecting: . Connection successful!
## 
## R is connected to the H2O cluster: 
##     H2O cluster uptime:         4 seconds 65 milliseconds 
##     H2O cluster timezone:       America/New_York 
##     H2O data parsing timezone:  UTC 
##     H2O cluster version:        3.44.0.3 
##     H2O cluster version age:    4 months and 18 days 
##     H2O cluster name:           H2O_started_from_R_Jstan_fhp551 
##     H2O cluster total nodes:    1 
##     H2O cluster total memory:   1.94 GB 
##     H2O cluster total cores:    8 
##     H2O cluster allowed cores:  8 
##     H2O cluster healthy:        TRUE 
##     H2O Connection ip:          localhost 
##     H2O Connection port:        54321 
##     H2O Connection proxy:       NA 
##     H2O Internal Security:      FALSE 
##     R Version:                  R version 4.3.1 (2023-06-16 ucrt)
## Warning in h2o.clusterInfo(): 
## Your H2O cluster version is (4 months and 18 days) old. There may be a newer version available.
## Please download and install the latest version from: https://h2o-release.s3.amazonaws.com/h2o/latest_stable.html
split.h2o <- h2o.splitFrame(as.h2o(train_tbl), ratios = c(0.85), seed = 1235)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
train_h2o <- split.h2o[[1]]
valid_h2o <- split.h2o[[2]]
test_h2o <- as.h2o(test_tbl)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
y <- "Attrition"
x <- setdiff(names(train_tbl), y)

models_h2o <- h2o.automl(
    x = x,
    y = y,
    training_frame = train_h2o,
    validation_frame = valid_h2o,
    leaderboard_frame = test_h2o,
    max_runtime_secs = 30,
    nfolds = 5,
    seed = 1523)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |===                                                                   |   4%
## 13:13:42.594: User specified a validation frame with cross-validation still enabled. Please note that the models will still be validated using cross-validation only, the validation frame will be used to provide purely informative validation metrics on the trained models.
## 13:13:42.615: AutoML: XGBoost is not available; skipping it.
  |                                                                            
  |=======                                                               |  11%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |======================================================================| 100%
models_h2o %>% typeof()
## [1] "S4"
models_h2o %>% slotNames()
## [1] "project_name"   "leader"         "leaderboard"    "event_log"     
## [5] "modeling_steps" "training_info"
models_h2o@leaderboard
##                                                  model_id       auc   logloss
## 1 StackedEnsemble_BestOfFamily_1_AutoML_1_20240509_131342 0.8457389 0.3108670
## 2                          GBM_1_AutoML_1_20240509_131342 0.8393743 0.3276879
## 3 StackedEnsemble_BestOfFamily_4_AutoML_1_20240509_131342 0.8377023 0.3313649
## 4 StackedEnsemble_BestOfFamily_3_AutoML_1_20240509_131342 0.8368932 0.3242535
## 5 StackedEnsemble_BestOfFamily_2_AutoML_1_20240509_131342 0.8368393 0.3221989
## 6                          GLM_1_AutoML_1_20240509_131342 0.8366775 0.3216285
##       aucpr mean_per_class_error      rmse        mse
## 1 0.6521905            0.2149676 0.3012776 0.09076818
## 2 0.6011589            0.2246764 0.3128686 0.09788676
## 3 0.6640050            0.1996764 0.3087477 0.09532513
## 4 0.6612023            0.2406958 0.3041739 0.09252174
## 5 0.6574361            0.2101133 0.3029567 0.09178274
## 6 0.6330270            0.2557443 0.3074904 0.09455036
## 
## [25 rows x 7 columns]
best_model <- models_h2o@leader
best_model
## Model Details:
## ==============
## 
## H2OBinomialModel: stackedensemble
## Model ID:  StackedEnsemble_BestOfFamily_1_AutoML_1_20240509_131342 
## Model Summary for Stacked Ensemble: 
##                                    key            value
## 1                    Stacking strategy cross_validation
## 2 Number of base models (used / total)              2/2
## 3     # GBM base models (used / total)              1/1
## 4     # GLM base models (used / total)              1/1
## 5                Metalearner algorithm              GLM
## 6   Metalearner fold assignment scheme           Random
## 7                   Metalearner nfolds                5
## 8              Metalearner fold_column               NA
## 9   Custom metalearner hyperparameters             None
## 
## 
## H2OBinomialMetrics: stackedensemble
## ** Reported on training data. **
## 
## MSE:  0.07074738
## RMSE:  0.2659838
## LogLoss:  0.2523481
## Mean Per-Class Error:  0.167144
## AUC:  0.9123509
## AUCPR:  0.7992585
## Gini:  0.8247018
## 
## Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold:
##         No Yes    Error     Rate
## No     746  35 0.044814  =35/781
## Yes     44 108 0.289474  =44/152
## Totals 790 143 0.084673  =79/933
## 
## Maximum Metrics: Maximum metrics at their respective thresholds
##                         metric threshold      value idx
## 1                       max f1  0.362001   0.732203 115
## 2                       max f2  0.267316   0.759097 149
## 3                 max f0point5  0.516904   0.830078  74
## 4                 max accuracy  0.516904   0.922830  74
## 5                max precision  0.948780   1.000000   0
## 6                   max recall  0.004867   1.000000 391
## 7              max specificity  0.948780   1.000000   0
## 8             max absolute_mcc  0.516904   0.691492  74
## 9   max min_per_class_accuracy  0.206982   0.842105 183
## 10 max mean_per_class_accuracy  0.267316   0.854492 149
## 11                     max tns  0.948780 781.000000   0
## 12                     max fns  0.948780 151.000000   0
## 13                     max fps  0.000723 781.000000 399
## 14                     max tps  0.004867 152.000000 391
## 15                     max tnr  0.948780   1.000000   0
## 16                     max fnr  0.948780   0.993421   0
## 17                     max fpr  0.000723   1.000000 399
## 18                     max tpr  0.004867   1.000000 391
## 
## Gains/Lift Table: Extract with `h2o.gainsLift(<model>, <data>)` or `h2o.gainsLift(<model>, valid=<T/F>, xval=<T/F>)`
## H2OBinomialMetrics: stackedensemble
## ** Reported on validation data. **
## 
## MSE:  0.07848421
## RMSE:  0.2801503
## LogLoss:  0.2783257
## Mean Per-Class Error:  0.2044755
## AUC:  0.866014
## AUCPR:  0.6889672
## Gini:  0.732028
## 
## Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold:
##         No Yes    Error     Rate
## No     136   7 0.048951   =7/143
## Yes      9  16 0.360000    =9/25
## Totals 145  23 0.095238  =16/168
## 
## Maximum Metrics: Maximum metrics at their respective thresholds
##                         metric threshold      value idx
## 1                       max f1  0.410193   0.666667  22
## 2                       max f2  0.140760   0.677419  54
## 3                 max f0point5  0.557493   0.740741  13
## 4                 max accuracy  0.557493   0.910714  13
## 5                max precision  0.972597   1.000000   0
## 6                   max recall  0.009026   1.000000 155
## 7              max specificity  0.972597   1.000000   0
## 8             max absolute_mcc  0.513884   0.620966  19
## 9   max min_per_class_accuracy  0.175808   0.790210  49
## 10 max mean_per_class_accuracy  0.140760   0.801119  54
## 11                     max tns  0.972597 143.000000   0
## 12                     max fns  0.972597  24.000000   0
## 13                     max fps  0.002717 143.000000 167
## 14                     max tps  0.009026  25.000000 155
## 15                     max tnr  0.972597   1.000000   0
## 16                     max fnr  0.972597   0.960000   0
## 17                     max fpr  0.002717   1.000000 167
## 18                     max tpr  0.009026   1.000000 155
## 
## Gains/Lift Table: Extract with `h2o.gainsLift(<model>, <data>)` or `h2o.gainsLift(<model>, valid=<T/F>, xval=<T/F>)`
## H2OBinomialMetrics: stackedensemble
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
## 
## MSE:  0.09410337
## RMSE:  0.3067627
## LogLoss:  0.3272577
## Mean Per-Class Error:  0.2418079
## AUC:  0.832081
## AUCPR:  0.6284665
## Gini:  0.664162
## 
## Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold:
##         No Yes    Error      Rate
## No     727  54 0.069142   =54/781
## Yes     63  89 0.414474   =63/152
## Totals 790 143 0.125402  =117/933
## 
## Maximum Metrics: Maximum metrics at their respective thresholds
##                         metric threshold      value idx
## 1                       max f1  0.329737   0.603390 114
## 2                       max f2  0.169543   0.651214 204
## 3                 max f0point5  0.490390   0.678879  65
## 4                 max accuracy  0.490390   0.888532  65
## 5                max precision  0.943267   1.000000   0
## 6                   max recall  0.001498   1.000000 398
## 7              max specificity  0.943267   1.000000   0
## 8             max absolute_mcc  0.329737   0.529345 114
## 9   max min_per_class_accuracy  0.171534   0.769737 202
## 10 max mean_per_class_accuracy  0.184402   0.774665 195
## 11                     max tns  0.943267 781.000000   0
## 12                     max fns  0.943267 151.000000   0
## 13                     max fps  0.001051 781.000000 399
## 14                     max tps  0.001498 152.000000 398
## 15                     max tnr  0.943267   1.000000   0
## 16                     max fnr  0.943267   0.993421   0
## 17                     max fpr  0.001051   1.000000 399
## 18                     max tpr  0.001498   1.000000 398
## 
## Gains/Lift Table: Extract with `h2o.gainsLift(<model>, <data>)` or `h2o.gainsLift(<model>, valid=<T/F>, xval=<T/F>)`
## Cross-Validation Metrics Summary: 
##                mean       sd cv_1_valid cv_2_valid cv_3_valid cv_4_valid
## accuracy   0.882697 0.038071   0.917098   0.910995   0.871508   0.822581
## auc        0.828122 0.046002   0.866695   0.803746   0.851724   0.859774
## err        0.117303 0.038071   0.082902   0.089005   0.128492   0.177419
## err_count 21.800000 6.833740  16.000000  17.000000  23.000000  33.000000
## f0point5   0.659094 0.081791   0.743802   0.720000   0.664557   0.536481
##           cv_5_valid
## accuracy    0.891304
## auc         0.758669
## err         0.108696
## err_count  20.000000
## f0point5    0.630631
## 
## ---
##                         mean       sd cv_1_valid cv_2_valid cv_3_valid
## precision           0.675339 0.109435   0.782609   0.750000   0.677419
## r2                  0.304412 0.046335   0.359537   0.317880   0.314642
## recall              0.627024 0.085125   0.620690   0.620690   0.617647
## residual_deviance 121.894005 7.082528 109.750520 126.416504 123.152390
## rmse                0.307452 0.016203   0.285964   0.296383   0.324735
## specificity         0.931105 0.054799   0.969512   0.962963   0.931034
##                   cv_4_valid cv_5_valid
## precision           0.500000   0.666667
## r2                  0.297836   0.232165
## recall              0.757576   0.518518
## residual_deviance 122.740060 127.410545
## rmse                0.320117   0.310062
## specificity         0.836601   0.955414

Save and Load

#h2o.getModel("GBM_grid_1_AutoML_1_20240417_173906_model_1") %>%
  #h2o.saveModel("h2o_models/")

#best_model <- h2o.loadModel("h2o_models/GBM_grid_1_AutoML_1_20240417_173906_model_1")

Make predictions

predictions <- h2o.predict(best_model, newdata = test_h2o)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
predictions_tbl <- predictions %>%
  as_tibble()

predictions_tbl %>%
  bind_cols(test_tbl)
## # A tibble: 369 × 35
##    predict    No     Yes   Age Attrition BusinessTravel    DailyRate Department 
##    <fct>   <dbl>   <dbl> <dbl> <fct>     <fct>                 <dbl> <fct>      
##  1 No      0.690 0.310      59 No        Travel_Rarely          1324 Research &…
##  2 No      0.933 0.0670     35 No        Travel_Rarely           809 Research &…
##  3 No      0.961 0.0392     34 No        Travel_Rarely          1346 Research &…
##  4 No      0.785 0.215      22 No        Non-Travel             1123 Research &…
##  5 No      0.976 0.0236     53 No        Travel_Rarely          1219 Sales      
##  6 No      0.978 0.0222     24 No        Non-Travel              673 Research &…
##  7 No      0.873 0.127      21 No        Travel_Rarely           391 Research &…
##  8 No      0.932 0.0679     34 Yes       Travel_Rarely           699 Research &…
##  9 No      0.997 0.00306    53 No        Travel_Rarely          1282 Research &…
## 10 Yes     0.169 0.831      32 Yes       Travel_Frequently      1125 Research &…
## # ℹ 359 more rows
## # ℹ 27 more variables: DistanceFromHome <dbl>, Education <fct>,
## #   EducationField <fct>, EmployeeNumber <dbl>, EnvironmentSatisfaction <fct>,
## #   Gender <fct>, HourlyRate <dbl>, JobInvolvement <fct>, JobLevel <dbl>,
## #   JobRole <fct>, JobSatisfaction <fct>, MaritalStatus <fct>,
## #   MonthlyIncome <dbl>, MonthlyRate <dbl>, NumCompaniesWorked <dbl>,
## #   OverTime <fct>, PercentSalaryHike <dbl>, PerformanceRating <fct>, …

Evaluate model

?h2o.performance
## starting httpd help server ... done
performance_h2o <- h2o.performance(best_model, newdata = test_h2o)
typeof(performance_h2o)
## [1] "S4"
slotNames(performance_h2o)
## [1] "algorithm" "on_train"  "on_valid"  "on_xval"   "metrics"
performance_h2o@metrics
## $model
## $model$`__meta`
## $model$`__meta`$schema_version
## [1] 3
## 
## $model$`__meta`$schema_name
## [1] "ModelKeyV3"
## 
## $model$`__meta`$schema_type
## [1] "Key<Model>"
## 
## 
## $model$name
## [1] "StackedEnsemble_BestOfFamily_1_AutoML_1_20240509_131342"
## 
## $model$type
## [1] "Key<Model>"
## 
## $model$URL
## [1] "/3/Models/StackedEnsemble_BestOfFamily_1_AutoML_1_20240509_131342"
## 
## 
## $model_checksum
## [1] "-5820552871344264680"
## 
## $frame
## $frame$name
## [1] "test_tbl_sid_9840_3"
## 
## 
## $frame_checksum
## [1] "-54414925341915866"
## 
## $description
## NULL
## 
## $scoring_time
## [1] 1.715275e+12
## 
## $predictions
## NULL
## 
## $MSE
## [1] 0.09076818
## 
## $RMSE
## [1] 0.3012776
## 
## $nobs
## [1] 369
## 
## $custom_metric_name
## NULL
## 
## $custom_metric_value
## [1] 0
## 
## $r2
## [1] 0.3333826
## 
## $logloss
## [1] 0.310867
## 
## $AUC
## [1] 0.8457389
## 
## $pr_auc
## [1] 0.6521905
## 
## $Gini
## [1] 0.6914779
## 
## $mean_per_class_error
## [1] 0.2149676
## 
## $domain
## [1] "No"  "Yes"
## 
## $cm
## $cm$`__meta`
## $cm$`__meta`$schema_version
## [1] 3
## 
## $cm$`__meta`$schema_name
## [1] "ConfusionMatrixV3"
## 
## $cm$`__meta`$schema_type
## [1] "ConfusionMatrix"
## 
## 
## $cm$table
## Confusion Matrix: Row labels: Actual class; Column labels: Predicted class
##         No Yes  Error       Rate
## No     274  35 0.1133 = 35 / 309
## Yes     19  41 0.3167 =  19 / 60
## Totals 293  76 0.1463 = 54 / 369
## 
## 
## $thresholds_and_metric_scores
## Metrics for Thresholds: Binomial metrics as a function of classification thresholds
##   threshold       f1       f2 f0point5 accuracy precision   recall specificity
## 1  0.948260 0.032787 0.020747 0.078125 0.840108  1.000000 0.016667    1.000000
## 2  0.940206 0.064516 0.041322 0.147059 0.842818  1.000000 0.033333    1.000000
## 3  0.940102 0.095238 0.061728 0.208333 0.845528  1.000000 0.050000    1.000000
## 4  0.893476 0.125000 0.081967 0.263158 0.848238  1.000000 0.066667    1.000000
## 5  0.831028 0.153846 0.102041 0.312500 0.850949  1.000000 0.083333    1.000000
##   absolute_mcc min_per_class_accuracy mean_per_class_accuracy tns fns fps tps
## 1     0.118299               0.016667                0.508333 309  59   0   1
## 2     0.167527               0.033333                0.516667 309  58   0   2
## 3     0.205458               0.050000                0.525000 309  57   0   3
## 4     0.237568               0.066667                0.533333 309  56   0   4
## 5     0.265973               0.083333                0.541667 309  55   0   5
##        tnr      fnr      fpr      tpr idx
## 1 1.000000 0.983333 0.000000 0.016667   0
## 2 1.000000 0.966667 0.000000 0.033333   1
## 3 1.000000 0.950000 0.000000 0.050000   2
## 4 1.000000 0.933333 0.000000 0.066667   3
## 5 1.000000 0.916667 0.000000 0.083333   4
## 
## ---
##     threshold       f1       f2 f0point5 accuracy precision   recall
## 364  0.001661 0.283019 0.496689 0.197889 0.176152  0.164835 1.000000
## 365  0.001315 0.282353 0.495868 0.197368 0.173442  0.164384 1.000000
## 366  0.001124 0.281690 0.495050 0.196850 0.170732  0.163934 1.000000
## 367  0.000865 0.281030 0.494234 0.196335 0.168022  0.163488 1.000000
## 368  0.000809 0.280374 0.493421 0.195822 0.165312  0.163043 1.000000
## 369  0.000570 0.279720 0.492611 0.195313 0.162602  0.162602 1.000000
##     specificity absolute_mcc min_per_class_accuracy mean_per_class_accuracy tns
## 364    0.016181     0.051645               0.016181                0.508091   5
## 365    0.012945     0.046130               0.012945                0.506472   4
## 366    0.009709     0.039895               0.009709                0.504854   3
## 367    0.006472     0.032530               0.006472                0.503236   2
## 368    0.003236     0.022971               0.003236                0.501618   1
## 369    0.000000     0.000000               0.000000                0.500000   0
##     fns fps tps      tnr      fnr      fpr      tpr idx
## 364   0 304  60 0.016181 0.000000 0.983819 1.000000 363
## 365   0 305  60 0.012945 0.000000 0.987055 1.000000 364
## 366   0 306  60 0.009709 0.000000 0.990291 1.000000 365
## 367   0 307  60 0.006472 0.000000 0.993528 1.000000 366
## 368   0 308  60 0.003236 0.000000 0.996764 1.000000 367
## 369   0 309  60 0.000000 0.000000 1.000000 1.000000 368
## 
## $max_criteria_and_metric_scores
## Maximum Metrics: Maximum metrics at their respective thresholds
##                         metric threshold      value idx
## 1                       max f1  0.296958   0.602941  75
## 2                       max f2  0.260290   0.665635  82
## 3                 max f0point5  0.606458   0.705128  23
## 4                 max accuracy  0.606458   0.891599  23
## 5                max precision  0.948260   1.000000   0
## 6                   max recall  0.018508   1.000000 301
## 7              max specificity  0.948260   1.000000   0
## 8             max absolute_mcc  0.467279   0.541270  38
## 9   max min_per_class_accuracy  0.158723   0.760518 119
## 10 max mean_per_class_accuracy  0.260290   0.793608  82
## 11                     max tns  0.948260 309.000000   0
## 12                     max fns  0.948260  59.000000   0
## 13                     max fps  0.000570 309.000000 368
## 14                     max tps  0.018508  60.000000 301
## 15                     max tnr  0.948260   1.000000   0
## 16                     max fnr  0.948260   0.983333   0
## 17                     max fpr  0.000570   1.000000 368
## 18                     max tpr  0.018508   1.000000 301
## 
## $gains_lift_table
## Gains/Lift Table: Avg response rate: 16.26 %, avg score: 16.72 %
##    group cumulative_data_fraction lower_threshold     lift cumulative_lift
## 1      1               0.01084011        0.851011 6.150000        6.150000
## 2      2               0.02168022        0.759438 4.612500        5.381250
## 3      3               0.03252033        0.710368 6.150000        5.637500
## 4      4               0.04065041        0.669865 6.150000        5.740000
## 5      5               0.05149051        0.653368 6.150000        5.826316
## 6      6               0.10027100        0.493950 3.075000        4.487838
## 7      7               0.15176152        0.348824 1.942105        3.624107
## 8      8               0.20054201        0.298783 2.391667        3.324324
## 9      9               0.30081301        0.189414 0.831081        2.493243
## 10    10               0.40108401        0.123223 0.498649        1.994595
## 11    11               0.50135501        0.080567 0.498649        1.695405
## 12    12               0.59891599        0.054548 0.683333        1.530543
## 13    13               0.69918699        0.035283 0.166216        1.334884
## 14    14               0.79945799        0.020677 0.332432        1.209153
## 15    15               0.89972900        0.009679 0.332432        1.111446
## 16    16               1.00000000        0.000570 0.000000        1.000000
##    response_rate    score cumulative_response_rate cumulative_score
## 1       1.000000 0.930511                 1.000000         0.930511
## 2       0.750000 0.795514                 0.875000         0.863012
## 3       1.000000 0.729192                 0.916667         0.818406
## 4       1.000000 0.682241                 0.933333         0.791173
## 5       1.000000 0.661355                 0.947368         0.763843
## 6       0.500000 0.570087                 0.729730         0.669583
## 7       0.315789 0.408511                 0.589286         0.581005
## 8       0.388889 0.322687                 0.540541         0.518171
## 9       0.135135 0.230009                 0.405405         0.422117
## 10      0.081081 0.146515                 0.324324         0.353217
## 11      0.081081 0.099645                 0.275676         0.302502
## 12      0.111111 0.067385                 0.248869         0.264203
## 13      0.027027 0.043611                 0.217054         0.232567
## 14      0.054054 0.025474                 0.196610         0.206593
## 15      0.054054 0.015610                 0.180723         0.185309
## 16      0.000000 0.004749                 0.162602         0.167204
##    capture_rate cumulative_capture_rate        gain cumulative_gain
## 1      0.066667                0.066667  515.000000      515.000000
## 2      0.050000                0.116667  361.250000      438.125000
## 3      0.066667                0.183333  515.000000      463.750000
## 4      0.050000                0.233333  515.000000      474.000000
## 5      0.066667                0.300000  515.000000      482.631579
## 6      0.150000                0.450000  207.500000      348.783784
## 7      0.100000                0.550000   94.210526      262.410714
## 8      0.116667                0.666667  139.166667      232.432432
## 9      0.083333                0.750000  -16.891892      149.324324
## 10     0.050000                0.800000  -50.135135       99.459459
## 11     0.050000                0.850000  -50.135135       69.540541
## 12     0.066667                0.916667  -31.666667       53.054299
## 13     0.016667                0.933333  -83.378378       33.488372
## 14     0.033333                0.966667  -66.756757       20.915254
## 15     0.033333                1.000000  -66.756757       11.144578
## 16     0.000000                1.000000 -100.000000        0.000000
##    kolmogorov_smirnov
## 1            0.066667
## 2            0.113430
## 3            0.180097
## 4            0.230097
## 5            0.296764
## 6            0.417638
## 7            0.475566
## 8            0.556634
## 9            0.536408
## 10           0.476375
## 11           0.416343
## 12           0.379450
## 13           0.279612
## 14           0.199676
## 15           0.119741
## 16           0.000000
## 
## $residual_deviance
## [1] 229.4198
## 
## $null_deviance
## [1] 327.6419
## 
## $AIC
## [1] 235.4198
## 
## $loglikelihood
## [1] 0
## 
## $null_degrees_of_freedom
## [1] 368
## 
## $residual_degrees_of_freedom
## [1] 366
h2o.auc(performance_h2o)
## [1] 0.8457389
h2o.confusionMatrix(performance_h2o)
## Confusion Matrix (vertical: actual; across: predicted)  for max f1 @ threshold = 0.296958386752964:
##         No Yes    Error     Rate
## No     274  35 0.113269  =35/309
## Yes     19  41 0.316667   =19/60
## Totals 293  76 0.146341  =54/369