# for Core packages
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
# for financial analysis
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
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
# for times series
library(timetk)

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(tidymodels)
## ── Attaching packages ────────────────────────────────────── tidymodels 1.2.0 ──
## ✔ broom        1.0.5      ✔ rsample      1.2.1 
## ✔ dials        1.2.1      ✔ 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.0.10
## Warning: package 'modeldata' was built under R version 4.3.3
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ scales::discard() masks purrr::discard()
## ✖ dplyr::filter()   masks stats::filter()
## ✖ xts::first()      masks dplyr::first()
## ✖ recipes::fixed()  masks stringr::fixed()
## ✖ dplyr::lag()      masks stats::lag()
## ✖ xts::last()       masks dplyr::last()
## ✖ dials::momentum() masks TTR::momentum()
## ✖ yardstick::spec() masks readr::spec()
## ✖ recipes::step()   masks stats::step()
## • Use suppressPackageStartupMessages() to eliminate package startup messages

Goal is to automate building and tuning a classification model to predict state unemployment, using the h2o::h2o.automl.

The following is the replication of Matt Dancho’s tutorial on this page

start_date <- "1989-01-01"

symbols_txt <- c("CTICLAIMS", # Connecticut
                 "MEICLAIMS", # Maine
                 "MAICLAIMS", # Massachusetts
                 "NHICLAIMS", # New Hampshire
                 "RIICLAIMS", # Rhode Island
                 "VTICLAIMS") # Vermont

claims_tbl <- tq_get(symbols_txt, get = "economic.data", from = start_date) %>%
    mutate(symbol = fct_recode(symbol,
                               "Connecticut"   = "CTICLAIMS",
                               "Maine"         = "MEICLAIMS",
                               "Massachusetts" = "MAICLAIMS",
                               "New Hampshire" = "NHICLAIMS",
                               "Rhode Island"  = "RIICLAIMS",
                               "Vermont"       = "VTICLAIMS")) %>%
    rename(claims = price)

Split data

data <- claims_tbl

set.seed(1234)

data_split <- initial_split(data, strata = "claims")
train_tbl <- training(data_split)
test_tbl <- testing(data_split)

Recipes

recipe_obj <- recipe(claims ~ ., data = train_tbl) %>%
    
    # Remove zero variance variables
    step_zv(all_predictors()) 

Model

