Please write R code to create a predictive model that predicts the probability of attrition. The goal is to help predict attrition for employees. I have also provided a glimpse of the dataset as well as a skim of the dataset.
attrition_raw_tbl %>% glimpse() Rows: 1,470 Columns: 35 $ Age
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(skimr)
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(xgboost)
##
## Attaching package: 'xgboost'
##
## The following object is masked from 'package:dplyr':
##
## slice
library(tidymodels)
## ── 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.2
## ✔ recipes 1.1.1
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ scales::discard() masks purrr::discard()
## ✖ dplyr::filter() masks stats::filter()
## ✖ recipes::fixed() masks stringr::fixed()
## ✖ dplyr::lag() masks stats::lag()
## ✖ xgboost::slice() masks dplyr::slice()
## ✖ yardstick::spec() masks readr::spec()
## ✖ recipes::step() masks stats::step()
## • Learn how to get started at https://www.tidymodels.org/start/
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.
# If data is not sensitive:
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 libraries
# Set seed for reproducibility
set.seed(123)
# Step 1: Prepare the data
attrition_tbl <- attrition_raw_tbl %>%
mutate(Attrition = as.factor(Attrition)) # Ensure target is a factor
# Step 2: Split the data
attrition_split <- initial_split(attrition_tbl, prop = 0.8, strata = Attrition)
attrition_train <- training(attrition_split)
attrition_test <- testing(attrition_split)
# Step 3: Preprocessing recipe
attrition_recipe <- recipe(Attrition ~ ., data = attrition_train) %>%
update_role(EmployeeNumber, new_role = "ID") %>% # Don't use ID in modeling
step_rm(EmployeeCount, Over18, StandardHours) %>% # Remove constant/uninformative features
step_dummy(all_nominal_predictors()) %>% # Convert categorical to dummies
step_zv(all_predictors()) %>% # Remove zero variance predictors
step_normalize(all_numeric_predictors()) # Normalize numeric features
# Step 4: Define the model (logistic regression)
log_reg_spec <- logistic_reg() %>%
set_engine("glm") %>%
set_mode("classification")
# Step 5: Create the workflow
attrition_workflow <- workflow() %>%
add_model(log_reg_spec) %>%
add_recipe(attrition_recipe)
# Step 6: Train the model
attrition_fit <- fit(attrition_workflow, data = attrition_train)
# Step 7: Predict probabilities on the test set
attrition_predictions <- predict(attrition_fit, attrition_test, type = "prob") %>%
bind_cols(attrition_test %>% select(Attrition))
# Step 8: View performance (ROC AUC)
roc_auc(attrition_predictions, truth = Attrition, .pred_Yes)
## # A tibble: 1 × 3
## .metric .estimator .estimate
## <chr> <chr> <dbl>
## 1 roc_auc binary 0.112
Please also create an h2o model
# Load libraries
library(tidyverse)
library(tidymodels)
library(h2o)
# Initialize H2O
h2o.init()
##
## H2O is not running yet, starting it now...
##
## Note: In case of errors look at the following log files:
## /var/folders/4c/kdd2fy0s48v8h8jvs3y0drph0000gn/T//Rtmpd0ogcI/file2bdf17fe3213/h2o_bradymartin_started_from_r.out
## /var/folders/4c/kdd2fy0s48v8h8jvs3y0drph0000gn/T//Rtmpd0ogcI/file2bdf318989b3/h2o_bradymartin_started_from_r.err
##
##
## Starting H2O JVM and connecting: .. Connection successful!
##
## R is connected to the H2O cluster:
## H2O cluster uptime: 2 seconds 879 milliseconds
## 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 16 days
## H2O cluster name: H2O_started_from_R_bradymartin_ggl822
## H2O cluster total nodes: 1
## H2O cluster total memory: 3.54 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.4.2 (2024-10-31)
## Warning in h2o.clusterInfo():
## Your H2O cluster version is (1 year, 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
# Set seed for reproducibility
set.seed(123)
# Step 1: Prepare the data
attrition_tbl <- attrition_raw_tbl %>%
mutate(Attrition = as.factor(Attrition)) # Ensure target is a factor
# Step 2: Split the data
attrition_split <- initial_split(attrition_tbl, prop = 0.8, strata = Attrition)
attrition_train <- training(attrition_split)
attrition_test <- testing(attrition_split)
# Step 3: Preprocessing recipe
attrition_recipe <- recipe(Attrition ~ ., data = attrition_train) %>%
update_role(EmployeeNumber, new_role = "ID") %>% # Exclude ID
step_rm(EmployeeCount, Over18, StandardHours) %>% # Remove constant features
step_dummy(all_nominal_predictors()) %>% # Convert categorical to dummies
step_zv(all_predictors()) %>% # Remove zero variance predictors
step_normalize(all_numeric_predictors()) # Normalize numeric features
# Step 4: Prepare the training and testing data
prepped_data <- prep(attrition_recipe, training = attrition_train)
train_data <- bake(prepped_data, new_data = NULL)
test_data <- bake(prepped_data, new_data = attrition_test)
# Convert data to H2O format
train_h2o <- as.h2o(train_data)
## | | | 0% | |======================================================================| 100%
test_h2o <- as.h2o(test_data)
## | | | 0% | |======================================================================| 100%
# Define target and predictors
target <- "Attrition"
predictors <- setdiff(names(train_h2o), target)
I recieved the following error please adjust the code to fix this error “Error in automl(max_runtime_secs = 300, seed = 123, nfolds = 5) : could not find function”automl”
I recived the response “The error occurs because the function automl() does not exist in H2O. The correct function is h2o.automl().”
# Step 5: Train the H2O model (AutoML for best model selection)
h2o_automl_model <- h2o.automl(
x = predictors,
y = target,
training_frame = train_h2o,
max_models = 10,
seed = 123,
stopping_metric = "AUC"
)
## | | | 0% | |== | 3%
## 21:39:42.597: AutoML: XGBoost is not available; skipping it. | |========== | 15% | |================ | 24% | |================================= | 47% | |======================================================================| 100%
# View the leaderboard
print(h2o_automl_model@leaderboard)
## model_id auc logloss
## 1 StackedEnsemble_BestOfFamily_1_AutoML_1_20250506_213942 0.8267276 0.3264250
## 2 GLM_1_AutoML_1_20250506_213942 0.8249353 0.3305197
## 3 StackedEnsemble_AllModels_1_AutoML_1_20250506_213942 0.8186140 0.3281250
## 4 GBM_1_AutoML_1_20250506_213942 0.7903828 0.3574247
## 5 GBM_2_AutoML_1_20250506_213942 0.7841662 0.3588757
## 6 GBM_grid_1_AutoML_1_20250506_213942_model_1 0.7805682 0.3593458
## aucpr mean_per_class_error rmse mse
## 1 0.6229002 0.2344409 0.3069755 0.09423394
## 2 0.6115539 0.2608718 0.3097773 0.09596200
## 3 0.6087349 0.2603647 0.3085749 0.09521849
## 4 0.5335186 0.3051611 0.3264897 0.10659551
## 5 0.5238853 0.2921107 0.3247969 0.10549304
## 6 0.5125909 0.2988130 0.3267623 0.10677362
##
## [12 rows x 7 columns]
# Best model
best_model <- h2o_automl_model@leader
# Step 6: Predict on test set
h2o_predictions <- h2o.predict(best_model, test_h2o)
## | | | 0% | |======================================================================| 100%
# View predictions
head(h2o_predictions)
## predict No Yes
## 1 No 0.9713438 0.028656247
## 2 No 0.9076311 0.092368926
## 3 No 0.9397981 0.060201878
## 4 No 0.9505561 0.049443921
## 5 Yes 0.7018224 0.298177635
## 6 No 0.9981058 0.001894184
# Step 7: Predict on new data (optional)
# Example using the first 5 rows from test data
new_data_h2o <- as.h2o(test_data[1:5, ])
## | | | 0% | |======================================================================| 100%
new_data_predictions <- h2o.predict(best_model, new_data_h2o)
## | | | 0% | |======================================================================| 100%
print(new_data_predictions)
## predict No Yes
## 1 No 0.9713438 0.02865625
## 2 No 0.9076311 0.09236893
## 3 No 0.9397981 0.06020188
## 4 No 0.9505561 0.04944392
## 5 Yes 0.7018224 0.29817763
##
## [5 rows x 3 columns]
# Shutdown H2O (optional, after all processes are complete)
h2o.shutdown(prompt = FALSE)