Load Required Libraries

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ 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.4.2
## ── Attaching packages ────────────────────────────────────── tidymodels 1.2.0 ──
## ✔ broom        1.0.8     ✔ rsample      1.2.1
## ✔ dials        1.3.0     ✔ tune         1.2.1
## ✔ infer        1.0.7     ✔ workflows    1.1.4
## ✔ modeldata    1.4.0     ✔ workflowsets 1.1.0
## ✔ parsnip      1.2.1     ✔ yardstick    1.3.2
## ✔ recipes      1.1.0
## Warning: package 'broom' was built under R version 4.4.3
## Warning: package 'dials' was built under R version 4.4.2
## Warning: package 'infer' was built under R version 4.4.2
## Warning: package 'modeldata' was built under R version 4.4.2
## Warning: package 'parsnip' was built under R version 4.4.2
## Warning: package 'tune' was built under R version 4.4.2
## Warning: package 'workflows' was built under R version 4.4.2
## Warning: package 'workflowsets' was built under R version 4.4.2
## Warning: package 'yardstick' was built under R version 4.4.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()
## • Use tidymodels_prefer() to resolve common conflicts.
library(h2o)
## Warning: package 'h2o' was built under R version 4.4.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:lubridate':
## 
##     day, hour, month, week, year
## 
## 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

Load Data

