library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.4.1
## Warning: package 'dplyr' was built under R version 4.4.1
## Warning: package 'lubridate' was built under R version 4.4.1
## ── 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
attrition_raw_tbl <- read_csv("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.
attrition_raw_tbl %>% glimpse()
## 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, …
# Load necessary libraries
library(tidyverse)
library(tidymodels)
## Warning: package 'tidymodels' was built under R version 4.4.1
## ── Attaching packages ────────────────────────────────────── tidymodels 1.2.0 ──
## ✔ broom        1.0.6      ✔ 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.1 
## ✔ recipes      1.0.10
## Warning: package 'dials' was built under R version 4.4.1
## Warning: package 'infer' was built under R version 4.4.1
## Warning: package 'modeldata' was built under R version 4.4.1
## Warning: package 'parsnip' was built under R version 4.4.1
## Warning: package 'tune' was built under R version 4.4.1
## Warning: package 'workflows' was built under R version 4.4.1
## Warning: package 'workflowsets' was built under R version 4.4.1
## Warning: package 'yardstick' was built under R version 4.4.1
## ── 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()
## • Dig deeper into tidy modeling with R at https://www.tmwr.org
library(h2o)
## Warning: package 'h2o' was built under R version 4.4.2
## 
## ----------------------------------------------------------------------
## 
## 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
# Initialize H2O cluster
h2o.init()
## 
## H2O is not running yet, starting it now...
## 
## Note:  In case of errors look at the following log files:
##     C:\Users\Surplus\AppData\Local\Temp\RtmpgDN8Gc\file4e48167c1f51/h2o_Surplus_started_from_r.out
##     C:\Users\Surplus\AppData\Local\Temp\RtmpgDN8Gc\file4e4854f27d21/h2o_Surplus_started_from_r.err
## 
## 
## Starting H2O JVM and connecting:  Connection successful!
## 
## R is connected to the H2O cluster: 
##     H2O cluster uptime:         6 seconds 157 milliseconds 
##     H2O cluster timezone:       America/New_York 
##     H2O data parsing timezone:  UTC 
##     H2O cluster version:        3.44.0.3 
##     H2O cluster version age:    11 months and 27 days 
##     H2O cluster name:           H2O_started_from_R_Surplus_qyz143 
##     H2O cluster total nodes:    1 
##     H2O cluster total memory:   1.75 GB 
##     H2O cluster total cores:    4 
##     H2O cluster allowed cores:  4 
##     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.0 (2024-04-24 ucrt)
## Warning in h2o.clusterInfo(): 
## Your H2O cluster version is (11 months and 27 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
# Preprocessing the dataset
attrition_raw_tbl <- attrition_raw_tbl %>%
  mutate(
    Attrition = as.factor(Attrition),
    BusinessTravel = as.factor(BusinessTravel),
    Department = as.factor(Department),
    EducationField = as.factor(EducationField),
    Gender = as.factor(Gender),
    MaritalStatus = as.factor(MaritalStatus),
    OverTime = as.factor(OverTime)
  )
# Split the data into training and testing sets
set.seed(123) # For reproducibility
data_split <- initial_split(attrition_raw_tbl, prop = 0.8, strata = Attrition)
train_data <- training(data_split)
test_data <- testing(data_split)

# Data preprocessing using recipe
attrition_recipe <- recipe(Attrition ~ ., data = train_data) %>%
  step_rm(EmployeeCount, Over18, StandardHours, EmployeeNumber) %>% # Remove irrelevant columns
  step_dummy(all_nominal_predictors(), -all_outcomes()) %>%         # One-hot encode categorical variables
  step_normalize(all_numeric_predictors())                         # Normalize numeric predictors
# Prepare the processed data
attrition_prep <- attrition_recipe %>% prep()
train_processed <- bake(attrition_prep, new_data = NULL)
test_processed <- bake(attrition_prep, new_data = test_data)

# Convert processed data to H2O frame
train_h2o <- as.h2o(train_processed)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
test_h2o <- as.h2o(test_processed)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
# Train an H2O logistic regression model
h2o_model <- h2o.glm(
  x = setdiff(names(train_processed), "Attrition"),
  y = "Attrition",
  training_frame = train_h2o,
  family = "binomial"
)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
# Summarize the H2O model
h2o.performance(h2o_model, train_h2o)
## H2OBinomialMetrics: glm
## 
## MSE:  0.08694483
## RMSE:  0.2948641
## LogLoss:  0.2985547
## Mean Per-Class Error:  0.2371723
## AUC:  0.861967
## AUCPR:  0.6711617
## Gini:  0.723934
## R^2:  0.3558592
## Residual Deviance:  701.6034
## AIC:  791.6034
## 
## Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold:
##         No Yes    Error       Rate
## No     920  66 0.066937    =66/986
## Yes     77 112 0.407407    =77/189
## Totals 997 178 0.121702  =143/1175
## 
## Maximum Metrics: Maximum metrics at their respective thresholds
##                         metric threshold      value idx
## 1                       max f1  0.357925   0.610354 134
## 2                       max f2  0.190545   0.672192 211
## 3                 max f0point5  0.537526   0.694200  78
## 4                 max accuracy  0.493309   0.893617  87
## 5                max precision  0.979064   1.000000   0
## 6                   max recall  0.004499   1.000000 391
## 7              max specificity  0.979064   1.000000   0
## 8             max absolute_mcc  0.451954   0.552022 100
## 9   max min_per_class_accuracy  0.174629   0.788360 222
## 10 max mean_per_class_accuracy  0.214204   0.793511 198
## 11                     max tns  0.979064 986.000000   0
## 12                     max fns  0.979064 188.000000   0
## 13                     max fps  0.000211 986.000000 399
## 14                     max tps  0.004499 189.000000 391
## 15                     max tnr  0.979064   1.000000   0
## 16                     max fnr  0.979064   0.994709   0
## 17                     max fpr  0.000211   1.000000 399
## 18                     max tpr  0.004499   1.000000 391
## 
## Gains/Lift Table: Extract with `h2o.gainsLift(<model>, <data>)` or `h2o.gainsLift(<model>, valid=<T/F>, xval=<T/F>)`
# Make predictions on the test set
predictions <- h2o.predict(h2o_model, newdata = test_h2o)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
# Add predictions back to the test set
test_results <- test_data %>%
  mutate(
    predicted_prob = as.vector(predictions$Yes),
    predicted_class = ifelse(predicted_prob > 0.5, "Yes", "No")
  )
# Ensure predicted_class is a factor with levels matching Attrition
test_results <- test_results %>%
  mutate(
    predicted_class = factor(predicted_class, levels = levels(Attrition))
  )
# Evaluate model performance
metrics <- test_results %>%
  metrics(truth = Attrition, estimate = predicted_class)

# Compute confusion matrix
conf_matrix <- test_results %>%
  conf_mat(truth = Attrition, estimate = predicted_class)
# Print evaluation metrics
metrics %>%
  as_tibble() %>%
  arrange(desc(.metric)) %>%
  print()
## # A tibble: 2 × 3
##   .metric  .estimator .estimate
##   <chr>    <chr>          <dbl>
## 1 kap      binary         0.473
## 2 accuracy binary         0.875
# Plot confusion matrix
autoplot(conf_matrix)

# Shut down H2O
h2o.shutdown(prompt = FALSE)