library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.4 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ 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
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
library(timetk)
library(umap)
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.3
## ✔ modeldata 1.3.0 ✔ workflowsets 1.0.1
## ✔ parsnip 1.1.1 ✔ yardstick 1.3.0
## ✔ recipes 1.0.9
## ── 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 tidymodels_prefer() to resolve common conflicts.
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)
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: 5 days 22 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 2 days
## H2O cluster name: H2O_started_from_R_spencer_qns693
## H2O cluster total nodes: 1
## H2O cluster total memory: 2.94 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 2 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%
## 16:11:03.273: 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%
|
|=========================================================== | 84%
|
|================================================================ | 91%
|
|===================================================================== | 98%
|
|======================================================================| 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 XGBoost_2_AutoML_10_20240423_161103 1791.119 3208109
## 2 StackedEnsemble_BestOfFamily_3_AutoML_10_20240423_161103 1802.031 3247315
## 3 StackedEnsemble_BestOfFamily_2_AutoML_10_20240423_161103 1823.060 3323549
## 4 StackedEnsemble_BestOfFamily_4_AutoML_10_20240423_161103 1823.715 3325937
## 5 StackedEnsemble_AllModels_1_AutoML_10_20240423_161103 1845.937 3407484
## 6 XGBoost_1_AutoML_10_20240423_161103 1996.418 3985683
## mae rmsle mean_residual_deviance
## 1 696.1008 NaN 3208109
## 2 704.0922 NaN 3247315
## 3 719.9349 NaN 3323549
## 4 740.3592 NaN 3325937
## 5 684.5565 NaN 3407484
## 6 725.8394 NaN 3985683
##
## [29 rows x 6 columns]
models_h2o@leader
## Model Details:
## ==============
##
## H2ORegressionModel: xgboost
## Model ID: XGBoost_2_AutoML_10_20240423_161103
## Model Summary:
## number_of_trees
## 1 75
##
##
## H2ORegressionMetrics: xgboost
## ** Reported on training data. **
##
## MSE: 1608972
## RMSE: 1268.453
## MAE: 558.3463
## RMSLE: NaN
## Mean Residual Deviance : 1608972
##
##
## H2ORegressionMetrics: xgboost
## ** Reported on validation data. **
##
## MSE: 2548844
## RMSE: 1596.51
## MAE: 684.1506
## RMSLE: NaN
## Mean Residual Deviance : 2548844
##
##
## H2ORegressionMetrics: xgboost
## ** Reported on cross-validation data. **
## ** 5-fold cross-validation on training data (Metrics computed for combined holdout predictions) **
##
## MSE: 5571552
## RMSE: 2360.413
## MAE: 737.2327
## RMSLE: NaN
## Mean Residual Deviance : 5571552
##
##
## Cross-Validation Metrics Summary:
## mean sd cv_1_valid
## mae 737.232400 57.348873 743.818300
## mean_residual_deviance 5571020.000000 4213982.500000 12119702.000000
## mse 5571020.000000 4213982.500000 12119702.000000
## r2 0.763817 0.119151 0.663727
## residual_deviance 5571020.000000 4213982.500000 12119702.000000
## rmse 2236.564200 843.208860 3481.336200
## rmsle NA 0.000000 NA
## cv_2_valid cv_3_valid cv_4_valid
## mae 732.494400 762.334530 801.527830
## mean_residual_deviance 2774197.500000 2473772.000000 7536740.000000
## mse 2774197.500000 2473772.000000 7536740.000000
## r2 0.832005 0.814385 0.614147
## residual_deviance 2774197.500000 2473772.000000 7536740.000000
## rmse 1665.592200 1572.823000 2745.312300
## rmsle NA NA NA
## cv_5_valid
## mae 645.986940
## mean_residual_deviance 2950688.200000
## mse 2950688.200000
## r2 0.894822
## residual_deviance 2950688.200000
## rmse 1717.756700
## rmsle NA
#h2o.getModel("XGBoost_2_AutoML_6_20240423_150448") %>%
#h2o.saveModel("h2o_models/")
best_model <- h2o.loadModel("h2o_models/XGBoost_2_AutoML_6_20240423_150448")
predictions <- h2o.predict(best_model, newdata = test_h2o)
##
|
| | 0%
|
|======================================================================| 100%
predictions_tbl <- predictions %>%
as_tibble()
predictions_tbl %>%
bind_cols(test_tbl)
## # A tibble: 2,763 × 4
## predict symbol date claims
## <dbl> <fct> <date> <int>
## 1 5471. Connecticut 1989-01-14 6503
## 2 4149. Connecticut 1989-01-28 4663
## 3 3502. Connecticut 1989-04-08 3610
## 4 3859. Connecticut 1989-04-29 3191
## 5 3882. Connecticut 1989-05-06 3224
## 6 4474. Connecticut 1989-08-12 3704
## 7 4316. Connecticut 1989-08-26 3373
## 8 3719. Connecticut 1989-09-02 2902
## 9 3719. Connecticut 1989-09-09 2856
## 10 3719. Connecticut 1989-09-16 3025
## # ℹ 2,753 more rows
?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_2_AutoML_6_20240423_150448"
##
## $model$type
## [1] "Key<Model>"
##
## $model$URL
## [1] "/3/Models/XGBoost_2_AutoML_6_20240423_150448"
##
##
## $model_checksum
## [1] "899625653374478336"
##
## $frame
## $frame$name
## [1] "test_tbl_sid_bd23_3"
##
##
## $frame_checksum
## [1] "8810563200150418260"
##
## $description
## NULL
##
## $scoring_time
## [1] 1.713903e+12
##
## $predictions
## NULL
##
## $MSE
## [1] 3139737
##
## $RMSE
## [1] 1771.93
##
## $nobs
## [1] 2763
##
## $custom_metric_name
## NULL
##
## $custom_metric_value
## [1] 0
##
## $r2
## [1] 0.8661028
##
## $mean_residual_deviance
## [1] 3139737
##
## $mae
## [1] 694.2018
##
## $rmsle
## [1] "NaN"
h2o.auc(performance_h2o)
## NULL
h2o.confusionMatrix(performance_h2o)
## Warning in .local(object, ...): No Confusion Matrices for H2ORegressionMetrics
## NULL