Import the cleaned data from Module 7.
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: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(tidyverse)
## Warning: package 'ggplot2' was built under R version 4.3.3
## ── 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() ──
## ✖ lubridate::day() masks h2o::day()
## ✖ dplyr::filter() masks stats::filter()
## ✖ lubridate::hour() masks h2o::hour()
## ✖ dplyr::lag() masks stats::lag()
## ✖ lubridate::month() masks h2o::month()
## ✖ lubridate::week() masks h2o::week()
## ✖ lubridate::year() masks h2o::year()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tidymodels)
## Warning: package 'tidymodels' was built under R version 4.3.3
## ── Attaching packages ────────────────────────────────────── tidymodels 1.2.0 ──
## ✔ broom 1.0.5 ✔ 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.1.0
## Warning: package 'dials' was built under R version 4.3.3
## Warning: package 'infer' was built under R version 4.3.3
## Warning: package 'modeldata' was built under R version 4.3.3
## Warning: package 'parsnip' was built under R version 4.3.3
## Warning: package 'recipes' was built under R version 4.3.3
## Warning: package 'rsample' was built under R version 4.3.3
## Warning: package 'tune' was built under R version 4.3.3
## Warning: package 'workflows' was built under R version 4.3.3
## Warning: package 'workflowsets' was built under R version 4.3.3
## Warning: package 'yardstick' was built under R version 4.3.3
## ── 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()
## • Learn how to get started at https://www.tidymodels.org/start/
library(tidyquant)
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
##
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
##
## ######################### Warning from 'xts' package ##########################
## # #
## # The dplyr lag() function breaks how base R's lag() function is supposed to #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or #
## # source() into this session won't work correctly. #
## # #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop #
## # dplyr from breaking base R's lag() function. #
## # #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. #
## # #
## ###############################################################################
##
## Attaching package: 'xts'
##
## The following objects are masked from 'package:dplyr':
##
## first, last
##
##
## Attaching package: 'PerformanceAnalytics'
##
## The following object is masked from 'package:graphics':
##
## legend
##
## Loading required package: quantmod
## Loading required package: TTR
##
## Attaching package: 'TTR'
##
## The following object is masked from 'package:dials':
##
## momentum
##
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
data <- read_csv("../00_data/data_wrangled/data_clean_apply.csv") %>%
# h2o requires all variables to be either numeric or factors
mutate(across(where(is.character), factor))
## New names:
## Rows: 501 Columns: 10
## ── Column specification
## ──────────────────────────────────────────────────────── Delimiter: "," chr
## (1): still_there dbl (8): ...1, fyear, co_per_rol, departure_code,
## ceo_dismissal, tenure_no_... date (1): leftofc
## ℹ 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.
## • `` -> `...1`
set.seed(1234)
data_split <- initial_split(data, strata = "ceo_dismissal")
train_tbl <- training(data_split)
test_tbl <- testing(data_split)
recipe_obj <- recipe(ceo_dismissal ~ ., data = train_tbl) %>%
# Remove zero variance variables
step_zv(all_predictors())
# Initialize h2o
h2o.init()
## Connection successful!
##
## R is connected to the H2O cluster:
## H2O cluster uptime: 4 minutes 47 seconds
## 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 1 day
## H2O cluster name: H2O_started_from_R_nilss_whl202
## H2O cluster total nodes: 1
## H2O cluster total memory: 3.58 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.2 (2023-10-31 ucrt)
## Warning in h2o.clusterInfo():
## Your H2O cluster version is (11 months and 1 day) 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
split.h2o <- h2o.splitFrame(as.h2o(train_tbl), ratio = c(0.85), seed = 2345)
##
|
| | 0%
|
|======================================================================| 100%
train_h2o <- split.h2o[[1]]
valid_h2o <- split.h2o[[2]]
test_h2o <- as.h2o(test_tbl)
##
|
| | 0%
|
|======================================================================| 100%
y <- "ceo_dismissal"
x <- setdiff(names(train_tbl), y)
models_h2o <-h2o.automl(
x = x,
y = y,
training_frame = train_h2o,
validation_frame = valid_h2o,
leaderboard_frame = test_h2o,
# max_runtime_secs = 30,
max_models = 10,
exclude_algos = "DeepLearning",
nfolds = 5,
seed = 3456
)
##
|
| | 0%
|
|==================== | 29%
## 21:45:07.905: User specified a validation frame with cross-validation still enabled. Please note that the models will still be validated using cross-validation only, the validation frame will be used to provide purely informative validation metrics on the trained models.
## 21:45:07.908: AutoML: XGBoost is not available; skipping it.
## 21:45:07.910: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:08.82: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:08.212: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:08.413: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:08.583: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:08.747: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:08.944: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:09.73: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:09.704: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
## 21:45:10.43: _response param, We have detected that your response column has only 2 unique values (0/1). If you wish to train a binary model instead of a regression model, convert your target column to categorical before training.
|
|======================================================================| 100%
Examine the output of h2o.automl
models_h2o %>% typeof()
## [1] "S4"
models_h2o %>% slotNames()
## [1] "project_name" "leader" "leaderboard" "event_log"
## [5] "modeling_steps" "training_info"
models_h2o@leaderboard
## model_id rmse
## 1 StackedEnsemble_BestOfFamily_1_AutoML_2_20241121_214507 0.01441041
## 2 StackedEnsemble_AllModels_1_AutoML_2_20241121_214507 0.01514312
## 3 GLM_1_AutoML_2_20241121_214507 0.03040661
## 4 GBM_5_AutoML_2_20241121_214507 0.04065315
## 5 XRT_1_AutoML_2_20241121_214507 0.05639046
## 6 GBM_grid_1_AutoML_2_20241121_214507_model_2 0.07468147
## mse mae rmsle mean_residual_deviance
## 1 0.0002076599 0.004475705 0.01359838 0.0002076599
## 2 0.0002293142 0.004444123 0.01437640 0.0002293142
## 3 0.0009245619 0.008272408 0.03240156 0.0009245619
## 4 0.0016526786 0.005553645 0.02251009 0.0016526786
## 5 0.0031798839 0.008092820 0.03199365 0.0031798839
## 6 0.0055773224 0.012960909 0.04623959 0.0055773224
##
## [12 rows x 6 columns]
models_h2o@leader
## Model Details:
## ==============
##
## H2ORegressionModel: stackedensemble
## Model ID: StackedEnsemble_BestOfFamily_1_AutoML_2_20241121_214507
## Model Summary for Stacked Ensemble:
## key value
## 1 Stacking strategy cross_validation
## 2 Number of base models (used / total) 3/4
## 3 # GBM base models (used / total) 1/1
## 4 # GLM base models (used / total) 1/1
## 5 # DRF base models (used / total) 1/2
## 6 Metalearner algorithm GLM
## 7 Metalearner fold assignment scheme Random
## 8 Metalearner nfolds 5
## 9 Metalearner fold_column NA
## 10 Custom metalearner hyperparameters None
##
##
## H2ORegressionMetrics: stackedensemble
## ** Reported on training data. **
##
## MSE: 0.0004211641
## RMSE: 0.02052228
## MAE: 0.004113045
## RMSLE: 0.01246042
## Mean Residual Deviance : 0.0004211641
##
##
## H2ORegressionMetrics: stackedensemble
## ** Reported on validation data. **
##
## MSE: 1.486865e-05
## RMSE: 0.003855989
## MAE: 0.002471622
## RMSLE: 0.003880091
## Mean Residual Deviance : 1.486865e-05
##
##
## H2ORegressionMetrics: stackedensemble
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
##
## MSE: 0.000937946
## RMSE: 0.0306259
## MAE: 0.006336358
## RMSLE: 0.02448172
## Mean Residual Deviance : 0.000937946
##
##
## Cross-Validation Metrics Summary:
## mean sd cv_1_valid cv_2_valid cv_3_valid
## mae 0.005820 0.003339 0.006603 0.003980 0.011231
## mean_residual_deviance 0.000705 0.001228 0.000607 0.000022 0.002854
## mse 0.000705 0.001228 0.000607 0.000022 0.002854
## null_deviance 0.399707 0.541925 0.993402 0.005376 0.993308
## r2 -Inf NA 0.963549 -Inf 0.791629
## residual_deviance 0.049046 0.088717 0.035833 0.001777 0.205477
## rmse 0.018296 0.021501 0.024644 0.004655 0.053421
## rmsle 0.015447 0.016590 0.022048 0.004640 0.041792
## cv_4_valid cv_5_valid
## mae 0.002682 0.004603
## mean_residual_deviance 0.000012 0.000028
## mse 0.000012 0.000028
## null_deviance 0.004083 0.002364
## r2 -Inf -Inf
## residual_deviance 0.000844 0.001301
## rmse 0.003497 0.005261
## rmsle 0.003506 0.005250
best_model <- models_h2o@leader
best_model
## Model Details:
## ==============
##
## H2ORegressionModel: stackedensemble
## Model ID: StackedEnsemble_BestOfFamily_1_AutoML_2_20241121_214507
## Model Summary for Stacked Ensemble:
## key value
## 1 Stacking strategy cross_validation
## 2 Number of base models (used / total) 3/4
## 3 # GBM base models (used / total) 1/1
## 4 # GLM base models (used / total) 1/1
## 5 # DRF base models (used / total) 1/2
## 6 Metalearner algorithm GLM
## 7 Metalearner fold assignment scheme Random
## 8 Metalearner nfolds 5
## 9 Metalearner fold_column NA
## 10 Custom metalearner hyperparameters None
##
##
## H2ORegressionMetrics: stackedensemble
## ** Reported on training data. **
##
## MSE: 0.0004211641
## RMSE: 0.02052228
## MAE: 0.004113045
## RMSLE: 0.01246042
## Mean Residual Deviance : 0.0004211641
##
##
## H2ORegressionMetrics: stackedensemble
## ** Reported on validation data. **
##
## MSE: 1.486865e-05
## RMSE: 0.003855989
## MAE: 0.002471622
## RMSLE: 0.003880091
## Mean Residual Deviance : 1.486865e-05
##
##
## H2ORegressionMetrics: stackedensemble
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
##
## MSE: 0.000937946
## RMSE: 0.0306259
## MAE: 0.006336358
## RMSLE: 0.02448172
## Mean Residual Deviance : 0.000937946
##
##
## Cross-Validation Metrics Summary:
## mean sd cv_1_valid cv_2_valid cv_3_valid
## mae 0.005820 0.003339 0.006603 0.003980 0.011231
## mean_residual_deviance 0.000705 0.001228 0.000607 0.000022 0.002854
## mse 0.000705 0.001228 0.000607 0.000022 0.002854
## null_deviance 0.399707 0.541925 0.993402 0.005376 0.993308
## r2 -Inf NA 0.963549 -Inf 0.791629
## residual_deviance 0.049046 0.088717 0.035833 0.001777 0.205477
## rmse 0.018296 0.021501 0.024644 0.004655 0.053421
## rmsle 0.015447 0.016590 0.022048 0.004640 0.041792
## cv_4_valid cv_5_valid
## mae 0.002682 0.004603
## mean_residual_deviance 0.000012 0.000028
## mse 0.000012 0.000028
## null_deviance 0.004083 0.002364
## r2 -Inf -Inf
## residual_deviance 0.000844 0.001301
## rmse 0.003497 0.005261
## rmsle 0.003506 0.005250
#?h2o.getModel
#?h2o.saveModel
#?h2o.loadModel
#h2o.getModel(GBM_3_AutoML_1_20241121_121503) %>%
# h2o.saveModel("h2o_models/")
#best_model <- h2o.loadModel(GBM_3_AutoML_1_20241121_121503)
predictions <- h2o.predict(best_model, newdata = test_h2o)
##
|
| | 0%
|
|======================================================================| 100%
## Warning in doTryCatch(return(expr), name, parentenv, handler): Test/Validation
## dataset column 'still_there' has levels not trained on: ["12/8//2020"]
predictions_tbl <- predictions %>%
as_tibble()
# predictions_tbl %>%
# bind_cols(test_tbl)
?h2o.performance
## starting httpd help server ... done
performance_h2o <- h2o.performance(best_model, newdata = as.h2o(test_tbl))
##
|
| | 0%
|
|======================================================================| 100%
typeof(performance_h2o)
## [1] "S4"
slotNames(performance_h2o)
## [1] "algorithm" "on_train" "on_valid" "on_xval" "metrics"
performance_h2o@metrics
## $model
## $model$`__meta`
## $model$`__meta`$schema_version
## [1] 3
##
## $model$`__meta`$schema_name
## [1] "ModelKeyV3"
##
## $model$`__meta`$schema_type
## [1] "Key<Model>"
##
##
## $model$name
## [1] "StackedEnsemble_BestOfFamily_1_AutoML_2_20241121_214507"
##
## $model$type
## [1] "Key<Model>"
##
## $model$URL
## [1] "/3/Models/StackedEnsemble_BestOfFamily_1_AutoML_2_20241121_214507"
##
##
## $model_checksum
## [1] "-5763700579230764800"
##
## $frame
## $frame$name
## [1] "test_tbl_sid_99ab_125"
##
##
## $frame_checksum
## [1] "-1981703159836798916"
##
## $description
## NULL
##
## $scoring_time
## [1] 1.732244e+12
##
## $predictions
## NULL
##
## $MSE
## [1] 0.0002076599
##
## $RMSE
## [1] 0.01441041
##
## $nobs
## [1] 126
##
## $custom_metric_name
## NULL
##
## $custom_metric_value
## [1] 0
##
## $r2
## [1] 0.9867064
##
## $mean_residual_deviance
## [1] 0.0002076599
##
## $mae
## [1] 0.004475705
##
## $rmsle
## [1] 0.01359838
##
## $residual_deviance
## [1] 0.02616515
##
## $null_deviance
## [1] 1.98034
##
## $AIC
## [1] -700.8582
##
## $loglikelihood
## [1] 0
##
## $null_degrees_of_freedom
## [1] 125
##
## $residual_degrees_of_freedom
## [1] 122
h2o.auc(performance_h2o)
## NULL
h2o.confusionMatrix(performance_h2o)
## Warning in .local(object, ...): No Confusion Matrices for H2ORegressionMetrics
## NULL