Load necessary libraries
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.4 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ 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)
## ── 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.9
## ── 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()
## • Search for functions across packages at https://www.tidymodels.org/find/
library(h2o)
##
## ----------------------------------------------------------------------
##
## 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
library(readr)
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.
Step 1: Split the data into training and testing sets
set.seed(123) # for reproducibility
split <- initial_split(attrition_raw_tbl, prop = 0.7, strata = "Attrition")
train_data <- training(split)
test_data <- testing(split)
Step 2: Preprocess the data
For simplicity, let’s drop EmployeeNumber and Over18 columns
train_data <- train_data %>%
select(-c(EmployeeNumber, Over18))
test_data <- test_data %>%
select(-c(EmployeeNumber, Over18))
Encode categorical variables
train_data <- train_data %>%
mutate(across(where(is.character), as.factor))
test_data <- test_data %>%
mutate(across(where(is.character), as.factor))
Step 3: Build a predictive model
h2o.init()
## Connection successful!
##
## R is connected to the H2O cluster:
## H2O cluster uptime: 12 days 23 hours
## 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 10 days
## H2O cluster name: H2O_started_from_R_spencer_qns693
## H2O cluster total nodes: 1
## H2O cluster total memory: 2.90 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.2.2 (2022-10-31)
## Warning in h2o.clusterInfo():
## Your H2O cluster version is (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 data to h2o frame
train_h2o <- as.h2o(train_data)
##
|
| | 0%
|
|======================================================================| 100%
test_h2o <- as.h2o(test_data)
##
|
| | 0%
|
|======================================================================| 100%
Specify predictor and response variables
predictors <- setdiff(names(train_data), "Attrition")
Train logistic regression model
model <- h2o.glm(x = predictors, y = "Attrition", training_frame = train_h2o, family = "binomial")
## Warning in .h2o.processResponseWarnings(res): Dropping bad and constant columns: [StandardHours, EmployeeCount].
##
|
| | 0%
|
|======================================================================| 100%
Step 5: Evaluate the model
Make predictions on test data
predictions <- h2o.predict(model, newdata = test_h2o)
##
|
| | 0%
|
|======================================================================| 100%
predicted_probs <- as.vector(predictions$predict)
Compute confusion matrix
predicted_classes <- ifelse(predicted_probs > 0.5, "Yes", "No")
confusion_matrix <- table(test_data$Attrition, predicted_classes)
accuracy <- sum(diag(confusion_matrix)) / sum(confusion_matrix)
print("Confusion Matrix:")
## [1] "Confusion Matrix:"
print(confusion_matrix)
## predicted_classes
## Yes
## No 370
## Yes 72
print(paste("Accuracy:", accuracy))
## [1] "Accuracy: 0.83710407239819"
Step 6: Predict attrition probability for new data
For new data, use h2o.predict(model, newdata = new_data) with type =
“response”