library(tidyverse)
attrition_raw_tbl <- read_csv(“../00_data/WA_Fn-UseC_-HR-Employee-Attrition.csv”)
attrition_raw_tbl %>% glimpse()
attrition_raw_tbl %>% slice(0) %>% glimpse()
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() ──
## ✖ 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("../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.
# Load required libraries
library(tidyverse)
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()
## • Use tidymodels_prefer() to resolve common conflicts.
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: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
# 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
# Handle missing values if any
# (Assuming no missing values for simplicity)
# Encode categorical variables
attrition_recipe <- recipe(Attrition ~ ., data = train_data) %>%
step_rm(Over18) %>% # Remove the Over18 column
step_dummy(all_nominal(), -all_outcomes()) %>%
prep()
train_data <- bake(attrition_recipe, new_data = train_data)
test_data <- bake(attrition_recipe, new_data = test_data)
# Step 3: Build a predictive model
h2o.init()
## Connection successful!
##
## R is connected to the H2O cluster:
## H2O cluster uptime: 1 hours 13 minutes
## 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 16 days
## H2O cluster name: H2O_started_from_R_Jstan_fhp551
## H2O cluster total nodes: 1
## H2O cluster total memory: 1.74 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 16 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
train_h2o <- as.h2o(train_data)
##
|
| | 0%
|
|======================================================================| 100%
test_h2o <- as.h2o(test_data)
##
|
| | 0%
|
|======================================================================| 100%
attrition_gbm <- h2o.gbm(x = names(train_data)[-which(names(train_data) == "Attrition")],
y = "Attrition",
training_frame = train_h2o,
validation_frame = test_h2o,
ntrees = 50,
learn_rate = 0.1,
max_depth = 5)
## Warning in .h2o.processResponseWarnings(res): Dropping bad and constant columns: [StandardHours, EmployeeCount].
##
|
| | 0%
|
|======================== | 34%
|
|======================================================================| 100%
# Step 4: Evaluate the model
# Convert the test data back to a data frame
test_df <- as.data.frame(test_data)
# Extract the actual Attrition values
actual_values <- test_df$Attrition
# Predictions
predictions <- as.vector(h2o.predict(attrition_gbm, newdata = test_h2o)$predict)
##
|
| | 0%
|
|======================================================================| 100%
# Convert predictions to binary (0 or 1)
predicted_classes <- ifelse(predictions > 0.5, 1, 0)
# Calculate accuracy
accuracy <- mean(as.integer(predicted_classes) == as.integer(actual_values))
print(paste("Accuracy:", accuracy))
## [1] "Accuracy: 0.83710407239819"
# Step 5: Predict the probability of attrition for new data
# You can use the trained h2o model to predict attrition probabilities for new data
All Prommpts: Please update the code to use tidymodels instead of caret and to use h2o model instead of gimnet.
Error in step_dummy(): Caused by error in
bake(): ! Only one factor level in Over18: Y Backtrace: 1.
… %>% prep() 3. recipes:::prep.recipe(.) 8.
recipes:::bake.step_dummy(x$steps[[i]], new_data = training)
Error in h2o.performance(): ! model must an
H2OModel object Backtrace: 1. h2o::h2o.performance(h2o_performance,
“accuracy”) Execution halted
Error in h2o.metric(): ! No accuracy for
H2ORegressionModel .Should be a H2OModelMetrics object! Backtrace: 1.
h2o::h2o.accuracy(attrition_gbm) 2. h2o::h2o.metric(object, thresholds,
“accuracy”)
Error Message: Error in h2o.metric(): ! argument
“metric” is missing, with no default Backtrace: 1.
h2o::h2o.metric(h2o_performance, “accuracy”) 3. base::paste0(“No”,
metric, ” for “, class(object))
Error Message: ! No accuracy for H2ORegressionMetrics Backtrace: 1. h2o::h2o.metric(h2o_performance, metric = “accuracy”)
Error Message: Error in
predicted_classes == actual_values: ! comparison (==) is
possible only for atomic and list types Backtrace: 1.
base::mean(predicted_classes == actual_values)