h2o.init()
##  Connection successful!
## 
## R is connected to the H2O cluster: 
##     H2O cluster uptime:         2 days 4 hours 
##     H2O cluster timezone:       America/New_York 
##     H2O data parsing timezone:  UTC 
##     H2O cluster version:        3.44.0.3 
##     H2O cluster version age:    10 months and 30 days 
##     H2O cluster name:           H2O_started_from_R_kajsabergstrand_fhp551 
##     H2O cluster total nodes:    1 
##     H2O cluster total memory:   1.44 GB 
##     H2O cluster total cores:    4 
##     H2O cluster allowed cores:  4 
##     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)
## Warning in h2o.clusterInfo(): 
## Your H2O cluster version is (10 months and 30 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
split.h2o <- h2o.splitFrame(as.h2o(train_tbl), ratios = 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 <- "claims"
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%
## 19:43:22.79: 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.
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |======================================================================| 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     mse
## 1    StackedEnsemble_AllModels_1_AutoML_18_20241119_194322 1682.939 2832283
## 2 StackedEnsemble_BestOfFamily_1_AutoML_18_20241119_194322 1755.924 3083268
## 3                      XGBoost_2_AutoML_18_20241119_194322 1756.180 3084169
## 4                      XGBoost_1_AutoML_18_20241119_194322 1775.195 3151319
## 5                      XGBoost_3_AutoML_18_20241119_194322 1792.369 3212586
## 6                          GBM_1_AutoML_18_20241119_194322 3111.325 9680342
##         mae rmsle mean_residual_deviance
## 1  675.6157   NaN                2832283
## 2  682.4564   NaN                3083268
## 3  682.4860   NaN                3084169
## 4  690.5329   NaN                3151319
## 5  754.4323   NaN                3212586
## 6 1101.7994   NaN                9680342
## 
## [12 rows x 6 columns]
models_h2o@leader
## Model Details:
## ==============
## 
## H2ORegressionModel: stackedensemble
## Model ID:  StackedEnsemble_AllModels_1_AutoML_18_20241119_194322 
## Model Summary for Stacked Ensemble: 
##                                     key            value
## 1                     Stacking strategy cross_validation
## 2  Number of base models (used / total)             3/10
## 3      # GBM base models (used / total)              0/4
## 4  # XGBoost base models (used / total)              3/3
## 5      # DRF base models (used / total)              0/2
## 6      # GLM base models (used / total)              0/1
## 7                 Metalearner algorithm              GLM
## 8    Metalearner fold assignment scheme           Random
## 9                    Metalearner nfolds                5
## 10              Metalearner fold_column               NA
## 11   Custom metalearner hyperparameters             None
## 
## 
## H2ORegressionMetrics: stackedensemble
## ** Reported on training data. **
## 
## MSE:  1505490
## RMSE:  1226.984
## MAE:  554.2382
## RMSLE:  NaN
## Mean Residual Deviance :  1505490
## 
## 
## H2ORegressionMetrics: stackedensemble
## ** Reported on validation data. **
## 
## MSE:  2212217
## RMSE:  1487.352
## MAE:  630.5789
## RMSLE:  NaN
## Mean Residual Deviance :  2212217
## 
## 
## H2ORegressionMetrics: stackedensemble
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
## 
## MSE:  4246594
## RMSE:  2060.727
## MAE:  693.0651
## RMSLE:  NaN
## Mean Residual Deviance :  4246594
## 
## 
## Cross-Validation Metrics Summary: 
##                                      mean                 sd         cv_1_valid
## mae                            692.431200          53.515842         751.971070
## mean_residual_deviance     3994871.800000     4437048.000000    11890053.000000
## mse                        3994871.800000     4437048.000000    11890053.000000
## null_deviance          34643366000.000000 18328420400.000000 66062455000.000000
## r2                               0.858098           0.075267           0.738124
## residual_deviance       5759607300.000000  6479182800.000000 17300027400.000000
## rmse                          1818.641800         926.966550        3448.195600
## rmsle                                  NA           0.000000                 NA
##                                cv_2_valid         cv_3_valid         cv_4_valid
## mae                            677.155900         675.368960         619.600200
## mean_residual_deviance     2210457.200000     2146556.800000     1259065.000000
## mse                        2210457.200000     2146556.800000     1259065.000000
## null_deviance          35163509000.000000 23613292500.000000 27020349400.000000
## r2                               0.909278           0.865259           0.931908
## residual_deviance       3189689860.000000  3181197060.000000  1836975870.000000
## rmse                          1486.760700        1465.113200        1122.080700
## rmsle                                  NA                 NA                 NA
##                                cv_5_valid
## mae                            738.059900
## mean_residual_deviance     2468226.000000
## mse                        2468226.000000
## null_deviance          21357226000.000000
## r2                               0.845924
## residual_deviance       3290145280.000000
## rmse                          1571.058800
## rmsle                                  NA

Save and Load

?h2o.getModel
?h2o.saveModel
?h2o.loadModel

h2o.getModel("StackedEnsemble_BestOfFamily_1_AutoML_15_20241119_192822") %>%
    h2o.saveModel("h20_models1/")
## [1] "/Users/kajsabergstrand/Desktop/PSU_DAT3100/11_module13/h20_models1/StackedEnsemble_BestOfFamily_1_AutoML_15_20241119_192822"
best_model <- h2o.loadModel("h20_models1/StackedEnsemble_BestOfFamily_1_AutoML_15_20241119_192822")

Make predictions

predictions <- h2o.predict(best_model, newdata = test_h2o)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |======================================================================| 100%
predictions_tbl <- predictions %>%
    as_tibble()

predictions_tbl %>%
    bind_cols(test_tbl)
## # A tibble: 2,808 × 4
##    predict symbol      date       claims
##      <dbl> <fct>       <date>      <int>
##  1   5427. Connecticut 1989-01-14   6503
##  2   4685. Connecticut 1989-01-28   4663
##  3   3443. Connecticut 1989-04-08   3610
##  4   3351. Connecticut 1989-04-29   3191
##  5   3351. Connecticut 1989-05-06   3224
##  6   4743. Connecticut 1989-07-01   5232
##  7   4356. Connecticut 1989-08-26   3373
##  8   3789. Connecticut 1989-09-02   2902
##  9   3789. Connecticut 1989-09-09   2856
## 10   3300. Connecticut 1989-09-16   3025
## # ℹ 2,798 more rows

Evaluate model

performance_h2o <- h2o.performance(best_model, newdata = test_h2o)
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_15_20241119_192822"
## 
## $model$type
## [1] "Key<Model>"
## 
## $model$URL
## [1] "/3/Models/StackedEnsemble_BestOfFamily_1_AutoML_15_20241119_192822"
## 
## 
## $model_checksum
## [1] "2488863327570913280"
## 
## $frame
## $frame$name
## [1] "test_tbl_sid_8f97_3"
## 
## 
## $frame_checksum
## [1] "4281387059679466868"
## 
## $description
## NULL
## 
## $scoring_time
## [1] 1.732063e+12
## 
## $predictions
## NULL
## 
## $MSE
## [1] 3648706
## 
## $RMSE
## [1] 1910.159
## 
## $nobs
## [1] 2808
## 
## $custom_metric_name
## NULL
## 
## $custom_metric_value
## [1] 0
## 
## $r2
## [1] 0.837092
## 
## $mean_residual_deviance
## [1] 3648706
## 
## $mae
## [1] 757.018
## 
## $rmsle
## [1] "NaN"
## 
## $residual_deviance
## [1] 10245566283
## 
## $null_deviance
## [1] 62892676851
## 
## $AIC
## [1] 50403.31
## 
## $loglikelihood
## [1] 0
## 
## $null_degrees_of_freedom
## [1] 2807
## 
## $residual_degrees_of_freedom
## [1] 2806
h2o.auc(performance_h2o)
## NULL
#h2o.confusionMatrix(performance_h2o)
#h2o.metric(performance_h2o)