# for Core packages
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.4     ✔ purrr   1.0.2
## ✔ tibble  3.2.1     ✔ dplyr   1.1.4
## ✔ tidyr   1.3.0     ✔ stringr 1.5.0
## ✔ readr   2.1.3     ✔ forcats 1.0.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
# for financial analysis
library(tidyquant)
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## 
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## 
## 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
## 
## 
## 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)

# for h2o
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.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.4 
## ✔ modeldata    1.3.0      ✔ workflowsets 1.0.1 
## ✔ parsnip      1.2.0      ✔ yardstick    1.2.0 
## ✔ recipes      1.0.10     
## ── 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()
## • Search for functions across packages at https://www.tidymodels.org/find/
library(umap)

Goal: Apply Matt Dancho’s tutorial to state unemployment initial claims of New England states.

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

set.seed(1234)

data_split <- initial_split(claims_tbl, 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

# Initialize h20
h2o.init()
##  Connection successful!
## 
## R is connected to the H2O cluster: 
##     H2O cluster uptime:         11 days 21 hours 
##     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_stephenmorris_fhp551 
##     H2O cluster total nodes:    1 
##     H2O cluster total memory:   0.91 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.2.2 (2022-10-31)
## 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
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,
    nfolds  = 5,
    seed = 3456
)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |==                                                                    |   3%
## 13:29:45.336: 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.
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |======================================================================| 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         XGBoost_grid_1_AutoML_17_20240507_132945_model_4 1911.023 3652009
## 2 StackedEnsemble_BestOfFamily_4_AutoML_17_20240507_132945 1911.285 3653009
## 3    StackedEnsemble_AllModels_3_AutoML_17_20240507_132945 1968.134 3873552
## 4    StackedEnsemble_AllModels_2_AutoML_17_20240507_132945 1998.728 3994914
## 5 StackedEnsemble_BestOfFamily_3_AutoML_17_20240507_132945 2054.125 4219429
## 6         XGBoost_grid_1_AutoML_17_20240507_132945_model_3 2056.233 4228095
##        mae rmsle mean_residual_deviance
## 1 797.4975   NaN                3652009
## 2 806.7797   NaN                3653009
## 3 728.6873   NaN                3873552
## 4 727.3975   NaN                3994914
## 5 791.7993   NaN                4219429
## 6 782.6758   NaN                4228095
## 
## [33 rows x 6 columns]
best_model <- models_h2o@leader
best_model
## Model Details:
## ==============
## 
## H2ORegressionModel: xgboost
## Model ID:  XGBoost_grid_1_AutoML_17_20240507_132945_model_4 
## Model Summary: 
##   number_of_trees
## 1              32
## 
## 
## H2ORegressionMetrics: xgboost
## ** Reported on training data. **
## 
## MSE:  2601961
## RMSE:  1613.059
## MAE:  695.9029
## RMSLE:  NaN
## Mean Residual Deviance :  2601961
## 
## 
## H2ORegressionMetrics: xgboost
## ** Reported on validation data. **
## 
## MSE:  4104847
## RMSE:  2026.042
## MAE:  755.4072
## RMSLE:  0.3449595
## Mean Residual Deviance :  4104847
## 
## 
## H2ORegressionMetrics: xgboost
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
## 
## MSE:  5786876
## RMSE:  2405.593
## MAE:  781.502
## RMSLE:  NaN
## Mean Residual Deviance :  5786876
## 
## 
## Cross-Validation Metrics Summary: 
##                                  mean             sd      cv_1_valid
## mae                        781.501950      49.238117      852.659600
## mean_residual_deviance 5786875.500000 6396435.500000 17133578.000000
## mse                    5786875.500000 6396435.500000 17133578.000000
## r2                           0.762278       0.109697        0.588625
## residual_deviance      5786875.500000 6396435.500000 17133578.000000
## rmse                      2188.181200    1117.329100     4139.273000
## rmsle                        0.390123       0.000000              NA
##                            cv_2_valid     cv_3_valid     cv_4_valid
## mae                        809.418640     732.600300     746.296300
## mean_residual_deviance 3689546.200000 2175749.000000 2080075.000000
## mse                    3689546.200000 2175749.000000 2080075.000000
## r2                           0.837456       0.840175       0.827557
## residual_deviance      3689546.200000 2175749.000000 2080075.000000
## rmse                      1920.819200    1475.042100    1442.246500
## rmsle                        0.390123             NA             NA
##                            cv_5_valid
## mae                        766.534850
## mean_residual_deviance 3855429.200000
## mse                    3855429.200000
## r2                           0.717579
## residual_deviance      3855429.200000
## rmse                      1963.524700
## rmsle                              NA

Save and Load

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

#best_model <- h2o.loadModel("   XGBoost_grid_1_AutoML_15_20240507_132529_model_4")

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,766 × 4
##    predict symbol      date       claims
##      <dbl> <fct>       <date>      <int>
##  1   5544. Connecticut 1989-01-14   6503
##  2   4456. Connecticut 1989-01-28   4663
##  3   4030. Connecticut 1989-04-08   3610
##  4   4030. Connecticut 1989-04-29   3191
##  5   4030. Connecticut 1989-05-06   3224
##  6   4847. Connecticut 1989-08-12   3704
##  7   4847. Connecticut 1989-08-26   3373
##  8   4847. Connecticut 1989-09-02   2902
##  9   4847. Connecticut 1989-09-09   2856
## 10   4847. Connecticut 1989-09-16   3025
## # ℹ 2,756 more rows

Evaluate model

?h2o.performance
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] "XGBoost_grid_1_AutoML_17_20240507_132945_model_4"
## 
## $model$type
## [1] "Key<Model>"
## 
## $model$URL
## [1] "/3/Models/XGBoost_grid_1_AutoML_17_20240507_132945_model_4"
## 
## 
## $model_checksum
## [1] "8452636483024181248"
## 
## $frame
## $frame$name
## [1] "test_tbl_sid_8a9b_3"
## 
## 
## $frame_checksum
## [1] "8320518109852287548"
## 
## $description
## NULL
## 
## $scoring_time
## [1] 1.715103e+12
## 
## $predictions
## NULL
## 
## $MSE
## [1] 3652009
## 
## $RMSE
## [1] 1911.023
## 
## $nobs
## [1] 2766
## 
## $custom_metric_name
## NULL
## 
## $custom_metric_value
## [1] 0
## 
## $r2
## [1] 0.8425054
## 
## $mean_residual_deviance
## [1] 3652009
## 
## $mae
## [1] 797.4975
## 
## $rmsle
## [1] "NaN"
h2o.auc(performance_h2o)
## NULL
h2o.confusionMatrix(performance_h2o)
## Warning in .local(object, ...): No Confusion Matrices for H2ORegressionMetrics
## NULL