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.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.5.0     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ 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.2
## ── 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.3
## ✔ modeldata    1.3.0     ✔ workflowsets 1.0.1
## ✔ parsnip      1.1.1     ✔ yardstick    1.3.0
## ✔ recipes      1.0.8
## Warning: package 'dials' was built under R version 4.3.2
## Warning: package 'scales' was built under R version 4.3.2
## Warning: package 'infer' was built under R version 4.3.2
## Warning: package 'modeldata' was built under R version 4.3.2
## Warning: package 'parsnip' was built under R version 4.3.2
## Warning: package 'tune' was built under R version 4.3.2
## Warning: package 'workflows' was built under R version 4.3.2
## Warning: package 'workflowsets' was built under R version 4.3.2
## Warning: package 'yardstick' was built under R version 4.3.2
## ── 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()
## • Dig deeper into tidy modeling with R at https://www.tmwr.org
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
library(umap)
## Warning: package 'umap' was built under R version 4.3.3
library(timetk)
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)
set.seed(1234)

data_split <- initial_split(claims_tbl, strata = "claims")
train_tbl <- training(data_split)
test_tbl <- testing(data_split)
recipe_obj <- recipe(claims ~ ., 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:         24 minutes 7 seconds 
##     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_Jstan_fhp551 
##     H2O cluster total nodes:    1 
##     H2O cluster total memory:   1.79 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.1 (2023-06-16 ucrt)
## 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%
## 00:59:56.501: 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.
## 00:59:56.501: AutoML: XGBoost is not available; skipping it.
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |=====================================                                 |  54%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |======================================================================| 100%
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_3_AutoML_15_20240507_05956 2786.735 7765894
## 2 StackedEnsemble_BestOfFamily_4_AutoML_15_20240507_05956 2865.915 8213469
## 3             GBM_grid_1_AutoML_15_20240507_05956_model_1 2890.723 8356278
## 4             GBM_grid_1_AutoML_15_20240507_05956_model_7 2970.755 8825383
## 5    StackedEnsemble_AllModels_1_AutoML_15_20240507_05956 3043.806 9264756
## 6 StackedEnsemble_BestOfFamily_2_AutoML_15_20240507_05956 3047.181 9285311
##         mae rmsle mean_residual_deviance
## 1 1005.3676   NaN                7765894
## 2 1042.8428   NaN                8213469
## 3  954.5562   NaN                8356278
## 4 1048.8784   NaN                8825383
## 5 1102.8636   NaN                9264756
## 6 1096.2601   NaN                9285311
## 
## [28 rows x 6 columns]
models_h2o@leader
## Model Details:
## ==============
## 
## H2ORegressionModel: stackedensemble
## Model ID:  StackedEnsemble_AllModels_3_AutoML_15_20240507_05956 
## Model Summary for Stacked Ensemble: 
##                                          key            value
## 1                          Stacking strategy cross_validation
## 2       Number of base models (used / total)             2/21
## 3           # GBM base models (used / total)             2/14
## 4  # DeepLearning base models (used / total)              0/4
## 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:  6541424
## RMSE:  2557.621
## MAE:  922.1452
## RMSLE:  NaN
## Mean Residual Deviance :  6541424
## 
## 
## H2ORegressionMetrics: stackedensemble
## ** Reported on validation data. **
## 
## MSE:  11245300
## RMSE:  3353.401
## MAE:  951.84
## RMSLE:  NaN
## Mean Residual Deviance :  11245300
## 
## 
## H2ORegressionMetrics: stackedensemble
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
## 
## MSE:  8037346
## RMSE:  2835.021
## MAE:  962.8897
## RMSLE:  NaN
## Mean Residual Deviance :  8037346
## 
## 
## Cross-Validation Metrics Summary: 
##                                      mean                 sd         cv_1_valid
## mae                            939.484560         125.077545         768.723100
## mean_residual_deviance     7853581.500000     9010445.000000     1970762.600000
## mse                        7853581.500000     9010445.000000     1970762.600000
## null_deviance          29319390000.000000 18405093000.000000 15692573000.000000
## r2                               0.694418           0.151424           0.818108
## residual_deviance      11174962000.000000 12962821000.000000  2831986000.000000
## rmse                          2509.134000        1395.451500        1403.838500
## rmsle                                  NA           0.000000                 NA
##                                cv_2_valid         cv_3_valid         cv_4_valid
## mae                           1064.648900         858.143200        1042.189500
## mean_residual_deviance     7292892.500000     3005789.000000    23563594.000000
## mse                        7292892.500000     3005789.000000    23563594.000000
## null_deviance          32341625000.000000 18835726000.000000 60209290000.000000
## r2                               0.679760           0.766536           0.438625
## residual_deviance      10348615000.000000  4397469700.000000 33790194000.000000
## rmse                          2700.535600        1733.721200        4854.234400
## rmsle                                  NA                 NA                 NA
##                                cv_5_valid
## mae                            963.718100
## mean_residual_deviance     3434871.000000
## mse                        3434871.000000
## null_deviance          19517730000.000000
## r2                               0.769063
## residual_deviance       4506551000.000000
## rmse                          1853.340500
## rmsle                                  NA
#h2o.getModel("StackedEnsemble_BestOfFamily_4_AutoML_14_20240507_05625") %>% h2o.saveModel("h2o_models/")

best_model <- h2o.loadModel("h2o_models/StackedEnsemble_BestOfFamily_4_AutoML_14_20240507_05625")

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   4997. Connecticut 1989-01-14   6503
##  2   4997. Connecticut 1989-01-28   4663
##  3   3608. Connecticut 1989-04-08   3610
##  4   3589. Connecticut 1989-04-29   3191
##  5   3574. Connecticut 1989-05-06   3224
##  6   5042. Connecticut 1989-08-12   3704
##  7   4929. Connecticut 1989-08-26   3373
##  8   4929. Connecticut 1989-09-02   2902
##  9   4929. Connecticut 1989-09-09   2856
## 10   4858. Connecticut 1989-09-16   3025
## # ℹ 2,756 more rows
?h2o.performance
## starting httpd help server ... done
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_4_AutoML_14_20240507_05625"
## 
## $model$type
## [1] "Key<Model>"
## 
## $model$URL
## [1] "/3/Models/StackedEnsemble_BestOfFamily_4_AutoML_14_20240507_05625"
## 
## 
## $model_checksum
## [1] "-4735192276950071808"
## 
## $frame
## $frame$name
## [1] "test_tbl_sid_9df6_3"
## 
## 
## $frame_checksum
## [1] "8320518109852287548"
## 
## $description
## NULL
## 
## $scoring_time
## [1] 1.715058e+12
## 
## $predictions
## NULL
## 
## $MSE
## [1] 4502463
## 
## $RMSE
## [1] 2121.901
## 
## $nobs
## [1] 2766
## 
## $custom_metric_name
## NULL
## 
## $custom_metric_value
## [1] 0
## 
## $r2
## [1] 0.8058291
## 
## $mean_residual_deviance
## [1] 4502463
## 
## $mae
## [1] 792.3475
## 
## $rmsle
## [1] "NaN"
## 
## $residual_deviance
## [1] 12453812864
## 
## $null_deviance
## [1] 64138698712
## 
## $AIC
## [1] 50231.06
## 
## $loglikelihood
## [1] 0
## 
## $null_degrees_of_freedom
## [1] 2765
## 
## $residual_degrees_of_freedom
## [1] 2764
h2o.auc(performance_h2o)
## NULL
h2o.confusionMatrix(performance_h2o)
## Warning in .local(object, ...): No Confusion Matrices for H2ORegressionMetrics
## NULL