-
Notifications
You must be signed in to change notification settings - Fork 2
/
regime_optimize_2.Rmd
1674 lines (1396 loc) · 66.3 KB
/
regime_optimize_2.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Regime changes 2.0"
author: "Francisco Bischoff"
date: "on `r format(Sys.time(), '%B %d, %Y')`"
output:
bookdown::html_document2:
base_format: workflowr::wflow_html
toc: true
fig_caption: yes
number_sections: yes
bibliography: [../papers/references.bib]
link-citations: true
csl: ../thesis/csl/ama.csl
css: style.css
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE, fig.align = "center", autodep = TRUE,
fig.height = 5, fig.width = 10,
tidy = "styler",
tidy.opts = list(strict = TRUE)
)
if (knitr::is_latex_output()) {
knitr::opts_chunk$set(dev = "pdf")
} else {
knitr::opts_chunk$set(dev = "svg")
}
rlang::check_installed(c(
"here", "glue", "visNetwork", "tibble", "kableExtra", "gridExtra",
"ggplot2", "dplyr", "dbarts", "vip", "pdp", "patchwork", "fastshap",
"tune"
))
options(dplyr.summarise.inform = FALSE)
library(here)
library(glue)
library(visNetwork)
library(tibble)
library(kableExtra)
library(patchwork)
library(ggplot2)
my_graphics <- function(image_name, base_path = here::here("docs", "figure")) {
file_path <- file.path(base_path, image_name)
if (knitr::is_latex_output()) {
if (file.exists(glue::glue("{file_path}.pdf"))) {
file_path <- glue::glue("{file_path}.pdf")
} else if (file.exists(glue::glue("{file_path}.png"))) {
file_path <- glue::glue("{file_path}.png")
} else {
file_path <- glue::glue("{file_path}.jpg")
}
} else {
if (file.exists(glue::glue("{file_path}.svg"))) {
file_path <- glue::glue("{file_path}.svg")
} else if (file.exists(glue::glue("{file_path}.png"))) {
file_path <- glue::glue("{file_path}.png")
} else {
file_path <- glue::glue("{file_path}.jpg")
}
}
knitr::include_graphics(file_path)
}
my_plot_html <- function(html, options) {
structure(paste0(
"<div class=\"figure\" style=\"text-align: ",
options$fig.align, "\">", html, "<p class=\"caption\">(#",
options$fig.lp, options$label, ")", options$fig.cap, "</p></div>"
),
class = "knit_asis"
)
}
my_kable <- function(title, label, content) {
res <- glue(r"(<br><table class="tg"><caption>)", "(\\#tab:{label}) {title}", r"(</caption>{content}</table>)")
out <- structure(res, format = "html", class = "knitr_kable")
attr(out, "format") <- "html"
out
}
surf_plot <- function() {
# library(rsm)
fit <- lm(mean ~ poly(window_size, mp_threshold, degree = 5), data = tree_data)
persp(fit, mp_threshold ~ window_size, zlab = "mean", zlim = c(0, 30))
}
lst_to_df <- function(lst, keep_attributes = TRUE) {
new_df <- dplyr::bind_rows(lst)
if (keep_attributes) {
nc <- nrow(new_df)
attributes(new_df) <- attributes(lst[[1]])
attr(new_df, "row.names") <- seq.int(1, nc)
}
new_df$tar_group <- NULL
return(new_df)
}
train_models <- function(data, parallel = FALSE, v = 10, rep = 3, grid = 30, train = NULL, test = NULL) {
if (is.null(train) && is.null(test)) {
set.seed(616)
initial_sampling <- rsample::initial_split(data, prop = 3 / 4)
training_split <- rsample::training(initial_sampling)
testing_split <- rsample::testing(initial_sampling)
} else {
training_split <- train
testing_split <- test
}
set.seed(616)
folds <- rsample::vfold_cv(training_split, v = v, rep = rep)
model_spec <- parsnip::bart(trees = parsnip::tune()) %>%
parsnip::set_mode("regression") %>%
parsnip::set_engine("dbarts")
model_set <- hardhat::extract_parameter_set_dials(model_spec)
wflw <- workflows::workflow() %>%
workflows::add_model(model_spec) %>%
workflows::add_formula(mean ~ .)
if (parallel) {
doParallel::registerDoParallel(cores = parallelly::availableCores())
}
set.seed(2022)
tune_search <- wflw %>%
tune::tune_grid(
resamples = folds,
param_info = model_set,
grid = grid,
metrics = yardstick::metric_set(yardstick::rmse, yardstick::rsq),
control = tune::control_grid(
verbose = TRUE,
allow_par = parallel,
save_workflow = FALSE,
save_pred = TRUE,
parallel_over = "resamples"
)
)
# uses the "one-standard error rule" (Breiman _et al._, 1984) that selects the most simple
# model that is within one standard error of the numerically optimal results.
tune_best <- tune_search %>% tune::select_best(metric = "rmse") # tune::select_by_one_std_err(trees, metric = "rsq")
final_flow <- wflw %>% tune::finalize_workflow(tune_best)
if (parallel) {
doParallel::stopImplicitCluster()
}
return(list(model = final_flow, training_data = training_split, testing_data = testing_split))
}
check_interactions <- function(model, train_data, features, parallel = FALSE) {
if (parallel) {
doParallel::registerDoParallel(cores = parallelly::availableCores())
}
# Quantify relative interaction strength
set.seed(2022)
interact <- suppressWarnings(vip::vint(model$fit$fit,
type = "regression", parallel = parallel,
feature_names = features,
train = train_data
))
if (parallel) {
doParallel::stopImplicitCluster()
}
return(interact)
}
shap_explain <- function(model, train_data, test_data, features, nsim = 20, parallel = FALSE) {
if (parallel) {
doParallel::registerDoParallel(cores = parallelly::availableCores())
}
set.seed(2022)
shap <- fastshap::explain(model,
feature_names = features,
X = data.matrix(train_data), nsim = nsim,
pred_wrapper = function(object, newdata) {
pred <- predict(object, newdata)
pred$.pred
}, adjust = TRUE,
newdata = data.matrix(test_data),
.parallel = parallel
)
if (parallel) {
doParallel::stopImplicitCluster()
}
return(shap)
}
check_importance <- function(model, train_data, test_data, features, type = c("firm", "permute", "shap"), nsim = 20, parallel = FALSE) {
type <- match.arg(type)
if (parallel) {
doParallel::registerDoParallel(cores = parallelly::availableCores())
}
importances <- NULL
set.seed(2022)
if (type == "firm") {
importances <- vip::vip(
object = model, # fitted model
method = "firm",
feature_names = features, # names of features
pred.fun = function(object, newdata) {
pred <- predict(object, newdata)
return(pred$.pred)
},
type = "regression",
parallel = parallel,
ice = TRUE,
train = train_data,
mapping = aes_string(fill = "Variable"),
aesthetics = list(color = "grey35", size = 0.8)
)
} else if (type == "permute") {
importances <- vip::vip(
object = model, # fitted model
method = "permute",
target = "mean",
feature_names = features, # names of features
type = "ratio",
pred_wrapper = function(object, newdata) {
pred <- predict(object, newdata)
pred$.pred
},
nsim = nsim,
metric = "rmse",
parallel = parallel,
keep = TRUE,
geom = "boxplot",
train = train_data,
mapping = aes_string(fill = "Variable"),
aesthetics = list(color = "grey35", size = 0.5)
)
importances$layers[[1]]$data <- importances$layers[[1]]$data %>%
dplyr::filter(!grepl("int_.*", Variable)) # nolint
} else if (type == "shap") {
importances <- vip::vip(
object = model, # fitted model
method = "shap",
feature_names = features, # names of features
pred_wrapper = function(object, newdata) {
pred <- predict(object, newdata)
pred$.pred
},
nsim = nsim,
train = as.data.frame(train_data),
newdata = as.data.frame(test_data),
.parallel = parallel,
mapping = aes_string(fill = "Variable"),
aesthetics = list(color = "grey35", size = 0.8)
)
}
importances$data <- importances$data %>%
dplyr::filter(!grepl("int_.*", Variable)) # nolint
if (parallel) {
doParallel::stopImplicitCluster()
}
return(importances)
}
tkplot <- function(object, interactive = FALSE, res = 50) {
ecg <- read_ecg_with_atr(here::here("inst/extdata/afib_regimes", object$record), resample_from = 200, resample_to = res)
value <- ecg[[1]]$II
prop <- 250 / res
mask <- seq.int(50, 100)
value[1:5] <- median(value[mask])
value[(length(value) - 5):length(value)] <- median(value[mask])
time <- seq(1, floor(length(value) * prop), length.out = length(value))
data <- tibble::tibble(time = time, value = value)
min_data <- min(data$value)
max_data <- max(data$value)
truth <- clean_truth(attr(ecg[[1]], "regimes"), length(ecg[[1]]$II)) # object$truth[[1]]
preds <- object$pred[[1]]
title <- glue::glue(
"Recording: {object$record} ",
"#truth: {length(truth)}, ",
"#preds: {length(preds)}, ",
"length: {floor(length(value)*prop)} ",
"FLOSS Score: {round(object$score, 3)}"
)
subtitle <- glue::glue(
"Parameters: ",
"MP window: {object$window_size}, ",
"MP threshold: {object$mp_threshold}, ",
"Time constraint: {object$time_constraint}, ",
"Regime threshold: {object$regime_threshold}"
)
plot <- data %>%
timetk::plot_time_series(
time, value,
.title = glue::glue(title, "<br><sup>{subtitle}</sup>"),
.interactive = interactive,
.smooth = FALSE,
.line_alpha = 0.3,
.line_size = 0.2,
.plotly_slider = interactive
)
if (interactive) {
plot <- plot %>%
plotly::add_segments(
x = preds, xend = preds, y = min_data,
yend = max_data * 1.1,
line = list(width = 2.5, color = "#0108c77f"),
name = "Predicted"
) %>%
plotly::add_segments(
x = truth, xend = truth, y = min_data,
yend = max_data,
line = list(width = 2.5, color = "#ff00007f"),
name = "Truth"
)
} else {
plot <- plot +
ggplot2::geom_segment(
data = tibble::tibble(pre = preds),
aes(
x = pre, xend = pre,
y = min_data, yend = max_data * 1.1
), size = 1, color = "#0108c77f"
) +
ggplot2::geom_segment(
data = tibble::tibble(tru = truth),
aes(
x = tru, xend = tru,
y = min_data, yend = max_data
), size = 1, color = "#ff00007f"
) +
ggplot2::theme_bw() +
ggplot2::theme(
legend.position = "none",
plot.margin = margin(0, 0, 0, 10)
) +
ggplot2::labs(title = title, subtitle = subtitle, y = ggplot2::element_blank())
}
plot
}
pbFinished <- function(msg) {
RPushbullet::pbPost("note", "Alert", msg)
}
source(here::here("scripts", "common", "read_ecg.R"))
source(here::here("scripts", "common", "score_floss.R"))
```
```{r cached, echo=FALSE, cache=FALSE}
network_1 <- readRDS(here::here("output", "regime_network.rds"))
outputs_1 <- readRDS(here::here("output", "regime_outputs.rds"))
net_1 <- network_1 %>%
visNetwork::visPhysics(hierarchicalRepulsion = list(
springLength = 1,
avoidOverlap = 0.5,
nodeDistance = 120
))
fitted1_1 <- outputs_1$fitted_models[[1]]
fitted2_1 <- outputs_1$fitted_models[[2]]
predictors_names_1 <- c("time_constraint", "mp_threshold", "window_size", "regime_threshold")
predictors_names <- c("time_constraint", "regime_threshold", "mp_threshold", "window_size", "regime_landmark")
outcome_name <- "mean"
all_fitted_1 <- lst_to_df(outputs_1$fitted_models)
all_scores_1 <- all_fitted_1 %>%
# dplyr::slice_head(n = 10) %>%
tidyr::unnest(.predictions) %>%
## mp_threshold of 1 and time_constraint of 750 are unrealistic, so we filter them out
dplyr::filter(dplyr::if_any(predictors_names_1[2]) <= 0.9, dplyr::if_any(predictors_names_1[1]) >= 800) %>%
dplyr::select(
id, rep, .sizes, .id,
all_of(predictors_names_1),
.config, .pred, truth
) %>%
dplyr::rename(fold = id, size = .sizes, record = .id, model = .config, pred = .pred) %>%
dplyr::distinct(rep, record, across(all_of(predictors_names_1)), .keep_all = TRUE) %>%
dplyr::mutate(truth = clean_truth(truth, size), pred = clean_pred(pred)) %>%
dplyr::mutate(score = score_regimes(truth, pred, 0))
holdout_scores_1 <- outputs_1$final_evaluation %>%
dplyr::select(
all_of(predictors_names_1),
.estimate
) %>%
dplyr::rename(score = .estimate) %>%
dplyr::arrange(score) %>%
dplyr::mutate(score = round(score, 3)) %>%
dplyr::mutate(`#` = dplyr::row_number(), .before = 1)
# this is a join of the all_scores_1 with the results using the landmark
all_scores <- readRDS(here::here("output/regime_outputs_lmk.rds"))
```
# Regime changes optimization
In this article, we will interchangeably use the words _parameter_, _variable_, and _feature_.
## Current pipeline
```{r thepipeline, out.width="100%", fig.cap="FLOSS pipeline."}
visNetwork::visInteraction(net_1, hover = TRUE, multiselect = TRUE, tooltipDelay = 100)
```
## Tuning process
As we have seen previously, the FLOSS algorithm is built on top of the Matrix Profile (MP). Thus, we have proposed several parameters that may or not impact the FLOSS prediction performance.
The variables for building the MP are:
- **`mp_threshold`**: the minimum similarity value to be considered for 1-NN.
- **`time_constraint`**: the maximum distance to look for the nearest neighbor.
- **`window_size`**: the default parameter always used to build an MP.
Later, the FLOSS algorithm also has a parameter that needs tuning to optimize the prediction:
- **`regime_threshold`**: the threshold below which a regime change is considered.
Using the `tidymodels` framework, we performed a basic grid search on all these parameters, followed by a bayesian search trying to finetune the parameters.
The workflow is as follows:
- From a total of 229 records, a set of 171 records were selected for tuning, and 58 records were held out.
- From these 171 records, a 5-fold cross-validation was performed two times. Here is where the grid search was performed (Figs. \@ref(fig:marginalplot) and \@ref(fig:performanceplot)).
- The best ten models from the cross-validation (5 models from each time) were then evaluated on the hold-out set. Table \@ref(tab:holdout).
Fig. \@ref(fig:marginalplot) shows the performance achieved individually during the cross-validation for each parameter. The plot shows the default performance metric (`floss_error_macro`) and another version (`floss_error_micro`) where the error is computed globally, being less prone to individual record errors.
```{r marginalplot, eval = FALSE, out.width="100%", cache=FALSE}
#| fig.cap="Marginal plot of all parameters searched during the cross-validation.
#| The first line shows the default performance metric (`macro`), which is the average of the scores of every recording
#| in the resamples. The line below shows another metric (`micro`) which does not take into account the length of every
#| recording but is later normalized by the total length of the resample. Lower values are better."
plot_data <- all_fitted %>% # this will collect the macro and micro scores
tidyr::unnest(.metrics) %>%
## mp_threshold of 1 and time_constraint of 750 are unrealistic, so we filter them out
dplyr::filter(dplyr::if_any(predictors_names[2]) <= 0.9, dplyr::if_any(predictors_names[1]) >= 800) %>%
dplyr::select(all_of(predictors_names), .metric, .estimate) %>%
dplyr::rename(prediction = .estimate, metric = .metric) %>%
tidyr::pivot_longer(names_to = "parameter", values_to = "value", cols = all_of(predictors_names))
aa <- ggplot2::ggplot(plot_data, ggplot2::aes(x = value, y = prediction, group = value)) +
ggplot2::geom_boxplot(outlier.alpha = 0.2) +
ggplot2::facet_grid(metric ~ parameter, scales = "free") +
ggplot2::labs(title = "Marginal plot", x = "Parameter value", y = "Performance") +
ggplot2::ylim(0, 30) +
ggplot2::theme_bw()
hack <- rlang::env_get(aa$layers[[1]]$stat, "compute_group")
body(hack)[[16]][[3]] <- quote(dplyr::if_else(data$x[1] <= 10, 0.02021286,
dplyr::if_else(data$x[1] <= 500, 5, 20)
))
rlang::env_poke(aa$layers[[1]]$stat, "compute_group", hack)
aa
body(hack)[[16]][[3]] <- quote(width) # unhack
rlang::env_poke(aa$layers[[1]]$stat, "compute_group", hack) # unhack
```
Fig. \@ref(fig:performanceplot) shows the performance across all cross-validation folds for every iteration of the bayes search.
```{r performanceplot, fig.height = 7.5, out.width="90%", cache=FALSE}
#| fig.cap="Parameters exploration using Bayesian optimization. The plots show the performances across all cross-validation
#| folds on every iteration of the bayes search. The first line shows the results of the first repetition, and
#| the second line during the second repetition. The values on the left are shown in the default metric (`macro`).
#| On the right side, the values are shown in the `micro` metric. The iteration 'Zero' is the initial grid search."
fit1 <- tune::autoplot(fitted1, type = "performance", width = 0.8) +
ggplot2::labs(title = "Performances - Repetition 1", x = "Iterations", y = "Performance") +
ggplot2::ylim(0, 45) + ggplot2::theme_bw()
fit1$layers[[1]]$geom$default_aes$alpha <- 0.2
fit1$layers[[2]]$geom$default_aes$alpha <- 0.5
fit2 <- tune::autoplot(fitted2, type = "performance", width = 0.8) +
ggplot2::labs(title = "Performances - Repetition 2", x = "Iterations", y = "Performance") +
ggplot2::ylim(0, 45) + ggplot2::theme_bw()
fit1 / fit2
fit1$layers[[1]]$geom$default_aes$alpha <- NA
fit1$layers[[2]]$geom$default_aes$alpha <- NA
```
Table \@ref(tab:holdout) shows the performance of the best ten models on the hold-out set (a set of records that was never used for training).
```{r holdout, eval = FALSE, cache=FALSE}
kableExtra::kbl(holdout_scores_1,
booktabs = TRUE,
col.names = c("#", "Time Constraint", "MP Threshold", "Window Size", "Regime Threshold", "FLOSS Score"),
caption = "Holdout results of the 10 best models from cross-validation (less is better)",
align = "c",
position = "ht"
) %>%
kableExtra::row_spec(0, bold = TRUE) %>%
kableExtra::kable_styling(full_width = TRUE)
```
## Parameters analysis
The above process was an example of parameter tuning seeking the best model for a given set of parameters. It used a nested cross-validation procedure that aims to find the best combination of parameters and avoid overfitting.
While this process is powerful and robust, it does not show us the importance of each parameter. At least one parameter has been introduced by reasoning about the problem (`mp_threshold`), but how important it (and other parameters) is for predicting regime changes?
For example, the process above took 4 days, 20 hours, and 15 minutes to complete the grid search using an Intel(R) Xeon(R) Silver 4210R @ 2.40 GHz server. Notice that about 133 different combinations of parameters were tested on computing the MP (not FLOSS, the `regime_threshold`), 5 folds, 2 times each. That sums up about 35.2 x 10^9^ all-pairs Euclidean distances computed on less than 5 days (on CPU, not GPU). Not bad.
Another side note on the above process, it is not a "release" environment, so we must consider lots of overhead in computation and memory usage that must be taken into account during these five days of grid search. Thus, much time can be saved if we know what parameters are essential for the problem.
In order to check the effect of the parameters on the model, we need to compute the _importance_ of each parameter.
Wei _et al._ published a comprehensive review on variable importance analysis [@Wei2015].
Our case is not a typical case of variable importance analysis, where a set of _features_ are tested against an _outcome_. Instead, we have to proxy our analysis by using as _outcome_ the FLOSS performance score and as _features_ (or _predictors_) the tuning parameters that lead to that score.
That is accomplished by fitting a model using the tuning parameters to predict the FLOSS score and then applying the techniques to compute the importance of each parameter.
For this matter, a Bayesian Additive Regression Trees (BART) model was chosen after an experimental trial with a set of regression models (including glmnet, gbm, mlp) and for its inherent characteristics, which allows being used for model-free variable selection [@Chipman2010]. The best BART model was selected using 10-fold cross-validation repeated 3 times, having great predictive power with an RMSE around 0.2 and an R^2^ around 0.99. With this fitted model, we could evaluate each parameter's importance.
### Interactions
Before starting the parameter importance analysis, we need to consider the parameter interactions since this is usually the weak spot of the analysis techniques, as will be discussed later.
The first BART model was fitted using the following parameters:
\begin{equation}
\begin{aligned}
E( score ) &= \alpha + time\_constraint\\
&\quad + mp\_threshold + window\_size\\
&\quad + regime\_threshold
\end{aligned}
(\#eq:first)
\end{equation}
After checking the interactions, this is the refitted model:
\begin{equation}
\begin{aligned}
E( score ) &= \alpha + time\_constraint\\
&\quad + mp\_threshold + window\_size\\
&\quad + regime\_threshold + \left(mp\_threshold \times window\_size\right)
\end{aligned}
(\#eq:refitted)
\end{equation}
Fig. \@ref(fig:interaction) shows the variable interaction strength between pairs of variables. That allows us to verify if there are any significant interactions between the variables. Using the information from the first model fit, equation \@ref(eq:first), we see that `mp_threshold` interacts strongly with `window_size`. After refitting, taking into account this interaction, we see that the interaction strength graphic is much better, equation \@ref(eq:refitted).
```{r modelbart, message=FALSE, cache=FALSE}
tree_data <- all_scores %>%
dplyr::group_by(across(all_of(predictors_names))) %>%
dplyr::summarize(mean = mean(score)) %>%
dplyr::ungroup()
trained_model <- NULL
# Caching ===========
if (file.exists(here("output", "dbarts_fitted_lmk.rds"))) {
trained_model <- readRDS(here("output", "dbarts_fitted_lmk.rds"))
} else {
trained_model <- train_models(tree_data, parallel = TRUE, v = 5, rep = 1, grid = 30)
saveRDS(trained_model, file = here("output", "dbarts_fitted_lmk.rds"))
}
train_data <- trained_model$training_data
testing_data <- trained_model$testing_data
set.seed(102)
best_fit <- generics::fit(trained_model$model, train_data)
# Caching ===========
if (file.exists(here("output", "importances_lmk.rds"))) {
interactions <- readRDS(here("output", "importances_lmk.rds"))
importance_firm <- interactions$importance_firm
importance_perm <- interactions$importance_perm
importance_shap <- interactions$importance_shap
shap_html_test <- interactions$shap_html_test
shap_fastshap_all_test <- interactions$shap_fastshap_all_test
interactions <- interactions$interactions
} else {
interactions <- check_interactions(best_fit, train_data, predictors_names, parallel = TRUE)
importance_firm <- check_importance(best_fit, testing_data, testing_data, predictors_names,
type = "firm", parallel = TRUE
)
importance_firm <- ggplot2::ggplot_build(importance_firm)$plot$data
importance_perm <- check_importance(best_fit, testing_data, testing_data, predictors_names,
type = "permute", nsim = 100, parallel = TRUE
)
importance_perm <- ggplot2::ggplot_build(importance_perm)$plot$data
importance_perm <- attr(importance_perm, "raw_scores")
importance_perm <- tibble::as_tibble(t(importance_perm)) %>%
dplyr::select(all_of(predictors_names)) %>%
tidyr::pivot_longer(everything(), names_to = "Variable", values_to = "Importance")
importance_shap <- check_importance(best_fit, train_data, testing_data[, predictors_names], predictors_names,
type = "shap", nsim = 400, parallel = TRUE
)
importance_shap <- ggplot2::ggplot_build(importance_shap)$plot$data
shap_fastshap_all_test <- shap_explain(best_fit, train_data[, predictors_names], testing_data[, predictors_names],
predictors_names,
nsim = 400, parallel = TRUE
)
preds_test <- predict(best_fit, testing_data[, predictors_names])
shap_html_test <- fastshap::force_plot(
object = shap_fastshap_all_test, feature_values = testing_data[, predictors_names],
baseline = mean(preds_test$.pred), display = "html"
)
shap_html_test <- stringr::str_remove(shap_html_test, "<meta.+?>")
saveRDS(list(
interactions = interactions,
importance_firm = importance_firm,
importance_perm = importance_perm,
importance_shap = importance_shap,
shap_fastshap_all_test = shap_fastshap_all_test,
shap_html_test = shap_html_test
), file = here("output", "importances_lmk.rds"))
}
# tree_data2 <- tree_data %>%
# dplyr::mutate(
# int_mp_w = mp_threshold * window_size,
# # int_mp_rt = mp_threshold * regime_threshold
# # int_mp_tc = mp_threshold * time_constraint
# .before = mean
# )
# A tibble: 10 × 2
# Variables Interaction
# <chr> <dbl>
# 1 regime_threshold*regime_landmark 1.51
# 2 mp_threshold*window_size 1.20
# 3 mp_threshold*regime_landmark 1.16
# 4 window_size*regime_landmark 0.985
# 5 time_constraint*regime_threshold 0.887
# 6 regime_threshold*window_size 0.850
# 7 regime_threshold*mp_threshold 0.810
# 8 time_constraint*regime_landmark 0.671
# 9 time_constraint*mp_threshold 0.619
# 10 time_constraint*window_size 0.389
# # A tibble: 10 × 2
# Variables Interaction
# <chr> <dbl>
# 1 mp_threshold*regime_landmark 1.46
# 2 regime_threshold*window_size 0.992
# 3 time_constraint*regime_threshold 0.683
# 4 regime_threshold*regime_landmark 0.624
# 5 time_constraint*mp_threshold 0.590
# 6 time_constraint*regime_landmark 0.449
# 7 mp_threshold*window_size 0.329
# 8 regime_threshold*mp_threshold 0.288
# 9 window_size*regime_landmark 0.256
# 10 time_constraint*window_size 0.251
train_data2 <- train_data %>%
dplyr::mutate(
int_rt_rl = regime_threshold * regime_landmark,
int_mp_w = mp_threshold * window_size,
int_mp_rl = mp_threshold * regime_landmark,
# int_mp_rt = mp_threshold * regime_threshold
# int_mp_tc = mp_threshold * time_constraint
.before = mean
)
testing_data2 <- testing_data %>%
dplyr::mutate(
int_rt_rl = regime_threshold * regime_landmark,
int_mp_w = mp_threshold * window_size,
int_mp_rl = mp_threshold * regime_landmark,
# int_mp_rt = mp_threshold * regime_threshold
# int_mp_tc = mp_threshold * time_constraint
.before = mean
)
predictor_names_int <- c(predictors_names, "int_rt_rl", "int_mp_w", "int_mp_rl")
trained_model2 <- NULL
# Caching ==========
if (file.exists(here("output", "dbarts_fitted2_lmk.rds"))) {
trained_model2 <- readRDS(here("output", "dbarts_fitted2_lmk.rds"))
} else {
trained_model2 <- train_models(NULL, parallel = TRUE, v = 5, rep = 1, grid = 30, train_data2, testing_data2)
saveRDS(trained_model2, file = here("output", "dbarts_fitted2_lmk.rds"))
}
train_data2 <- trained_model2$training_data
testing_data2 <- trained_model2$testing_data
set.seed(102)
best_fit2 <- generics::fit(trained_model2$model, train_data2)
# Caching ===========
if (file.exists(here("output", "importances2_lmk.rds"))) {
interactions2 <- readRDS(here("output", "importances2_lmk.rds"))
importance_firm2 <- interactions2$importance_firm2
importance_perm2 <- interactions2$importance_perm2
importance_shap2 <- interactions2$importance_shap2
shap_fastshap_all_test2 <- interactions2$shap_fastshap_all_test2
shap_html_test2 <- interactions2$shap_html_test2
interactions2 <- interactions2$interactions2
} else {
interactions2 <- check_interactions(best_fit2, train_data2, predictors_names, parallel = TRUE)
importance_firm2 <- check_importance(best_fit2, testing_data2, testing_data2, predictors_names, type = "firm", parallel = TRUE)
importance_firm2 <- ggplot2::ggplot_build(importance_firm2)$plot$data
importance_perm2 <- check_importance(best_fit2, testing_data2, testing_data2, predictor_names_int,
type = "permute",
nsim = 100, parallel = TRUE
)
importance_perm2 <- ggplot2::ggplot_build(importance_perm2)$plot$data
importance_perm2 <- attr(importance_perm2, "raw_scores")
importance_perm2 <- tibble::as_tibble(t(importance_perm2)) %>%
dplyr::select(all_of(predictors_names)) %>%
tidyr::pivot_longer(everything(), names_to = "Variable", values_to = "Importance")
importance_shap2 <- check_importance(best_fit2, train_data2[, predictor_names_int], testing_data2[, predictor_names_int], predictor_names_int,
type = "shap", nsim = 400, parallel = TRUE
)
importance_shap2 <- ggplot2::ggplot_build(importance_shap2)$plot$data
shap_fastshap_all_test2 <- shap_explain(best_fit2, train_data2[, predictor_names_int], testing_data2[, predictor_names_int], predictors_names, nsim = 400, parallel = TRUE)
preds_test2 <- predict(best_fit2, testing_data2[, predictor_names_int])
shap_html_test2 <- fastshap::force_plot(object = shap_fastshap_all_test2, feature_values = testing_data2[, predictors_names], baseline = mean(preds_test2$.pred), display = "html")
shap_html_test2 <- stringr::str_remove(shap_html_test2, "<meta.+?>")
saveRDS(list(
interactions2 = interactions2,
importance_firm2 = importance_firm2,
importance_perm2 = importance_perm2,
importance_shap2 = importance_shap2,
shap_fastshap_all_test2 = shap_fastshap_all_test2,
shap_html_test2 = shap_html_test2
), file = here("output", "importances2_lmk.rds"))
}
```
```{r interaction, fig.height = 5, fig.width= 8, out.width="100%", cache=FALSE}
#| fig.cap="Variable interactions strenght using feature importance ranking measure (FIRM) approach [@Greenwell2018].
#| A) Shows strong interaction between `mp_threshold` and `window_size`.
#| B) Refitting the model with this interaction taken into account, the strength is substantially reduced."
interactions_plot <- ggplot2::ggplot(interactions, ggplot2::aes(
x = reorder(Variables, Interaction),
y = Interaction, fill = Variables
)) +
ggplot2::geom_col(color = "grey35", size = 0.2) +
ggplot2::coord_flip() +
ggplot2::labs(
title = "Normal fit",
y = ggplot2::element_blank(),
x = ggplot2::element_blank()
) +
ggplot2::ylim(0, 1.65) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position = "none")
interactions2_plot <- ggplot2::ggplot(interactions2, ggplot2::aes(
x = reorder(Variables, Interaction),
y = Interaction, fill = Variables
)) +
ggplot2::geom_col(color = "grey35", size = 0.2) +
ggplot2::coord_flip() +
ggplot2::labs(
title = "Taking into account the interactions",
y = "Interaction strength",
x = ggplot2::element_blank()
) +
ggplot2::ylim(0, 1.65) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position = "none")
inter <- interactions_plot / interactions2_plot
inter + plot_annotation(
title = "Variable Interaction Strength",
tag_levels = c("A", "1"),
theme = ggplot2::theme_bw()
)
```
### Importance
After evaluating the interactions, we then can perform the analysis of the variable importance. The goal is to understand how the FLOSS score behaves when we change the parameters.
Here is a brief overview of the different techniques:
#### Feature Importance Ranking Measure (FIRM)
The FIRM is a variance-based method. This implementation uses the ICE curves to quantify each feature effect which is more robust than partial dependance plots (PDP) [@Greenwell2020].
It is also helpful to inspect the ICE curves to uncover some heterogeneous relationships with the outcome [@Molnar2022].
**Advantages:**
* Has a causal interpretation (for the model, not for the real world)
* ICE curves can uncover heterogeneous relationships
**Disadvantages:**
* The method does not take into account interactions.
#### Permutation
The Permutation method was introduced by Breiman in 2001 [@Breiman2001] for Random Forest, and the implementation used here is a model-agnostic version introduced by Fisher _et al._ in 2019 [@Fisher2018]. A feature is "unimportant" if shuffling its values leaves the model error unchanged, assuming that the model has ignored the feature for the prediction.
**Advantages:**
* Easy interpretation: the importance is the increase in model error when the feature's information is destroyed.
* No interactions: the interaction effects are also destroyed by permuting the feature values.
**Disadvantages:**
* It is linked to the model error: not a disadvantage _per se_, but may lead to misinterpretation if the goal is to understand how the output varies, regardless of the model's performance. For example, if we want to measure the robustness of the model when someone tampers the features, we want to know the _model variance_ explained by the features. Model variance (explained by the features) and feature importance correlate strongly when the model generalizes well (it is not overfitting).
* Correlations: If features are correlated, the permutation feature importance can be biased by unrealistic data instances. Thus we need to be careful if there are strong correlations between features.
#### SHAP
The SHAP feature importance [@Lundberg2017] is an alternative to permutation feature importance. The difference between both is that Permutation feature importance is based on the decrease in model performance, while SHAP is based on the magnitude of feature attributions.
**Advantages:**
* It is not linked to the model error: as the underlying concept of SHAP is the Shapley value, the value attributed to each feature is related to its contribution to the output value. If a feature is important, its addition will significantly affect the output.
**Disadvantages:**
* Computer time: Shapley value is a computationally expensive method and usually is computed using Montecarlo simulations.
* The Shapley value can be misinterpreted: The Shapley value of a feature value **is not** the difference of the predicted value after removing the feature from the model training. The interpretation of the Shapley value is: "Given the current set of feature values, the contribution of a feature value to the difference between the actual prediction and the mean prediction is the estimated Shapley value" [@Molnar2022].
* Correlations: As with other permutation methods, the SHAP feature importance can be biased by unrealistic data instances when features are correlated.
### Importance analysis
Using the three techniques above simultaneously allows a broad comparison of the model behavior [@Greenwell2020]. All three methods are model-agnostic (separates interpretation from the model), but as we have seen above, each method has its advantages and disadvantages [@Molnar2022].
Fig. \@ref(fig:importance) then shows the variable importance using three methods: Feature Importance Ranking Measure (FIRM) using Individual Conditional Expectation (ICE), Permutation-based, and Shapley Additive explanations (SHAP). The first line of this figure shows that the interaction between `mp_threshold` and `window_size` obscures the results, where except for `time_constraint`, the other variables have similar importance. In the second line, the most important feature that all three methods agree on is the `regime_threshold`.
```{r importance, fig.height = 7, fig.width= 15, out.width="100%", cache=FALSE}
#| fig.cap="Variables importances using three different methods. A) Feature Importance Ranking Measure
#| using ICE curves. B) Permutation method. C) SHAP (400 iterations). Line 1 refers to the original
#| fit, and line 2 to the re-fit, taking into account the interactions between variables
#| (Fig. \\@ref(fig:interaction))."
importance_firm_plot <- ggplot2::ggplot(importance_firm, aes(
x = reorder(Variable, Importance),
y = Importance, fill = Variable
)) +
ggplot2::geom_col(colour = "grey35", size = 0.8, show.legend = FALSE) +
ggplot2::coord_flip() +
ggplot2::labs(
title = "Feature Importance Ranking Measure",
subtitle = "Individual Conditional Expectation",
x = "",
y = ggplot2::element_blank()
) +
ggplot2::ylim(0, 3.5) +
ggplot2::theme_bw() +
ggplot2::theme(
legend.position = "none",
plot.margin = margin(0, 0, 0, 10)
)
importance_perm_plot <- ggplot2::ggplot(importance_perm, aes(
x = reorder(Variable, Importance),
y = Importance, fill = Variable
)) +
ggplot2::geom_boxplot(colour = "grey35", size = 0.5, show.legend = FALSE) +
ggplot2::coord_flip() +
ggplot2::labs(
title = "Permutation-based (100x)",
x = "",
y = ggplot2::element_blank()
) +
ggplot2::ylim(2, 15) +
ggplot2::theme_bw() +
ggplot2::theme(
legend.position = "none",
plot.margin = margin(0, 0, 0, 10)
)
importance_shap_plot <- ggplot2::ggplot(importance_shap, aes(
x = reorder(Variable, Importance),
y = Importance, fill = Variable
)) +
ggplot2::geom_col(colour = "grey35", size = 0.8, show.legend = FALSE) +
ggplot2::coord_flip() +
ggplot2::labs(
title = "SHAP (400 iterations)",
x = "",
y = ggplot2::element_blank()
) +
ggplot2::ylim(0, 1.6) +
ggplot2::theme_bw() +
ggplot2::theme(
legend.position = "none",
plot.margin = margin(0, 0, 0, 10)
)
importance_firm2_plot <- ggplot2::ggplot(importance_firm2, aes(
x = reorder(Variable, Importance),
y = Importance, fill = Variable
)) +
ggplot2::geom_col(colour = "grey35", size = 0.8, show.legend = FALSE) +
ggplot2::coord_flip() +
ggplot2::labs(
x = "",
y = "Importance"
) +
ggplot2::ylim(0, 3.5) +
ggplot2::theme_bw() +
ggplot2::theme(
legend.position = "none",
plot.margin = margin(0, 0, 0, 10)
)
importance_perm2_plot <- ggplot2::ggplot(importance_perm2, aes(
x = reorder(Variable, Importance),
y = Importance, fill = Variable
)) +
ggplot2::geom_boxplot(colour = "grey35", size = 0.5, show.legend = FALSE) +
ggplot2::coord_flip() +
ggplot2::labs(
x = "",
y = "Importance"
) +
ggplot2::ylim(2, 15) +
ggplot2::theme_bw() +
ggplot2::theme(
legend.position = "none",
plot.margin = margin(0, 0, 0, 10)
)
importance_shap2_plot <- ggplot2::ggplot(importance_shap2, aes(
x = reorder(Variable, Importance),
y = Importance, fill = Variable
)) +
ggplot2::geom_col(colour = "grey35", size = 0.8, show.legend = FALSE) +
ggplot2::coord_flip() +
ggplot2::labs(
x = "",
y = "Importance"
) +
ggplot2::ylim(0, 1.6) +
ggplot2::theme_bw() +
ggplot2::theme(
legend.position = "none",
plot.margin = margin(0, 0, 0, 10)
)
all <- (importance_firm_plot / importance_firm2_plot + plot_layout(tag_level = "new")) |
(importance_perm_plot / importance_perm2_plot + plot_layout(tag_level = "new")) |
(importance_shap_plot / importance_shap2_plot + plot_layout(tag_level = "new")) +
plot_layout(guides = "collect")
all + plot_annotation(
title = "Variable importances",
tag_levels = c("A", "1"),
theme = ggplot2::theme_bw() + ggplot2::theme(
plot.title = ggplot2::element_text(size = 20)
)
)
```
Fig. \@ref(fig:importanceshap) and \@ref(fig:importanceshap2) show the effect of each feature on the FLOSS score. The main differences before and after removing the interactions are the magnitude of the less important features and the shape of `time_constraint` that initially had a valley around 1600. However, it seems that it flats out.
```{r importanceshap, message=FALSE, fig.height = 6, fig.width= 10, out.width="100%", cache=FALSE}
#| fig.cap="This shows the effect each variable has on FLOSS score. This plot doesn't take into account the
#| variable interactions."
t1 <- autoplot(shap_fastshap_all_test,
type = "dependence",
X = testing_data, feature = predictors_names[2], alpha = 0.2
) + ggplot2::geom_smooth(method = loess) + ggplot2::theme_bw()
t2 <- autoplot(shap_fastshap_all_test,
type = "dependence",