-
Notifications
You must be signed in to change notification settings - Fork 2
/
report.Rmd
2067 lines (1733 loc) · 84.5 KB
/
report.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: "Predicting Group Life Client Mortality during a Pandemic, Final Report"
author: Team Outliers
date: August 2, 2021
output:
github_document:
toc: true
toc_depth: 2
pdf_document:
keep_tex: true
---
```{r, setup, include=FALSE}
knitr::opts_chunk$set(
fig.path = "figures/report/fig-",
cache.path = "cache/report/")
```
# Final report
IMA Math-to-Industry Bootcamp, Securian Financial
Team members:
* Marc Härkönen
* Samara Chamoun
* Shuxian Xu
* Abba Ramadan
* Lei Yang
* Yuchen Cao
Mentor:
* Douglas Armstrong
Supervisors:
* Daniel Spirn
* Thomas Höft
# Executive summary
As Babe Ruth once said: “Yesterday’s home runs don’t win today’s games!”
In March 2020, with the pandemic starting, the whole world fell into a state of uncertainty about the future. Similarly to other businesses, the insurance sector was affected by the COVID breakout as well and the whole business landscape needs to address the changes that came along.
We are team Outliers from the Securian Financial Department of Data Science and we think we have the resources, the expertise and the determination to present the management team with a whole new set of information that can help their decision making during a pandemic. With Group Life Insurance being an important part of our company and for our clients, there is no doubt that we should look closely at how it is being affected by the recent events. For the past few weeks, we have been working on a project that aims to predict Group Life mortality for our clients during a pandemic.
One might ask how the pandemic is exactly affecting group life insurance. As we know, life insurance guarantees payment of death benefits. Since the COVID-19 breakout, our clients are experiencing a higher mortality rate then usual, which has resulted in an unprecedented increase in claims. Our primary function as data scientists is to correctly forecast the mortality risk, and the way to do that is by first tracking the claims performance.
We classify clients as high-risk and low-risk by using one of the most popular metrics to track claims performance, the Actual-to-Expected ratio (AE).
Observing the large shift of the proportion of clients that are classified as high-risk from 2019 to 2020, we hypothesize that the pre-pandemic, historical AE of a client is no longer a good predictor of the client’s performance during a pandemic.
We aim at replacing this historical AE with a predictive one that can help our management and sales team have better insight on the possibility that a client experiences an Adverse mortality event during an outbreak. We collect data from the zip codes where the companies are located: poverty percentage, education level, unemployment rate, etc. We then combine this information with some characteristics of the companies such as average age of employees and some pandemic-related resources. We then apply several machine learning models, validate the results and build the best possible insight for proper risk-management.
We provide our management team with two models: one is long-term and the other is short-term. Each of these models serve different purposes and bring valuable assets to the company.
The long-term model can be used at a specific time and uses the information of some clients to predict what can happen to other clients in different zip codes. While working on this model, our goal was to minimize the loss of money for Securian that can be caused by long-term adverse mortality event such as a pandemic. On one hand, we aim at minimizing the number of clients that were adverse and predicted otherwise. We also wanted to prevent the company from losing clients that will perform well, so we simultaneously focused on minimizing the number of clients that are not adverse and predicted to be so. The strength of this model lies in understanding the contributions of different predictors in the performance of the clients. The management team can have better insights and clarity regarding how each predictor contributes positively or negatively into the classification. It is worthy to note that adding the AE2019 to the list of predictors for this model won’t make any additional improvements.
As opposed to the long-term model, the short-term model integrates the time factor and can react to changes during the pandemic.
Not only can the model predict the future performance of existing clients, it can also do so for potential new clients.
Having these two models in the hands of the management team, the latter can gain accurate and deep understanding of old and new clients performance during a pandemic. They can use this enhanced understanding to determine contract renewals, to negotiate with clients and most importantly to better face the uncertainties of the future.
# Data wrangling
In this section, we describe our data gathering and tidying process.
We will be making extensive use of the `tidyverse` family of packages.
A series of scripts are used to generate tibbles, which are then saved in a `*.feather` for fast loading.
A full list of scripts with their dependencies can be viewed in the Appendix.
```{r message = FALSE}
library(tidyverse)
library(feather)
library(lubridate)
```
## Data sources
Our dataset consists of two parts: publicly obtained data and simulated clients.
Below we describe our publicly obtained datasets.
Filename | Source | Description
---------|--------|------------
`covid_deaths_usafacts.csv` | [USAFacts](https://usafacts.org/visualizations/coronavirus-covid-19-spread-map/) | Cumulative weekly COVID-19 deaths by county
`soa_base_2017.csv` | (Sent by Douglas Armstrong) | $q_x$ values by gender, age, industry
`Population_Estimates.csv` | [USDA ERS](https://www.ers.usda.gov/data-products/county-level-data-sets/download-data/) | Population estimates of the U.S., states and counties, 2019
`COVID-19_Vaccinations_in_the_United_States_County_data.gov.csv` | [CDC](https://catalog.data.gov/dataset/covid-19-vaccinations-in-the-united-statescounty-8204e) | Overall US COVID-19 Vaccine administration and vaccine equity data at county level
`Education_Estimates.csv` | [USDA ERS](https://www.ers.usda.gov/data-products/county-level-data-sets/download-data/) | Educational attainment for adults age 25 and older for the U.S., states and counties, 2015-19
`Poverty_Estimates.csv` | [USDA ERS](https://www.ers.usda.gov/data-products/county-level-data-sets/download-data/) | Poverty rates in the U.S., states and counties, 2019
`Unemployment_Estimates.csv` | [USDA ERS](https://www.ers.usda.gov/data-products/county-level-data-sets/download-data/) | Unemployment rates, 2019 and 2020; median househould income, 2019. States and counties
`Vaccine_Hesitancy_for_COVID-19__County_and_local_estimates.csv` | [CDC](https://catalog.data.gov/dataset/vaccine-hesitancy-for-covid-19-county-and-local-estimates) | Vaccine hesitancy estimates for COVID-19
`countypres_2000-2020.csv` | [MIT Election Data + Science Lab](https://dataverse.harvard.edu/file.xhtml?fileId=4819117&version=9.0) | Election data by county (only 2020 used)
`zcta_county_rel_10.txt` | [US Census Bureau](https://www.census.gov/geographies/reference-files/time-series/geo/relationship-files.2010.html#par_textimage_674173622) | Zip code to county relationship file (2010)
`2020_12_23/reference_hospitalization_all_locs.csv` | [IHME](http://www.healthdata.org/node/8787) | COVID-19 projections **as of Dec 23 2020**
`state.txt` | [US Census Bureau](https://www.census.gov/library/reference/code-lists/ansi.html) | State names and FIPS codes
### US Census bureau
We used the US Census Bureau's API to obtain the 2019 estimates for population and density per county from the Census Bureau's Population Estimates Program (PEP).
The `censusapi` package provides an R interface to the API.
Using the API requires an API key, which can be obtained from [here](https://api.census.gov/data/key_signup.html).
The following snippet fetches the data, and saves the tibble into a file called `pop_den.feather`. See also `data/census.R`.
```{r eval = FALSE}
library("censusapi")
Sys.setenv(CENSUS_KEY = "YOUR_KEY_HERE")
# date_code = 12 is an estimate for July 1, 2019
# total population + density
pop <- getCensus(
name = "pep/population",
vintage = 2019,
region = "county:*",
vars = c("POP", "DENSITY"),
DATE_CODE = 12)
pop <- tibble(pop) %>%
select(-DATE_CODE)
write_feather(pop, "pop_den.feather")
```
## County to zip3
So far all of our public data is expressed by US county, but our clients' location are given as a ZIP3 code (the first three digits of a five-digit zip code).
The conversion from county to ZIP3 is nontrivial, as some zip codes span multiple counties and some counties span multiple zip codes.
To convert data given by county to ZIP3, we first need a ZIP3 to county relationship table.
The relationship table contains three columns: ZIP3, County, and Population. Each row corresponds to a pair $(\text{ZIP3}, \text{county})$, and the Population column contains the population in the intersection $\text{ZIP3} \cap \text{county}$.
Then, given county-level data, we compute the corresponding value for any given ZIP3 by taking a weighted average of all counties intersecting that ZIP3, and weighting by the population in $\text{ZIP3} \cap \text{county}$.
This operation looks as follows in code (suppose `A` contains some county-level data, e.g. poverty levels):
```{r eval = FALSE}
A %>%
left_join(zip3_rel, by = "county") %>%
group_by(zip3) %>%
summarize(poverty = weighted.mean(poverty, population, na.rm = TRUE))
```
We note that in practice, the country is represented by a 5 digit FIPS code.
The first two digits indicate the state, and the last 3 digits indicate the county.
The relationship table is generated by `zip3_rel.R` and can be loaded from `zip3_rel.feather`.
For an example of how it's used, see `wrangling.Rmd` and `deaths.R`.
## Weekly deaths & IHME forecasts
In some of our models we use weekly COVID deaths as a predictor.
The file `covid_deaths_usafacts.csv` contains this data for every day and every county.
We convert the county-level information to zip3 as above, and convert the daily data to weekly.
The library `lubridate` doesn't contain a type for week; we use the last day of the week instead (using `lubridate::ceiling_date(date, unit = "week")`).
We will also be using forecasts from the Institute for Health Metrics and Evaluation (IHME) to assist our models.
These forecasts are only given by state, so we need to convert states to ZIP3.
The file `data/state.txt` contains the state FIPS code and state name.
Since some ZIP3 codes span several states, we assign a state to each ZIP3 code by determining which state is most represented among counties in the ZIP3.
See also `data/deaths.R` and `time.Rmd` (line 856 onwards).
## Simulated client dataset
The clients we were tasked to study were simulated by Securian Financial.
The dataset consists of 20 files called `data/simulation_data/experience_weekly_{n}.RDS` and `data/simulation_data/person_{n}.RDS` for $n = 1,\dotsc, 10$.
In total, we have 500 clients and 1,382,321 individuals.
The `person_{n}.RDS` files contain information such as company, zip code, age, face amount, gender, and collar (blue or white, but in this dataset every indivual was blue collar).
The rows in `experience_weekly_{n}.RDS` correspond to individuals and weeks, and contains a flag `death` that becomes 1 on the week they die.
In total, these tables contain 170,025,483 rows, but the same information can be conveyed in 1,382,231 rows by attaching to each individual their death date (or `NA` if they don't die).
```{r eval = FALSE}
read_data <- function(n) {
exp_name <- str_glue("simulation_data/experience_weekly_{n}.RDS")
per_name <- str_glue("simulation_data/person_{n}.RDS")
exp <- read_rds(exp_name)
per <- read_rds(per_name)
dies <-
exp %>%
filter(death > 0) %>%
select(client, participant, week, month, year)
aug_per <-
per %>%
left_join(dies, by = c("client", "participant"))
aug_per
}
all_persons <- (1:10) %>% map_dfr(read_data)
```
We noticed that some individuals die more than once. The following removes the multiple deaths.
```{r eval = FALSE}
all_persons <-
all_persons %>%
group_by(client, participant) %>%
arrange(year, week, .by_group = TRUE) %>%
slice_head()
```
We finally attach to each individual their yearly $q_x$ value, and save the resuilting tibble in `data/simultation_data/all_persons.feather`.
```{r eval = FALSE}
qx_table <- read_csv("soa_base_2017.csv")
all_persons <-
all_persons %>%
left_join(qx_table, by = c("Age", "Sex", "collar")) %>%
relocate(qx, .after = collar)
write_feather(all_persons %>% ungroup(), "simulation_data/all_persons.feather")
```
The individual-level dataset is then converted to a client-level dataset.
We summarize each client by taking their ZIP3, size (number of individuals), volume (sum of face amounts), average qx, average age, and expected amount of claims.
We also compute the amount weekly total amount of claims.
See also `data/all_persons.r`.
## Final cleanup
Some of our clients are located in ZIP3 codes that we cannot deal with for various reasons.
They correspond to the following areas
ZIP3 | Area |
-----|------------|
969 | Guam, Palau, Federated States of Micronesia, Northern Mariana Islands, Marshall Islands |
093 | Military bases in Iraq and Afghanistan |
732 | Not in use |
872 | Not in use |
004 | Not in use |
202 | Washington DC, Government 1 |
753 | Dallas, TX |
772 | Houston, TX |
The final two are problematic since they contained no population in 2010: one is used exclusively by a hospital, and the other is used exclusively by a mall.
Additionally, election data is not available in Washington D.C., so we remove clients located there.
In the end, we have a total of 492 clients to work with.
The data merging is done in the file `processed_data.r` which generates the file `data/processed_data_20_12_23.feather`.
The dependency tree is outlined in the Appendix.
After merging, this gives us a final dataset of 492 clients over 118 weeks ranging from Jan 1st 2019 to June 27th 2021.
We make two separate tibbles.
```{r echo = FALSE}
# Slice is getting masked by xgboost...
slice <- dplyr::slice
```
```{r}
weekly_data <-
read_feather("data/processed_data_20_12_23.feather") %>%
select(-ae_2021, -ae_2020, -ae_2019,
-actual_2021, -actual_2020, -actual_2019, -adverse,
-STATE_NAME, -shrinkage, -dep_var) %>%
arrange(client, date)
yearly_data <-
read_feather("data/processed_data_20_12_23.feather") %>%
group_by(client) %>%
slice(1) %>%
select(-date, -claims, -zip_deaths, -smoothed_ae, -shrunk_ae,
-class, -smoothed_deaths,
-hes, -hes_uns, -str_hes, -ae, -dep_var, -shrinkage, -STATE_NAME, -ihme_deaths)
```
Each row in `yearly_data` corresponds to a client, and it contains the following variables
Variable | Description
---------|------------
`zip3` | ZIP3 code
`client` | client ID
`size` | number of individuals
`volume` | sum of face values
`avg_qx` | average $q_x$
`avg_age` | average age
`per_male` | percentage of males
`per_blue_collar` | percentage of blue collar workers
`expected` | expected yearly amount of claims
`actual_{2021, 2020, 2019}` | actual claims in {2021, 2020, 2019}
`ae_{2021, 2020, 2019}` | actual claims / expected claims in {2021, 2020, 2019}
`nohs` | percentage of zip residents without a high school diploma
`hs` | percentage of zip residents with only a high school diploma
`college` | percentage of zip residents with only a community college or associates degree
`bachelor` | percentage of zip residents with a bachelor's degree
`R_birth` | birthrate in zip
`R_death` | deathrate in zip (pre-covid)
`unemp` | unemployment in zip
`poverty` | percentage of zip residents living in poverty
`per_dem` | percentage of zip residents who voted Democrat in 2020
`svi` | Social Vulnerability Index
`cvac` | CVAC level of concern for vaccine rollout
`income` | median household income in zipcode
`POP` | population in zipcode
`density` | zipcode population density
`adverse` | whether or not ae_2020 > 3
The tibble `weekly_data` contain most of the above variables, but also some that change weekly.
Each row correspond to a pair $(\text{client}, \text{week})$.
We describe the ones not present above
Variable | Description
---------|------------
`date` | the last day of the week (`lubridate::ceiling_date(date, unit = "week")`)
`claims` | claims for that client on that week (\$)
`zip_deaths` | number of deaths that week in the zipcode
`smoothed_ae` | smoothed version of actual weekly AE (see the section on long-term models)
`shrunk_ae` | shrunk version of smoothed weekly AE (see the section on long-term models)
`ae` | actual weekly AE
`ihme_deaths` | IHME Covid death forecasts. **These are only available until Apr 4th 2021, and are set to 0 after this date.**
`hes`, `hes_uns`, `str_hes` | percentage of the zip population that are vaccine hesitant, hesitant or unsure, and strongly hesistan respectively
# Data exploration and motivation
Since the pandemic started, our clients' claims increased dramatically.
In normal times, we expect an Actual-to-Expected ratio close to 1.
As we can see below, this doesn't apply in times of pandemic.
```{r}
yearly_data %>%
ungroup() %>%
transmute(
`2019` = ae_2019 > 1,
`2020` = ae_2020 > 1,
`2021` = ae_2021 > 1) %>%
pivot_longer(`2019`:`2021`, names_to = "year", values_to = "adverse") %>%
mutate(adverse = fct_rev(fct_recode(factor(adverse), `AE > 1` = "TRUE", `AE < 1` = "FALSE"))) %>%
ggplot(aes(x = year, fill = adverse)) + geom_bar() +
labs(x = "Year", y = "Count", fill = "Class", title = "Number of clients experiencing adverse mortality")
```
We plot the magnitude of claims.
Each dot corresponds to a client.
We see that the expected claims look similar to the actual claims in 2019, while things change dramatically in 2020 and 2021.
Note that the vertical axis is logarithmic!
The change in the claims during a pandemic differs by orders of magnitude compared to the expected ones.
```{r}
library(ggbeeswarm)
set.seed(92929292)
yearly_data %>%
ungroup() %>%
select(expected, actual_2019, actual_2020, actual_2021) %>%
rename(actual_Expected = expected) %>%
pivot_longer(everything(), names_to = "Year", values_to = "Claims") %>%
mutate(Year = str_sub(Year, 8)) %>%
filter(Claims > 0) %>%
ggplot(aes(Year, Claims, color = Year)) + scale_y_log10() + geom_beeswarm(size = 0.5, priority = "random") +
guides(color = "none") + labs(title = "Size of claims") +
scale_color_manual(values = c("yellow3", "deepskyblue", "black", "red"))
```
# Long-term model
Our first goal was to create a simple model to classify clients between high risk or low risk.
In this first model, we determine client risk based on AE in 2020, and we will use data available before the pandemic as predictors.
Our first task is to determine what "high risk" and "low risk" mean.
To this extent, we define "AE 2020 > 3" as "high risk", as this is close the the first quartile of the AE in 2020.
```{r}
summary(yearly_data %>% pull(ae_2020))
```
This threshold was used to create the column `adverse` in `yearly_data`.
Thoughout this and following sections, we will be using extensively the `tidymodels` framework. We will explain the commands as they appear.
```{r message = FALSE}
library(tidymodels)
```
## Feature engineering
Our mentor's hypothesis was that the AE for 2019 was not a good predictor for client risk during a pandemic.
To test this hypothesis, we train and test a selection of models, some with 2019 AE as a predictor, and some without.
We start with a recipe, which defines our model formulas and data preprocessing steps.
We remove all categorical predictors and all variables that are not available before 2020.
We also remove the correlated variable `actual_2019`.
We then remove zero-variance predictors and normalize all predictors.
```{r}
with2019 <-
recipe(adverse ~ ., data = yearly_data) %>%
step_rm(all_nominal_predictors()) %>%
step_rm(ae_2020, ae_2021, actual_2019, actual_2020, actual_2021) %>%
step_zv(all_predictors()) %>%
step_normalize(all_predictors())
no2019 <-
with2019 %>%
step_rm(ae_2019)
```
Next, we describe our models using `parsnip` model specifications.
We will try 8 different models: logistic regression, penalized logistic regression (penalty value chosen by initial tuning), random forest, tuned random forest, single layer neural network, RBF support vector machine, polynomial support vector machine, and K nearest neighbors.
```{r}
log_spec <-
logistic_reg() %>%
set_engine("glm") %>%
set_mode("classification")
tuned_log_spec <-
logistic_reg(penalty = 0.00118) %>%
set_engine("glmnet") %>%
set_mode("classification")
forest_spec <-
rand_forest(trees = 1000) %>%
set_mode("classification") %>%
set_engine("ranger", num.threads = 8, importance = "impurity", seed = 123)
tuned_forest_spec <-
rand_forest(trees = 1000, mtry = 12, min_n = 21) %>%
set_mode("classification") %>%
set_engine("ranger", num.threads = 8, importance = "impurity", seed = 123)
sln_spec <-
mlp() %>%
set_engine("nnet") %>%
set_mode("classification")
svm_rbf_spec <-
svm_rbf() %>%
set_engine("kernlab") %>%
set_mode("classification")
svm_poly_spec <-
svm_poly() %>%
set_engine("kernlab") %>%
set_mode("classification")
knn_spec <-
nearest_neighbor() %>%
set_engine("kknn") %>%
set_mode("classification")
```
In `tidymodels`, the combination of a recipe and a model specification is called a **workflow**.
Training a workflow trains both the recipe (i.e. it will learn the scaling and translation parameters for the normalization step) and the underlying model.
When a workflow is used to predict, the trained recipe will automatically be applied to a new set of data, and passed on to the trained model.
We can also combine sets of models and recipes into a `workflowset`.
This will allow us to easily train and test our models on the same dataset.
We first split our clients into training and testing sets.
```{r}
set.seed(30308)
init <- initial_split(yearly_data, strata = adverse)
```
All of our model selection, tuning, etc. will be done using 10-fold CV on the training set.
```{r}
set.seed(30308)
crossval <- vfold_cv(training(init), strata = adverse)
```
Our workflowset will contain the 16 combinations of the 8 model specifications and 2 recipes.
We train each one on the 10 cross-validation splits, and assess the results using the area under the ROC (`roc_auc`).
```{r echo = FALSE}
# masked by fabletools
accuracy <- yardstick::accuracy
```
```{r long_feature_eng, cache = TRUE}
models <- list(Logistic = log_spec,
`Penalized logistic` = tuned_log_spec,
`Random forest` = forest_spec,
`Tuned random forest` = tuned_forest_spec,
`Neural net` = sln_spec,
`RBF SVM` = svm_rbf_spec,
`Polynomial SVM` = svm_poly_spec,
`KNN` = knn_spec)
recipes <- list("with2019ae" = with2019,
"no2019ae" = no2019)
wflows <- workflow_set(recipes, models)
fit_wflows <-
wflows %>%
workflow_map(fn = "fit_resamples",
seed = 30332,
resamples = crossval,
control = control_resamples(save_pred = TRUE),
metrics = metric_set(roc_auc, accuracy))
```
We now look at the results with and without the 2019 AE as a predictor
```{r}
fit_wflows %>%
collect_metrics() %>%
separate(wflow_id, into = c("rec", "mod"), sep = "_", remove = FALSE) %>%
ggplot(aes(x = rec, y = mean, color = mod, group = mod)) +
geom_point() + geom_line() + facet_wrap(~ factor(.metric)) +
labs(color = "Model", x = NULL, y = "Value", title = "Performance of models with/without 2019 data")
```
The performance with 2019 AE as a predictor is equal or worse than not using it.
Thus in the following we use the recipe where 2019 AE is removed.
We note that the above analysis was done with models with default hyperparameters.
It is certainly possible that some methods would have seen benefits from tuning.
## Model selection
With our data preprocessing locked in, we turn to model selection next.
We will look at five models, each with 10 different hyperparameters.
```{r}
tune_log_spec <-
logistic_reg(penalty = tune()) %>%
set_engine("glmnet") %>%
set_mode("classification")
tune_forest_spec <-
rand_forest(trees = 1000, mtry = tune(), min_n = tune()) %>%
set_mode("classification") %>%
set_engine("ranger", num.threads = 8, importance = "impurity", seed = 123)
tune_sln_spec <-
mlp(hidden_units = tune(), penalty = tune(), epochs = tune()) %>%
set_engine("nnet") %>%
set_mode("classification")
tune_svm_rbf_spec <-
svm_rbf(cost = tune(), rbf_sigma = tune(), margin = tune()) %>%
set_engine("kernlab") %>%
set_mode("classification")
tune_knn_spec <-
nearest_neighbor(neighbors = tune(), dist_power = tune()) %>%
set_engine("kknn") %>%
set_mode("classification")
models <- list(`Logistic` = tune_log_spec,
`Random forest` = tune_forest_spec,
`Neural network` = tune_sln_spec,
`SVM RBF` = tune_svm_rbf_spec,
`KNN` = tune_knn_spec)
recipes <- list(no2019)
wflows <- workflow_set(recipes, models)
```
For each model, the 10 tuning parameters will be automatically selected using a latin hypercube. See the documentation of `dials::grid_latin_hypercube` for implementation details.
Again, performance will be evaluated by 10-fold crossvalidation.
```{r long_tune_models, cache = TRUE, collapse = TRUE}
results <-
wflows %>%
workflow_map(resamples = crossval,
grid = 10,
metrics = metric_set(roc_auc, accuracy),
control = control_grid(save_pred = TRUE),
seed = 828282)
```
The results below suggest that the random forest is performing the best, especially in terms of the area under the ROC.
We will thus choose it for further tuning.
```{r}
autoplot(results)
```
## Tuning a random forest
Since we've chosen a random forest, we no longer need to normalize our predictors.
This will make model explanation easier later on.
We wrap the recipe and model specification into a workflow.
```{r}
forest_rec <-
recipe(adverse ~ ., data = yearly_data) %>%
step_rm(all_nominal_predictors()) %>%
step_rm(ae_2020, ae_2021, actual_2019, actual_2020, actual_2021) %>%
step_zv(all_predictors()) %>%
step_rm(ae_2019)
forest_wflow <-
workflow() %>%
add_model(tune_forest_spec) %>%
add_recipe(forest_rec)
```
We have two tunable hyperparameters: `min_n`, the minimal number of datapoints required for a node to split, and `mtry`, the number of randomly selected predictors in each tree.
We fix the number of trees to 1000, and we set the tuning range of `mtry` to be between 1 and 20.
Tuning will happen on a regular, 10 x 10 grid.
```{r}
forest_params <-
forest_wflow %>%
parameters() %>%
update(mtry = mtry(c(1, 20)))
forest_grid <-
grid_regular(forest_params, levels = 10)
```
```{r long_tune_forest, cache = TRUE, collapse = TRUE}
forest_tune <-
forest_wflow %>%
tune_grid(
resamples = crossval,
grid = forest_grid,
metrics = metric_set(roc_auc, accuracy)
)
```
The tuning results are below.
We choose a set of parameters whose `roc_auc` is high. In this case, we choose `mtry = 5`, `min_n = 6`. The command `finalize_workflow` applies these parameters and returns a tuned workflow.
```{r}
autoplot(forest_tune)
best_params <- list(mtry = 5, min_n = 6)
final_forest <-
forest_wflow %>%
finalize_workflow(best_params)
```
## Thresholding
At the moment, our forest classifies each client by predicting the probability of belonging to the "high risk" class. If that probability is greater than 0.5, the final classification will be "high risk", if not, the final classification will be "low risk".
By changing the threshold from 0.5 to something else, we can influence the number of false positives or false negatives. This is important, since false positives and false negatives have different financial impacts for the insurer.
For example, a false positive would unfairly label a customer as high-risk when in reality they are not. Such a misclassification may lead to loss of profitable clients. On the other hand, a false negative might lead to mismanagement of risk due to exessive claims.
We can study the effect of different thresholds using the package `probably`.
For each of our 10 cross-validation sets, we train a random forest using the optimal parameters found above, and predict using 101 threshold values between 0 and 1.
The function `probably::threshold_perf` will compute seveal metrics, but we plot only sensitivity, specificity, and j-index.
These are averaged over the 10 crossvalidation sets.
```{r, message = FALSE}
library(probably)
forest_resamples <-
final_forest %>%
finalize_workflow(best_params) %>%
fit_resamples(
resamples = crossval,
control = control_resamples(save_pred = TRUE)
)
forest_resamples <-
forest_resamples %>%
rowwise() %>%
mutate(thr_perf = list(threshold_perf(.predictions, adverse, `.pred_ae > 3`, thresholds = seq(0.0, 1, by = 0.01))))
my_threshold <- 0.67
forest_resamples %>%
select(thr_perf, id) %>%
unnest(thr_perf) %>%
group_by(.threshold, .metric) %>%
summarize(estimate = mean(.estimate)) %>%
filter(.metric != "distance") %>%
ggplot(aes(x = .threshold, y = estimate, color = .metric)) + geom_line() +
geom_vline(xintercept = my_threshold, linetype = "dashed") +
labs(x = "Threshold", y = "Estimate", color = "Metric", title = "Sensitivity and specificity by threshold")
```
Some expertise and business intuition are required in order to determine the desired threshold value.
Due to a lack of time and resources, we decided to choose a threshold value that would simultaneously optimize for sensitivity and specificity. To that extent, we choose the threshold value of 0.67, corresponding to the dotted line above.
## Final results
With all the parameters chosen, we can finally train our random forest on the whole training set, and test it on the test set. We augment the testing set with our predicted probabilities.
```{r}
trained_forest <-
final_forest %>%
fit(training(init))
thresholded_predictions <-
trained_forest %>%
predict(testing(init), type = "prob") %>%
mutate(class_pred =
make_two_class_pred(
`.pred_ae > 3`,
levels = levels(yearly_data$adverse),
threshold = my_threshold)) %>%
bind_cols(testing(init))
```
We can now compute a confusion matrix and some summary statistics. Note that we have 124 clients in the testing set, of which 74% are high risk (`ae > 3`). This is the No Information Rate. We can see that our model is clearly doing better than just naively guessing.
```{r}
confusion_matrix <-
thresholded_predictions %>%
conf_mat(adverse, class_pred)
confusion_matrix %>% autoplot(type = "heatmap")
confusion_matrix %>% summary()
```
## Model explanation
We pick two specific clients as examples to explain our model result. We choose client 58 who is located in Brooklyn, New York and client 412 who is located in Asheville, North Carolina. The first one faced adverse mortality and the second one didn't.
We load the `DALEX` package to plot break-down plots and to compute SHAP values.
```{r message = FALSE}
library(DALEX)
library(DALEXtra)
```
```{r}
fit_parsnip <- trained_forest %>% extract_fit_parsnip
trained_recipe <- trained_forest %>% extract_recipe
train <- trained_recipe %>% bake(training(init))
test <- trained_recipe %>% bake(testing(init))
```
Convert to an “explainer” object for later plot
```{r message = FALSE, warning = FALSE}
ex <-
explain(
model = fit_parsnip,
data = train)
```
Below, we have the break-down plot of the client located in New York.
```{r}
ex %>%
predict_parts(train %>% slice(343)) %>%
plot(digits = 2, max_features = 5, title = "Client 58, New York, Brooklyn")
```
The following presents the SHAP values of the client located in New York.
```{r shapNY, cache = TRUE}
shap <- predict_parts(explainer = ex,
new_observation = train %>% slice(343),
type = "shap",
B = 25)
```
```{r}
plot(shap, show_boxplots = FALSE, title = "Client 58, New York, Brooklyn")
```
This is the break-down plot of the client located in NC.
```{r}
ex %>%
predict_parts(test %>% slice(80)) %>%
plot(digits = 2, max_features = 5, title = "Client 412, North Carolina, Asheville")
```
And those are the SHAP values of the client located in NC.
```{r shapNC, cache = TRUE}
shap <- predict_parts(explainer = ex,
new_observation = test %>% slice(80),
type = "shap",
B = 25)
```
```{r}
plot(shap, show_boxplots = FALSE, title = "Client 412, North Carolina, Asheville")
```
We can also determine which predictors contributed the most in our model.
```{r}
trained_forest %>%
extract_fit_engine() %>%
importance() %>%
as_tibble_row() %>%
pivot_longer(everything(), names_to = "Variable", values_to = "Importance") %>%
slice_max(Importance, n = 10) %>%
ggplot(aes(y = fct_reorder(factor(Variable), Importance), x = Importance, fill = fct_reorder(factor(Variable), Importance))) +
geom_col() +
scale_fill_brewer(palette = "Spectral") +
guides(fill = "none") + labs(y = "Variable", x = "Importance")
```
# Short-term model
## Introduction
Now that we have introduced the long-term model and presented its results, we can move to the next step: adding time-dependent data. To do this, we will be using `weekly_data` throughout this section.
We recall how we obtained `weekly_data` by describing some of the preprocessing steps in `data/processed_data.r`.
To begin with, we merged the following 4 data sets:
1. `data/deaths_zip3.feather`: daily covid deaths data.
2. `data/simulation_data/all_persons.feather`: a tibble frame created in our data wrangling process, containing simulated data for each participants from our clients.
3. `data/data.feather` : zip3 data created in data wrangling process.
4. `data/2020_12_23/reference_hospitalization_all_locs.csv`: data from IHME as of Dec 23 2020
Next, we need some kind of a rolling count for AE.
We could use the "true" weekly AE for each client, but it turns out that that number is too volatile: there are many weeks without any deaths, which means that any deaths will lead to huge, momentary spikes.
Another quantity that is quite volatile is the weekly COVID death count .
Thus we smooth the volatile quantities by taking a weighted average in the 13 weeks prior. The weights come from a Gaussian distribution, and we weight recent AE numbers higher than older ones.
```{r}
smoother <- function(x) { weighted.mean(x, dnorm(seq(-1, 0, length.out = length(x)), sd = 0.33)) }
sliding_smoother <-
timetk::slidify(smoother, .period = 13, .align = "right")
```
The function `sliding_smoother` takes a vector and outputs a vector of smoothed values.
We add smoothed AE and smoothed weekly zip deaths to the tibble `weekly_data`.
```{r eval = FALSE}
weekly_data <-
weekly_data %>%
group_by(client) %>%
mutate(smoothed_ae = sliding_smoother(ae), smoothed_deaths = sliding_smoother(zip_deaths), .before = size) %>%
drop_na()
```
Then we shrink smoothed ae based on $\log(\text{Volume} \cdot \text{average } q_x)$. This gives us some kind of a measure of client size and mortality. The motivation for this is that small clients that experience adverse mortality are much less impactful as large ones.
We add the shrunk, smoothed AE to `weekly_data`.
```{r eval = FALSE}
client_shrinkage <-
weekly_data %>%
summarize(dep_var = first(volume * avg_qx)) %>%
mutate(shrinkage = rescale(log(dep_var), to = c(0.3, 1)))
weekly_data <-
weekly_data %>%
left_join(client_shrinkage, by = "client") %>%
ungroup() %>%
mutate(shrunk_ae = smoothed_ae * shrinkage, .after = smoothed_ae)
```
In order to choose a threshold for high and low risk classification, we look again at quantiles.
```{r}
weekly_data %>%
ungroup() %>%
group_by(date) %>%
summarize(
`12.5` = quantile(shrunk_ae, 0.125),
`25` = quantile(shrunk_ae, 0.25),
`50` = quantile(shrunk_ae, 0.50)
) %>%
pivot_longer(-date, names_to = "pth", values_to = "shrunk_ae") %>%
ggplot(aes(x = date, y = shrunk_ae, color = pth)) +
geom_line() +
geom_hline(yintercept = 2.5, linetype = "dashed")
```
Based on this, we choose `smoothed shrunk AE > 2.5` as "Adverse", which corresponds to the dotted line above.
With this choice, we have the following proportion of adverse clients over time.
```{r}
weekly_data %>%
group_by(date) %>%
summarize(`Percentage classified Adverse` = sum(class == "Adverse") / n()) %>%
ggplot(aes(x = date, y = `Percentage classified Adverse`)) + geom_line()
```
## Model selection
We first start by dividing our timeline into training and testing sets: we take all the dates before January 1 2021 as our training set and all the dates from January 1 2021 to April 1 2021 as our test set (3 months later). Our goal is to try and use the data from our clients' performance before January 1 to predict their performance after this date.
```{r}
train <-
weekly_data %>%
filter(date <= "2021-01-01")
test <-
weekly_data %>%
filter(date > "2021-01-01" & date <= "2021-04-01")
```
There are two mains things that set this model apart from the long-term model introduced in the first section. First, the AE is updated weekly as opposed to the long-term model where the AE is taken yearly. Second, we are adding weekly deaths as one of the predictors in addition to the variables introduced in the long-term model. Now, that we have a clear understanding of the predictors in the short-term model, the question that arises is how we can use the weekly deaths in the testing time (since such information won't be available for us in the "future"). To solve this issue, we decided to forecast the deaths for this "future" period: so we will use the weekly deaths from March 2020 to January 2021 and forecast the weekly deaths 3 months later. To do so, we will use the ARIMA forecaster.
```{r message = FALSE}
library(fable)
library(tsibble)
```
```{r forecast, cache = TRUE, warning = FALSE}
forecast <-
weekly_data %>%
filter(date >= "2020-03-15" & date <= "2021-01-01") %>%
as_tsibble(index = date, key = client) %>%
model(arima = ARIMA(smoothed_deaths)) %>%
forecast(h = "3 months")
```
We create a new set called `forecasted_test` out of our testing set where we replace `smoothed_deaths` by `forecasted_deaths`.
```{r}
forecasted_test <-
forecast %>%
as_tibble() %>%
select(client, date, .mean) %>%
right_join(test, by = c("client", "date")) %>%
select(-smoothed_deaths) %>%
rename(smoothed_deaths = .mean)
```
We are ready to introduce our modeling strategy.
We first start by introducing a common recipe that we will use for all our models. Our target variable is `class`, we use all the predictors in `weekly_data` except for `client`, `zip3`, `claims`, `smoothed_ae`, `shrunk_ae`, `ae`, `zip_deaths`, `ihme_deaths` and `date.` We normalize all predictors and we apply log to both Volume of the client and Population of the zip code.
```{r}
common_recipe <-
recipe(class ~ ., data = weekly_data) %>%
step_rm(client, zip3, claims, smoothed_ae, shrunk_ae, ae, zip_deaths, ihme_deaths, date) %>%
step_zv(all_predictors()) %>%
step_log(volume, POP) %>%
step_normalize(all_predictors())
```
Now, that we have our recipe, we are ready to try out different models and report the results. Let us introduce the five models and then we will talk a little bit about each one of them.
```{r}
forest_spec <-
rand_forest(trees = 1000) %>%
set_engine("ranger", num.threads = 8, seed = 123456789) %>%
set_mode("classification")
log_spec <-
logistic_reg(
mode = "classification",
engine = "glm")
knn_spec <-
nearest_neighbor() %>%
set_engine("kknn") %>%
set_mode("classification")
sln_spec <-
mlp(activation = "relu", hidden_units = 6, epochs = 100) %>%
set_engine("keras", verbose=0) %>%
set_mode("classification")
bt_spec <- boost_tree(
mode = "classification",
engine = "xgboost",
trees = 100)
```
We use Random Forest (`forest`), Logistic Regression (`log`), Nearest Neighbor (`knn`), Neural Network with single layer (`sln`) and Boosted Trees (`bt`) respectively with default settings. For the Random Forest, we consider 1000 trees and for the Boosted Trees, we take 100 trees. All of these models use different engines introduced in `tidymodels`.
We then create the workflow for the five models mentioned above with the recipe taken to be the "common recipe" and the model taken to be the ones introduced in the previous chunk.
```{r}
bt_wf <-
workflow() %>%
add_recipe(common_recipe) %>%
add_model(bt_spec)
log_wf <-
workflow() %>%
add_recipe(common_recipe) %>%
add_model(log_spec)
forest_wf <-
workflow() %>%
add_recipe(common_recipe) %>%
add_model(forest_spec)
knn_wf <-
workflow() %>%
add_recipe(common_recipe) %>%
add_model(knn_spec)
sln_wf <-
workflow() %>%
add_recipe(common_recipe) %>%
add_model(sln_spec)
```
We can take each of these models and evaluate their performance separately, but we want to find a way where we can compare their performance through time. So, we create a tibble containing the five different workflows, we fit out training set and we predict our `forecasted_test.` For the prediction, we use `class_predict` to come up with a class (this prediction will be used to calculate accuracy, sensitivity and specificity). We also use `prob_predict` to come up with a predicitive probability (used to calculate the `roc_auc`).
```{r Short_model_comp, cache = FALSE, warning = FALSE, message = FALSE}
wflows <- tribble(~wflow,
sln_wf,
knn_wf, log_wf, forest_wf, bt_wf)
wflows <-
wflows %>%
mutate(wflows_fit = map(wflow, ~ fit(.x, train)))
wflows <-
wflows %>%
mutate(
class_predict = map(wflows_fit, ~ predict(.x, forecasted_test)),
prob_predict = map(wflows_fit, ~ predict(.x, forecasted_test, type = "prob")))
```
Now that we have our prediction as a class and as a probability, we are ready to compare the metrics for the five models.
```{r}
wflows %>%
bind_cols(tribble(~id, "Neural Network", "Nearest Neigbor", "Logistic Regression", " Random Forest", "Boosted Trees")) %>%
select(-wflow, -wflows_fit) %>%
mutate(prob_predict = map(prob_predict, ~ bind_cols(.x, test %>% select(date, class)))) %>%
unnest(c(class_predict, prob_predict)) %>%
group_by(id, date) %>%
summarize(
sens = sens_vec(class, .pred_class),
spec = spec_vec(class, .pred_class),
roc_auc = roc_auc_vec(class, .pred_Adverse),
accuracy = accuracy_vec(class, .pred_class), .groups = "keep") %>%
pivot_longer(sens:accuracy, names_to = "metric", values_to = "value") %>%
ungroup() %>%
ggplot(aes(x = date, y = value, color = id)) +
geom_point() +
geom_line() +
facet_wrap( ~ metric)
```
One can wonder how much our models are being affected by the forecasting of deaths. Let's replace `forecasted_test` by `test` and let's see what happens. (So, now actual deaths is used instead of forecasted deaths). We see that the difference is not very big and our forecasting is not affecting the models in a bad way.
```{r}
wflows_cheat <-
wflows %>%
mutate(
class_predict = map(wflows_fit, ~ predict(.x, test)),
prob_predict = map(wflows_fit, ~ predict(.x, test, type = "prob")))
wflows_cheat %>%
bind_cols(tribble(~id, "Neural Network", "Nearest Neighbor", "Logistic Regression", "Random Forest", "Boosted Trees")) %>%
select(-wflow, -wflows_fit) %>%
mutate(prob_predict = map(prob_predict, ~ bind_cols(.x, test %>% select(date, class)))) %>%
unnest(c(class_predict, prob_predict)) %>%
group_by(id, date) %>%
summarize(
sens = sens_vec(class, .pred_class),
spec = spec_vec(class, .pred_class),
roc_auc = roc_auc_vec(class, .pred_Adverse),
accuracy = accuracy_vec(class, .pred_class), .groups = "keep") %>%
pivot_longer(sens:accuracy, names_to = "metric", values_to = "value") %>%
ungroup() %>%
ggplot(aes(x = date, y = value, color = id)) +
geom_point() +
geom_line() +
facet_wrap( ~ metric)
```
## Tuning Boosted Trees Model
Comparing the models above, we can see that the Boosted Trees is the best model. So, we use it for the rest of the project, we tune it, and we report the results.
One of our goals is to have a model that can predict clients it hasn't seen before.
First, we split our clients into training and testing clients.
The training clients are "known"; they will be what the model will be trained on and they represent 75% of our total.
The testing clients are "unknown"; they will represent brand new clients and they represent 25% of our total.