library(tidyverse)

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
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, …
# If data is sensitive:
attrition_raw_tbl %>%
    slice(0) %>%
    glimpse()
## Rows: 0
## Columns: 35
## $ Age                      <dbl> 
## $ Attrition                <chr> 
## $ BusinessTravel           <chr> 
## $ DailyRate                <dbl> 
## $ Department               <chr> 
## $ DistanceFromHome         <dbl> 
## $ Education                <dbl> 
## $ EducationField           <chr> 
## $ EmployeeCount            <dbl> 
## $ EmployeeNumber           <dbl> 
## $ EnvironmentSatisfaction  <dbl> 
## $ Gender                   <chr> 
## $ HourlyRate               <dbl> 
## $ JobInvolvement           <dbl> 
## $ JobLevel                 <dbl> 
## $ JobRole                  <chr> 
## $ JobSatisfaction          <dbl> 
## $ MaritalStatus            <chr> 
## $ MonthlyIncome            <dbl> 
## $ MonthlyRate              <dbl> 
## $ NumCompaniesWorked       <dbl> 
## $ Over18                   <chr> 
## $ OverTime                 <chr> 
## $ PercentSalaryHike        <dbl> 
## $ PerformanceRating        <dbl> 
## $ RelationshipSatisfaction <dbl> 
## $ StandardHours            <dbl> 
## $ StockOptionLevel         <dbl> 
## $ TotalWorkingYears        <dbl> 
## $ TrainingTimesLastYear    <dbl> 
## $ WorkLifeBalance          <dbl> 
## $ YearsAtCompany           <dbl> 
## $ YearsInCurrentRole       <dbl> 
## $ YearsSinceLastPromotion  <dbl> 
## $ YearsWithCurrManager     <dbl>

Please write R code to create a predictive model that predicts the probability of attrition.

# Load necessary libraries
library(tidyverse)
library(caret)
## Loading required package: lattice
## 
## Attaching package: 'caret'
## The following object is masked from 'package:purrr':
## 
##     lift
# 1. Clean and preprocess the data
attrition_clean_tbl <- attrition_raw_tbl %>%
  select(-EmployeeCount, -Over18, -StandardHours, -EmployeeNumber) %>% # Remove constant or ID columns
  mutate(Attrition = as.factor(Attrition)) %>%
  mutate_if(is.character, as.factor) # Convert character columns to factors

# 2. Split the data into training and testing sets
set.seed(123)
split <- createDataPartition(attrition_clean_tbl$Attrition, p = 0.8, list = FALSE)
train_tbl <- attrition_clean_tbl[split, ]
test_tbl  <- attrition_clean_tbl[-split, ]

# 3. Train a logistic regression model
model_logit <- train(
  Attrition ~ ., 
  data = train_tbl,
  method = "glm", 
  family = "binomial",
  trControl = trainControl(method = "cv", number = 5)
)

# 4. Evaluate model performance
pred_prob <- predict(model_logit, newdata = test_tbl, type = "prob")
pred_class <- predict(model_logit, newdata = test_tbl)

conf_matrix <- confusionMatrix(pred_class, test_tbl$Attrition)
print(conf_matrix)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  No Yes
##        No  236  30
##        Yes  10  17
##                                           
##                Accuracy : 0.8635          
##                  95% CI : (0.8188, 0.9006)
##     No Information Rate : 0.8396          
##     P-Value [Acc > NIR] : 0.149962        
##                                           
##                   Kappa : 0.3878          
##                                           
##  Mcnemar's Test P-Value : 0.002663        
##                                           
##             Sensitivity : 0.9593          
##             Specificity : 0.3617          
##          Pos Pred Value : 0.8872          
##          Neg Pred Value : 0.6296          
##              Prevalence : 0.8396          
##          Detection Rate : 0.8055          
##    Detection Prevalence : 0.9078          
##       Balanced Accuracy : 0.6605          
##                                           
##        'Positive' Class : No              
## 
# 5. Add predicted probabilities to the test set
results <- test_tbl %>%
  mutate(Predicted_Attrition_Prob = pred_prob$Yes)