attrition_raw_tbl <- read_csv("../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.
# Use glimpse to examine the data
glimpse(attrition_raw_tbl)
## Rows: 1,470
## Columns: 35
## $ Age                      <dbl> 41, 49, 37, 33, 27, 32, 59, 30, 38, 36, 35, 2…
## $ Attrition                <chr> "Yes", "No", "Yes", "No", "No", "No", "No", "…
## $ BusinessTravel           <chr> "Travel_Rarely", "Travel_Frequently", "Travel…
## $ DailyRate                <dbl> 1102, 279, 1373, 1392, 591, 1005, 1324, 1358,…
## $ Department               <chr> "Sales", "Research & Development", "Research …
## $ DistanceFromHome         <dbl> 1, 8, 2, 3, 2, 2, 3, 24, 23, 27, 16, 15, 26, …
## $ Education                <dbl> 2, 1, 2, 4, 1, 2, 3, 1, 3, 3, 3, 2, 1, 2, 3, …
## $ EducationField           <chr> "Life Sciences", "Life Sciences", "Other", "L…
## $ EmployeeCount            <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
## $ EmployeeNumber           <dbl> 1, 2, 4, 5, 7, 8, 10, 11, 12, 13, 14, 15, 16,…
## $ EnvironmentSatisfaction  <dbl> 2, 3, 4, 4, 1, 4, 3, 4, 4, 3, 1, 4, 1, 2, 3, …
## $ Gender                   <chr> "Female", "Male", "Male", "Female", "Male", "…
## $ HourlyRate               <dbl> 94, 61, 92, 56, 40, 79, 81, 67, 44, 94, 84, 4…
## $ JobInvolvement           <dbl> 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                  <chr> "Sales Executive", "Research Scientist", "Lab…
## $ JobSatisfaction          <dbl> 4, 2, 3, 3, 2, 4, 1, 3, 3, 3, 2, 3, 3, 4, 3, …
## $ MaritalStatus            <chr> "Single", "Married", "Single", "Married", "Ma…
## $ 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, …
## $ Over18                   <chr> "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", …
## $ OverTime                 <chr> "Yes", "No", "Yes", "Yes", "No", "No", "Yes",…
## $ PercentSalaryHike        <dbl> 11, 23, 15, 11, 12, 13, 20, 22, 21, 13, 13, 1…
## $ PerformanceRating        <dbl> 3, 4, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 3, …
## $ RelationshipSatisfaction <dbl> 1, 4, 2, 3, 4, 3, 1, 2, 2, 2, 3, 4, 4, 3, 2, …
## $ StandardHours            <dbl> 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 8…
## $ 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          <dbl> 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, …

Step 1: Split the Data

set.seed(123)
split <- initial_split(attrition_raw_tbl, prop = 0.8, strata = "Attrition")
train_data <- training(split)
test_data <- testing(split)

# Optional: Reduce training size for faster prototyping
train_data <- train_data %>% sample_frac(0.5)

Step 2: Preprocess the Data with Tidymodels

attrition_recipe <- recipe(Attrition ~ ., data = train_data) %>%
  step_rm(Over18, EmployeeCount, StandardHours) %>%
  step_dummy(all_nominal(), one_hot = TRUE) %>%
  step_center(all_numeric(), -all_outcomes()) %>%
  step_scale(all_numeric(), -all_outcomes())

# Fit the recipe
attrition_recipe_prep <- prep(attrition_recipe, training = train_data)

# Apply preprocessing
train_data_processed <- bake(attrition_recipe_prep, new_data = train_data)
test_data_processed <- bake(attrition_recipe_prep, new_data = test_data)

Step 3: Train a Model Using H2O AutoML

h2o.init()
##  Connection successful!
## 
## R is connected to the H2O cluster: 
##     H2O cluster uptime:         2 minutes 48 seconds 
##     H2O cluster timezone:       America/New_York 
##     H2O data parsing timezone:  UTC 
##     H2O cluster version:        3.44.0.3 
##     H2O cluster version age:    1 year, 4 months and 10 days 
##     H2O cluster name:           H2O_started_from_R_adamc_pcs264 
##     H2O cluster total nodes:    1 
##     H2O cluster total memory:   2.89 GB 
##     H2O cluster total cores:    12 
##     H2O cluster allowed cores:  12 
##     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.4.1 (2024-06-14 ucrt)
## Warning in h2o.clusterInfo(): 
## Your H2O cluster version is (1 year, 4 months and 10 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
# Convert to H2OFrame
train_h2o <- as.h2o(train_data_processed)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
test_h2o <- as.h2o(test_data_processed)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
# Define predictors and response
predictors <- setdiff(names(train_data_processed), "Attrition_Yes")
response <- "Attrition_Yes"

# Train AutoML
automl <- h2o.automl(
  x = predictors,
  y = response,
  training_frame = train_h2o,
  max_runtime_secs = 30,
  max_models = 5,
  exclude_algos = c("StackedEnsemble"),
  seed = 123
)
##   |                                                                              |                                                                      |   0%  |                                                                              |=======                                                               |  10%
## 19:10:43.797: AutoML: XGBoost is not available; skipping it.  |                                                                              |===========                                                           |  15%  |                                                                              |======================================================================| 100%

Step 4: Evaluate Best Model

predictions <- h2o.predict(automl@leader, newdata = test_h2o)$predict
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%

Step 5: Assess Performance

performance <- h2o.performance(automl@leader, newdata = test_h2o)
print(performance)
## H2ORegressionMetrics: glm
## 
## MSE:  0.0001298281
## RMSE:  0.01139421
## MAE:  0.00864985
## RMSLE:  0.01229906
## Mean Residual Deviance :  0.0001298281
## R^2 :  0.9998729
## Null Deviance :301.3765
## Null D.o.F. :294
## Residual Deviance :0.03829928
## Residual D.o.F. :241
## AIC :-1692.87

Optional: Inspect Best Model

summary(automl@leader)
## Model Details:
## ==============
## 
## H2ORegressionModel: glm
## Model Key:  GLM_1_AutoML_2_20250430_191043 
## GLM Model: summary
##     family     link              regularization
## 1 gaussian identity Ridge ( lambda = 0.009983 )
##                                                                    lambda_search
## 1 nlambda = 30, lambda.max = 99.83, lambda.min = 0.009983, lambda.1se = 0.009983
##   number_of_predictors_total number_of_active_predictors number_of_iterations
## 1                         53                          53                   30
##                                                      training_frame
## 1 AutoML_2_20250430_191043_training_train_data_processed_sid_95dd_1
## 
## H2ORegressionMetrics: glm
## ** Reported on training data. **
## 
## MSE:  0.0001286205
## RMSE:  0.0113411
## MAE:  0.008406775
## RMSLE:  0.01152495
## Mean Residual Deviance :  0.0001286205
## R^2 :  0.9998712
## Null Deviance :587
## Null D.o.F. :587
## Residual Deviance :0.07562884
## Residual D.o.F. :534
## AIC :-3489.011
## 
## 
## 
## H2ORegressionMetrics: glm
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
## 
## MSE:  0.0002617287
## RMSE:  0.01617803
## MAE:  0.011901
## RMSLE:  0.01652345
## Mean Residual Deviance :  0.0002617287
## R^2 :  0.9997378
## Null Deviance :590.8731
## Null D.o.F. :587
## Residual Deviance :0.1538964
## Residual D.o.F. :534
## AIC :-3071.271
## 
## 
## Cross-Validation Metrics Summary: 
##                              mean        sd cv_1_valid cv_2_valid cv_3_valid
## mae                      0.011903  0.000737   0.011863   0.011444   0.011489
## mean_residual_deviance   0.000262  0.000032   0.000247   0.000267   0.000232
## mse                      0.000262  0.000032   0.000247   0.000267   0.000232
## null_deviance          118.174614 26.120630  99.503430 124.715546  85.238010
## r2                       0.999727  0.000045   0.999703   0.999747   0.999661
## residual_deviance        0.030779  0.003714   0.029177   0.031482   0.027371
## rmse                     0.016157  0.000976   0.015725   0.016334   0.015230
## rmsle                    0.016395  0.002266   0.018804   0.013793   0.018740
##                        cv_4_valid cv_5_valid
## mae                      0.011529   0.013187
## mean_residual_deviance   0.000248   0.000315
## mse                      0.000248   0.000315
## null_deviance          129.812580 151.603490
## r2                       0.999776   0.999750
## residual_deviance        0.028983   0.036884
## rmse                     0.015739   0.017755
## rmsle                    0.015052   0.015584
## 
## Scoring History: 
##             timestamp   duration iteration lambda predictors deviance_train
## 1 2025-04-30 19:10:44  0.000 sec         1   .1E3         54          0.970
## 2 2025-04-30 19:10:44  0.000 sec         2  .73E2         54          0.960
## 3 2025-04-30 19:10:44  0.000 sec         3  .53E2         54          0.947
## 4 2025-04-30 19:10:44  0.000 sec         4  .39E2         54          0.929
## 5 2025-04-30 19:10:44  0.000 sec         5  .28E2         54          0.906
##   deviance_xval deviance_se    alpha iterations training_rmse training_deviance
## 1         0.985       0.099 0.000000         NA            NA                NA
## 2         0.977       0.098 0.000000         NA            NA                NA
## 3         0.967       0.097 0.000000         NA            NA                NA
## 4         0.953       0.096 0.000000         NA            NA                NA
## 5         0.935       0.094 0.000000         NA            NA                NA
##   training_mae training_r2
## 1           NA          NA
## 2           NA          NA
## 3           NA          NA
## 4           NA          NA
## 5           NA          NA
## 
## ---
##              timestamp   duration iteration lambda predictors deviance_train
## 26 2025-04-30 19:10:44  0.014 sec        26 .36E-1         54          0.002
## 27 2025-04-30 19:10:44  0.014 sec        27 .26E-1         54          0.001
## 28 2025-04-30 19:10:44  0.014 sec        28 .19E-1         54          0.000
## 29 2025-04-30 19:10:44  0.014 sec        29 .14E-1         54          0.000
## 30 2025-04-30 19:10:44  0.018 sec        30  .1E-1         54          0.000
## 31 2025-04-30 19:10:44  0.018 sec        31   .0E0         54          0.000
##    deviance_xval deviance_se    alpha iterations training_rmse
## 26         0.003       0.000 0.000000         NA            NA
## 27         0.002       0.000 0.000000         NA            NA
## 28         0.001       0.000 0.000000         NA            NA
## 29         0.000       0.000 0.000000         NA            NA
## 30         0.000       0.000 0.000000         NA            NA
## 31         0.000       0.000 0.000000         31       0.01134
##    training_deviance training_mae training_r2
## 26                NA           NA          NA
## 27                NA           NA          NA
## 28                NA           NA          NA
## 29                NA           NA          NA
## 30                NA           NA          NA
## 31           0.00013      0.00841     0.99987
## 
## Variable Importances: (Extract with `h2o.varimp`) 
## =================================================
## 
## Variable Importances: 
##                  variable relative_importance scaled_importance percentage
## 1            Attrition_No            0.986911          1.000000   0.958840
## 2            OverTime_Yes            0.005037          0.005104   0.004894
## 3 EnvironmentSatisfaction            0.002244          0.002274   0.002180
## 4    MaritalStatus_Single            0.002067          0.002094   0.002008
## 5      YearsInCurrentRole            0.002063          0.002091   0.002004
## 
## ---
##                        variable relative_importance scaled_importance
## 48 EducationField_Life.Sciences            0.000176          0.000178
## 49       EducationField_Medical            0.000075          0.000076
## 50             StockOptionLevel            0.000043          0.000044
## 51             Department_Sales            0.000039          0.000040
## 52   JobRole_Research.Scientist            0.000010          0.000010
## 53                MonthlyIncome            0.000001          0.000001
##    percentage
## 48   0.000171
## 49   0.000073
## 50   0.000042
## 51   0.000038
## 52   0.000010
## 53   0.000001