# View top predictions
head(results %>% select(Attrition, Predicted_Attrition_Prob))
## # A tibble: 6 × 2
##   Attrition Predicted_Attrition_Prob
##   <fct>                        <dbl>
## 1 No                        0.0356  
## 2 No                        0.0688  
## 3 No                        0.0726  
## 4 No                        0.0384  
## 5 No                        0.0860  
## 6 No                        0.000366

Prompt 2:

Please update the code to use tidymodels instead of caret and to use the h2o model instead of glmnet.

# Load libraries
library(tidymodels)
## ── 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
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ scales::discard()        masks purrr::discard()
## ✖ dplyr::filter()          masks stats::filter()
## ✖ recipes::fixed()         masks stringr::fixed()
## ✖ dplyr::lag()             masks stats::lag()
## ✖ caret::lift()            masks purrr::lift()
## ✖ yardstick::precision()   masks caret::precision()
## ✖ yardstick::recall()      masks caret::recall()
## ✖ yardstick::sensitivity() masks caret::sensitivity()
## ✖ yardstick::spec()        masks readr::spec()
## ✖ yardstick::specificity() masks caret::specificity()
## ✖ 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(dplyr)

# Initialize H2O
h2o.init()
##  Connection successful!
## 
## R is connected to the H2O cluster: 
##     H2O cluster uptime:         13 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:    1 year, 4 months and 15 days 
##     H2O cluster name:           H2O_started_from_R_katiegoy_fyb567 
##     H2O cluster total nodes:    1 
##     H2O cluster total memory:   1.30 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.1 (2024-06-14)
## Warning in h2o.clusterInfo(): 
## Your H2O cluster version is (1 year, 4 months and 15 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
# --- Data Preprocessing ---
# Remove unnecessary columns and convert types
attrition_clean_tbl <- attrition_raw_tbl %>%
  select(-EmployeeCount, -Over18, -StandardHours, -EmployeeNumber) %>%
  mutate(Attrition = as.factor(Attrition)) %>%
  mutate(across(where(is.character), as.factor))

# Split data
set.seed(123)
data_split <- initial_split(attrition_clean_tbl, prop = 0.8, strata = Attrition)
train_data <- training(data_split)
test_data  <- testing(data_split)

# Ensure Attrition is a factor (important for classification)
train_data <- train_data %>% mutate(Attrition = as.factor(Attrition))
test_data  <- test_data %>% mutate(Attrition = as.factor(Attrition))

# Convert to H2O frames
train_h2o <- as.h2o(train_data)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
test_h2o  <- as.h2o(test_data)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
# Define response and predictors
y <- "Attrition"
x <- setdiff(names(train_data), y)

# Fit H2O GLM model (logistic regression)
h2o_model <- h2o.glm(
  x = x,
  y = y,
  training_frame = train_h2o,
  family = "binomial",
  seed = 123
)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
# Predict on test set
predictions <- h2o.predict(h2o_model, test_h2o)
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%
print(predictions)  # Check output columns
##   predict        No          Yes
## 1      No 0.9743353 0.0256647194
## 2      No 0.9278288 0.0721712366
## 3      No 0.9325557 0.0674442703
## 4      No 0.9549825 0.0450175293
## 5      No 0.9225257 0.0774742801
## 6      No 0.9994963 0.0005037438
## 
## [295 rows x 3 columns]
# Convert predictions to tibble and merge with actual Attrition
pred_df <- as_tibble(predictions) %>%
  bind_cols(test_data %>% select(Attrition)) %>%
  rename(prob_attrition = Yes)

# Evaluate
conf_mat <- conf_mat(pred_df, truth = Attrition, estimate = predict)
print(conf_mat)
##           Truth
## Prediction  No Yes
##        No  225  20
##        Yes  22  28
# View sample predictions
pred_df %>% select(Attrition, predict, prob_attrition) %>% head()
## # A tibble: 6 × 3
##   Attrition predict prob_attrition
##   <fct>     <fct>            <dbl>
## 1 No        No            0.0257  
## 2 No        No            0.0722  
## 3 No        No            0.0674  
## 4 No        No            0.0450  
## 5 No        No            0.0775  
## 6 No        No            0.000504