-
Notifications
You must be signed in to change notification settings - Fork 1
/
construct_onlineretail_fixed_pnbd_models.qmd
1175 lines (807 loc) · 28.2 KB
/
construct_onlineretail_fixed_pnbd_models.qmd
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: "Construct Non-Hierarchical P/NBD Model for Online Retail Transaction Data"
author: "Mick Cooney <[email protected]>"
date: "Last updated: `r format(Sys.time(), '%B %d, %Y')`"
editor: source
execute:
message: false
warning: false
error: false
format:
html:
light: superhero
dark: darkly
anchor-sections: true
embed-resources: true
number-sections: true
smooth-scroll: true
toc: true
toc-depth: 3
toc-location: left
code-fold: true
code-summary: "Show code"
---
```{r import_libraries}
#| echo: FALSE
#| message: FALSE
library(conflicted)
library(tidyverse)
library(scales)
library(cowplot)
library(directlabels)
library(magrittr)
library(rlang)
library(lobstr)
library(rsyslog)
library(fs)
library(purrr)
library(furrr)
library(glue)
library(cmdstanr)
library(brms)
library(posterior)
library(bayesplot)
library(tidybayes)
source("lib_utils.R")
source("lib_btyd.R")
conflict_lst <- resolve_conflicts(
c("magrittr", "rlang", "dplyr", "readr", "purrr", "ggplot2", "MASS",
"fitdistrplus")
)
options(
width = 80L,
warn = 1,
mc.cores = parallelly::availableCores()
)
set.seed(42)
stanfit_seed <- 4501
n_sim <- 2000
theme_set(theme_cowplot())
plan(multisession)
```
In this workbook we construct our first hierarchical P/NBD models on the
synthetic data with the longer timeframe.
# Load and Construct Datasets
We start by modelling the P/NBD model using our synthetic datasets before we
try to model real-life data.
## Load Online Retail Data
We now want to load the online retail transaction data.
```{r load_online_retail_data}
#| echo: TRUE
customer_cohortdata_tbl <- read_rds("data/onlineretail_cohort_tbl.rds")
customer_cohortdata_tbl |> glimpse()
customer_transactions_tbl <- read_rds("data/onlineretail_transactions_tbl.rds")
customer_transactions_tbl |> glimpse()
customer_subset_id <- read_rds("data/onlineretail_customer_subset_ids.rds")
customer_subset_id |> glimpse()
```
## Load Derived Data
```{r load_derived_data}
#| echo: TRUE
customer_summarystats_tbl <- read_rds("data/onlineretail_customer_summarystats_tbl.rds")
obs_fitdata_tbl <- read_rds("data/onlineretail_obs_fitdata_tbl.rds")
obs_validdata_tbl <- read_rds("data/onlineretail_obs_validdata_tbl.rds")
customer_fit_stats_tbl <- obs_fitdata_tbl |>
rename(x = tnx_count)
```
## Load Subset Data
We also want to construct our data subsets for the purposes of speeding up our
valuations.
```{r construct_customer_subset_data}
#| echo: TRUE
customer_fit_subset_tbl <- obs_fitdata_tbl |>
filter(customer_id %in% customer_subset_id)
customer_fit_subset_tbl |> glimpse()
customer_valid_subset_tbl <- obs_validdata_tbl |>
filter(customer_id %in% customer_subset_id)
customer_valid_subset_tbl |> glimpse()
```
We now use these datasets to set the start and end dates for our various
validation methods.
```{r set_start_end_dates}
dates_lst <- read_rds("data/onlineretail_simulation_dates.rds")
use_fit_start_date <- dates_lst$use_fit_start_date
use_fit_end_date <- dates_lst$use_fit_end_date
use_valid_start_date <- dates_lst$use_valid_start_date
use_valid_end_date <- dates_lst$use_valid_end_date
```
We now split out the transaction data into fit and validation datasets.
```{r create_customer_transaction_splits}
#| echo: true
customer_fit_transactions_tbl <- customer_transactions_tbl |>
filter(
customer_id %in% customer_subset_id,
tnx_timestamp >= use_fit_start_date,
tnx_timestamp <= use_fit_end_date
)
customer_fit_transactions_tbl |> glimpse()
customer_valid_transactions_tbl <- customer_transactions_tbl |>
filter(
customer_id %in% customer_subset_id,
tnx_timestamp >= use_valid_start_date,
tnx_timestamp <= use_valid_end_date
)
customer_valid_transactions_tbl |> glimpse()
```
Finally, we want to extract the first transaction for each customer, so we
can add this data to assess our models.
```{r extract_customer_first_transaction}
#| echo: true
customer_initial_tnx_tbl <- customer_fit_transactions_tbl |>
slice_min(n = 1, order_by = tnx_timestamp, by = customer_id)
customer_initial_tnx_tbl |> glimpse()
```
We now expand out these initial transactions so that we can append them to
our simulations.
```{r expand_initial_simulation_transactions}
#| echo: true
sim_init_tbl <- customer_initial_tnx_tbl |>
transmute(
customer_id,
draw_id = list(1:n_sim),
tnx_timestamp,
tnx_amount
) |>
unnest(draw_id)
sim_init_tbl |> glimpse()
```
Before we start on that, we set a few parameters for the workbook to organise
our Stan code.
```{r setup_workbook_parameters}
#| echo: TRUE
stan_modeldir <- "stan_models"
stan_codedir <- "stan_code"
```
# Fit First P/NBD Model
We now construct our Stan model and prepare to fit it with our synthetic
dataset.
We also want to set a number of overall parameters for this workbook
To start the fit data, we want to use the 1,000 customers. We also need to
calculate the summary statistics for the validation period.
## Compile and Fit Stan Model
We now compile this model using `CmdStanR`.
```{r compile_pnbd_fixed_stanmodel}
#| echo: TRUE
#| results: "hide"
pnbd_fixed_stanmodel <- cmdstan_model(
"stan_code/pnbd_fixed.stan",
include_paths = stan_codedir,
pedantic = TRUE,
dir = stan_modeldir
)
```
We then use this compiled model with our data to produce a fit of the data.
```{r fit_pnbd_onlineretail_fixed1_stanmodel}
#| echo: TRUE
stan_modelname <- "pnbd_onlineretail_fixed1"
stanfit_seed <- stanfit_seed + 1
stanfit_prefix <- str_c("fit_", stan_modelname)
stanfit_object_file <- glue("data/{stanfit_prefix}_stanfit.rds")
stan_data_lst <- customer_fit_stats_tbl |>
select(customer_id, x, t_x, T_cal) |>
compose_data(
lambda_mn = 0.25,
lambda_cv = 1.00,
mu_mn = 0.10,
mu_cv = 1.00,
)
if(!file_exists(stanfit_object_file)) {
pnbd_onlineretail_fixed1_stanfit <- pnbd_fixed_stanmodel$sample(
data = stan_data_lst,
chains = 4,
iter_warmup = 500,
iter_sampling = 500,
seed = stanfit_seed,
save_warmup = TRUE,
output_dir = stan_modeldir,
output_basename = stanfit_prefix,
)
pnbd_onlineretail_fixed1_stanfit$save_object(stanfit_object_file, compress = "gzip")
} else {
pnbd_onlineretail_fixed1_stanfit <- read_rds(stanfit_object_file)
}
pnbd_onlineretail_fixed1_stanfit$print()
```
We have some basic HMC-based validity statistics we can check.
```{r calculate_pnbd_onlineretail_fixed1_hmc_diagnostics}
#| echo: TRUE
pnbd_onlineretail_fixed1_stanfit$cmdstan_diagnose()
```
## Visual Diagnostics of the Sample Validity
Now that we have a sample from the posterior distribution we need to create a
few different visualisations of the diagnostics.
```{r plot_pnbd_onlineretail_fixed1_lambda_traceplots_nowarmup}
#| echo: TRUE
parameter_subset <- c(
"lambda[1]", "lambda[2]", "lambda[3]", "lambda[4]",
"mu[1]", "mu[2]", "mu[3]", "mu[4]"
)
pnbd_onlineretail_fixed1_stanfit$draws(inc_warmup = FALSE) |>
mcmc_trace(pars = parameter_subset) +
expand_limits(y = 0) +
labs(
x = "Iteration",
y = "Value",
title = "Traceplot of Sample of Lambda and Mu Values"
) +
theme(axis.text.x = element_text(size = 10))
```
We also check $N_{eff}$ as a quick diagnostic of the fit.
```{r plot_pnbd_onlineretail_fixed1_parameter_neffratio}
#| echo: TRUE
pnbd_onlineretail_fixed1_stanfit |>
neff_ratio(pars = c("lambda", "mu")) |>
mcmc_neff() +
ggtitle("Plot of Parameter Effective Sample Sizes")
```
Finally, we want to check out the energy diagnostic, which is often indicative
of problems with the posterior mixing.
```{r plot_pnbd_onlineretail_fixed1_energy}
#| echo: true
pnbd_onlineretail_fixed1_stanfit |>
nuts_params() |>
mcmc_nuts_energy(binwidth = 50)
```
## Assess the Model
As we intend to run the same logic to assess each of our models, we have
combined all this logic into a single function `run_model_assessment`, to
run the simulations and combine the datasets.
```{r run_pnbd_onlineretail_fixed1_assessment}
#| echo: TRUE
pnbd_stanfit <- pnbd_onlineretail_fixed1_stanfit |>
recover_types(customer_fit_stats_tbl)
pnbd_onlineretail_fixed1_assess_data_lst <- run_model_assessment(
model_stanfit = pnbd_stanfit,
insample_tbl = customer_fit_subset_tbl,
fit_label = "pnbd_onlineretail_fixed1",
fit_end_dttm = use_fit_end_date |> as.POSIXct(),
valid_start_dttm = use_valid_start_date |> as.POSIXct(),
valid_end_dttm = use_valid_end_date |> as.POSIXct(),
sim_seed = 1010
)
pnbd_onlineretail_fixed1_assess_data_lst |> glimpse()
```
### Check In-Sample Data Validation
We first check the model against the in-sample data.
```{r run_pnbd_onlineretail_fixed1_fit_assessment}
#| echo: TRUE
simdata_tbl <- pnbd_onlineretail_fixed1_assess_data_lst |>
use_series(model_fit_index_filepath) |>
read_rds() |>
use_series(sim_file) |>
map_dfr(read_rds) |>
select(customer_id, draw_id, sim_data) |>
unnest(sim_data) |>
bind_rows(sim_init_tbl) |>
arrange(customer_id, draw_id, tnx_timestamp)
assess_plots_lst <- create_model_assessment_plots(
obsdata_tbl = customer_fit_transactions_tbl,
simdata_tbl = simdata_tbl
)
assess_plots_lst |> map(print)
```
This fit looks reasonable and appears to capture most of the aspects of the
data used to fit it. Given that this is a synthetic dataset, this is not
surprising, but at least we appreciate that our model is valid.
### Check Out-of-Sample Data Validation
We now repeat for the out-of-sample data.
```{r run_pnbd_onlineretail_fixed1_valid_assessment}
#| echo: TRUE
simdata_tbl <- pnbd_onlineretail_fixed1_assess_data_lst |>
use_series(model_valid_index_filepath) |>
read_rds() |>
use_series(sim_file) |>
map_dfr(read_rds) |>
select(customer_id, draw_id, sim_data) |>
unnest(sim_data) |>
arrange(customer_id, draw_id, tnx_timestamp)
assess_plots_lst <- create_model_assessment_plots(
obsdata_tbl = customer_valid_transactions_tbl,
simdata_tbl = simdata_tbl
)
assess_plots_lst |> map(print)
```
As for our short time frame data, overall our model is working well.
```{r delete_pnbd_onlineretail_fixed1_valid_assessment}
#| echo: false
rm(simdata_tbl)
rm(insample_plots_lst)
rm(outsample_plots_lst)
gc()
```
# Fit Alternate Prior Model.
We want to try an alternate prior model with a smaller co-efficient of variation
to see what impact it has on our procedures.
```{r fit_pnbd_onlineretail_fixed2_stanmodel}
#| echo: TRUE
stan_modelname <- "pnbd_onlineretail_fixed2"
stanfit_seed <- stanfit_seed + 1
stanfit_prefix <- str_c("fit_", stan_modelname)
stanfit_object_file <- glue("data/{stanfit_prefix}_stanfit.rds")
stan_data_lst <- customer_fit_stats_tbl |>
select(customer_id, x, t_x, T_cal) |>
compose_data(
lambda_mn = 0.25,
lambda_cv = 0.50,
mu_mn = 0.10,
mu_cv = 0.50,
)
if(!file_exists(stanfit_object_file)) {
pnbd_onlineretail_fixed2_stanfit <- pnbd_fixed_stanmodel$sample(
data = stan_data_lst,
chains = 4,
iter_warmup = 500,
iter_sampling = 500,
seed = stanfit_seed,
save_warmup = TRUE,
output_dir = stan_modeldir,
output_basename = stanfit_prefix,
)
pnbd_onlineretail_fixed2_stanfit$save_object(stanfit_object_file, compress = "gzip")
} else {
pnbd_onlineretail_fixed2_stanfit <- read_rds(stanfit_object_file)
}
pnbd_onlineretail_fixed2_stanfit$print()
```
We have some basic HMC-based validity statistics we can check.
```{r calculate_pnbd_onlineretail_fixed2_hmc_diagnostics}
#| echo: TRUE
pnbd_onlineretail_fixed2_stanfit$cmdstan_diagnose()
```
## Visual Diagnostics of the Sample Validity
Now that we have a sample from the posterior distribution we need to create a
few different visualisations of the diagnostics.
```{r plot_pnbd_onlineretail_fixed2_lambda_traceplots}
#| echo: TRUE
parameter_subset <- c(
"lambda[1]", "lambda[2]", "lambda[3]", "lambda[4]",
"mu[1]", "mu[2]", "mu[3]", "mu[4]"
)
pnbd_onlineretail_fixed2_stanfit$draws(inc_warmup = FALSE) |>
mcmc_trace(pars = parameter_subset) +
expand_limits(y = 0) +
labs(
x = "Iteration",
y = "Value",
title = "Traceplot of Sample of Lambda and Mu Values"
) +
theme(axis.text.x = element_text(size = 10))
```
We want to check the $N_{eff}$ statistics also.
```{r plot_pnbd_onlineretail_fixed2_parameter_neffratio}
#| echo: TRUE
pnbd_onlineretail_fixed2_stanfit |>
neff_ratio(pars = c("lambda", "mu")) |>
mcmc_neff() +
ggtitle("Plot of Parameter Effective Sample Sizes")
```
Finally, we want to check out the energy diagnostic, which is often indicative
of problems with the posterior mixing.
```{r plot_pnbd_onlineretail_fixed2_energy}
#| echo: true
pnbd_onlineretail_fixed2_stanfit |>
nuts_params() |>
mcmc_nuts_energy(binwidth = 50)
```
## Assess the Model
As we intend to run the same logic to assess each of our models, we have
combined all this logic into a single function `run_model_assessment`, to
run the simulations and combine the datasets.
```{r run_pnbd_onlineretail_fixed2_assessment}
#| echo: TRUE
pnbd_stanfit <- pnbd_onlineretail_fixed2_stanfit |>
recover_types(customer_fit_stats_tbl)
pnbd_onlineretail_fixed2_assess_data_lst <- run_model_assessment(
model_stanfit = pnbd_stanfit,
insample_tbl = customer_fit_subset_tbl,
fit_label = "pnbd_onlineretail_fixed2",
fit_end_dttm = use_fit_end_date |> as.POSIXct(),
valid_start_dttm = use_valid_start_date |> as.POSIXct(),
valid_end_dttm = use_valid_end_date |> as.POSIXct(),
sim_seed = 1020
)
pnbd_onlineretail_fixed2_assess_data_lst |> glimpse()
```
### Check In-Sample Data Validation
We first check the model against the in-sample data.
```{r run_pnbd_onlineretail_fixed2_fit_assessment}
#| echo: TRUE
simdata_tbl <- pnbd_onlineretail_fixed2_assess_data_lst |>
use_series(model_fit_index_filepath) |>
read_rds() |>
use_series(sim_file) |>
map_dfr(read_rds) |>
select(customer_id, draw_id, sim_data) |>
unnest(sim_data) |>
bind_rows(sim_init_tbl) |>
arrange(customer_id, draw_id, tnx_timestamp)
assess_plots_lst <- create_model_assessment_plots(
obsdata_tbl = customer_fit_transactions_tbl,
simdata_tbl = simdata_tbl
)
assess_plots_lst |> map(print)
```
This fit looks reasonable and appears to capture most of the aspects of the
data used to fit it. Given that this is a synthetic dataset, this is not
surprising, but at least we appreciate that our model is valid.
### Check Out-of-Sample Data Validation
We now repeat for the out-of-sample data.
```{r run_pnbd_onlineretail_fixed2_valid_assessment}
#| echo: TRUE
simdata_tbl <- pnbd_onlineretail_fixed2_assess_data_lst |>
use_series(model_valid_index_filepath) |>
read_rds() |>
use_series(sim_file) |>
map_dfr(read_rds) |>
select(customer_id, draw_id, sim_data) |>
unnest(sim_data) |>
arrange(customer_id, draw_id, tnx_timestamp)
assess_plots_lst <- create_model_assessment_plots(
obsdata_tbl = customer_valid_transactions_tbl,
simdata_tbl = simdata_tbl
)
assess_plots_lst |> map(print)
```
```{r delete_pnbd_onlineretail_fixed2_valid_assessment}
#| echo: false
rm(simdata_tbl)
rm(insample_plots_lst)
rm(outsample_plots_lst)
gc()
```
# Fit Tight-Lifetime Model
We now want to try a model where we use priors with a tighter coefficient of
variation for lifetime but keep the CoV for transaction frequency.
```{r fit_pnbd_onlineretail_fixed3_stanmodel}
#| echo: TRUE
stan_modelname <- "pnbd_onlineretail_fixed3"
stanfit_seed <- stanfit_seed + 1
stanfit_prefix <- str_c("fit_", stan_modelname)
stanfit_object_file <- glue("data/{stanfit_prefix}_stanfit.rds")
stan_data_lst <- customer_fit_stats_tbl |>
select(customer_id, x, t_x, T_cal) |>
compose_data(
lambda_mn = 0.25,
lambda_cv = 1.00,
mu_mn = 0.10,
mu_cv = 0.50,
)
if(!file_exists(stanfit_object_file)) {
pnbd_onlineretail_fixed3_stanfit <- pnbd_fixed_stanmodel$sample(
data = stan_data_lst,
chains = 4,
iter_warmup = 500,
iter_sampling = 500,
seed = stanfit_seed,
save_warmup = TRUE,
output_dir = stan_modeldir,
output_basename = stanfit_prefix,
)
pnbd_onlineretail_fixed3_stanfit$save_object(stanfit_object_file, compress = "gzip")
} else {
pnbd_onlineretail_fixed3_stanfit <- read_rds(stanfit_object_file)
}
pnbd_onlineretail_fixed3_stanfit$print()
```
We have some basic HMC-based validity statistics we can check.
```{r calculate_pnbd_onlineretail_fixed3_hmc_diagnostics}
#| echo: TRUE
pnbd_onlineretail_fixed3_stanfit$cmdstan_diagnose()
```
## Visual Diagnostics of the Sample Validity
Now that we have a sample from the posterior distribution we need to create a
few different visualisations of the diagnostics.
```{r plot_pnbd_onlineretail_fixed3_lambda_traceplots}
#| echo: TRUE
parameter_subset <- c(
"lambda[1]", "lambda[2]", "lambda[3]", "lambda[4]",
"mu[1]", "mu[2]", "mu[3]", "mu[4]"
)
pnbd_onlineretail_fixed3_stanfit$draws(inc_warmup = FALSE) |>
mcmc_trace(pars = parameter_subset) +
expand_limits(y = 0) +
labs(
x = "Iteration",
y = "Value",
title = "Traceplot of Sample of Lambda and Mu Values"
) +
theme(axis.text.x = element_text(size = 10))
```
We want to check the $N_{eff}$ statistics also.
```{r plot_pnbd_onlineretail_fixed3_parameter_neffratio}
#| echo: TRUE
pnbd_onlineretail_fixed3_stanfit |>
neff_ratio(pars = c("lambda", "mu")) |>
mcmc_neff() +
ggtitle("Plot of Parameter Effective Sample Sizes")
```
Finally, we want to check out the energy diagnostic, which is often indicative
of problems with the posterior mixing.
```{r plot_pnbd_onlineretail_fixed3_energy}
#| echo: true
pnbd_onlineretail_fixed3_stanfit |>
nuts_params() |>
mcmc_nuts_energy(binwidth = 50)
```
## Assess the Model
As we intend to run the same logic to assess each of our models, we have
combined all this logic into a single function `run_model_assessment`, to
run the simulations and combine the datasets.
```{r run_pnbd_onlineretail_fixed3_assessment}
#| echo: TRUE
pnbd_stanfit <- pnbd_onlineretail_fixed3_stanfit |>
recover_types(customer_fit_stats_tbl)
pnbd_onlineretail_fixed3_assess_data_lst <- run_model_assessment(
model_stanfit = pnbd_stanfit,
insample_tbl = customer_fit_subset_tbl,
fit_label = "pnbd_onlineretail_fixed3",
fit_end_dttm = use_fit_end_date |> as.POSIXct(),
valid_start_dttm = use_valid_start_date |> as.POSIXct(),
valid_end_dttm = use_valid_end_date |> as.POSIXct(),
sim_seed = 1030
)
pnbd_onlineretail_fixed3_assess_data_lst |> glimpse()
```
### Check In-Sample Data Validation
We first check the model against the in-sample data.
```{r run_pnbd_onlineretail_fixed3_fit_assessment}
#| echo: TRUE
simdata_tbl <- pnbd_onlineretail_fixed3_assess_data_lst |>
use_series(model_fit_index_filepath) |>
read_rds() |>
use_series(sim_file) |>
map_dfr(read_rds) |>
select(customer_id, draw_id, sim_data) |>
unnest(sim_data) |>
bind_rows(sim_init_tbl) |>
arrange(customer_id, draw_id, tnx_timestamp)
assess_plots_lst <- create_model_assessment_plots(
obsdata_tbl = customer_fit_transactions_tbl,
simdata_tbl = simdata_tbl
)
assess_plots_lst |> map(print)
```
This fit looks reasonable and appears to capture most of the aspects of the
data used to fit it. Given that this is a synthetic dataset, this is not
surprising, but at least we appreciate that our model is valid.
### Check Out-of-Sample Data Validation
We now repeat for the out-of-sample data.
```{r run_pnbd_onlineretail_fixed3_valid_assessment}
#| echo: TRUE
simdata_tbl <- pnbd_onlineretail_fixed3_assess_data_lst |>
use_series(model_valid_index_filepath) |>
read_rds() |>
use_series(sim_file) |>
map_dfr(read_rds) |>
select(customer_id, draw_id, sim_data) |>
unnest(sim_data) |>
arrange(customer_id, draw_id, tnx_timestamp)
assess_plots_lst <- create_model_assessment_plots(
obsdata_tbl = customer_valid_transactions_tbl,
simdata_tbl = simdata_tbl
)
assess_plots_lst |> map(print)
```
```{r delete_pnbd_onlineretail_fixed3_valid_assessment}
#| echo: false
rm(simdata_tbl)
rm(insample_plots_lst)
rm(outsample_plots_lst)
gc()
```
# Fit Narrow-Short-Lifetime Model
We now want to try a model where we use priors with a tighter coefficient of
variation for lifetime but keep the CoV for transaction frequency.
```{r fit_pnbd_onlineretail_fixed4_stanmodel}
#| echo: TRUE
stan_modelname <- "pnbd_onlineretail_fixed4"
stanfit_seed <- stanfit_seed + 1
stanfit_prefix <- str_c("fit_", stan_modelname)
stanfit_object_file <- glue("data/{stanfit_prefix}_stanfit.rds")
stan_data_lst <- customer_fit_stats_tbl |>
select(customer_id, x, t_x, T_cal) |>
compose_data(
lambda_mn = 0.25,
lambda_cv = 1.00,
mu_mn = 0.20,
mu_cv = 0.30,
)
if(!file_exists(stanfit_object_file)) {
pnbd_onlineretail_fixed4_stanfit <- pnbd_fixed_stanmodel$sample(
data = stan_data_lst,
chains = 4,
iter_warmup = 500,
iter_sampling = 500,
seed = stanfit_seed,
save_warmup = TRUE,
output_dir = stan_modeldir,
output_basename = stanfit_prefix,
)
pnbd_onlineretail_fixed4_stanfit$save_object(stanfit_object_file, compress = "gzip")
} else {
pnbd_onlineretail_fixed4_stanfit <- read_rds(stanfit_object_file)
}
pnbd_onlineretail_fixed4_stanfit$print()
```
We have some basic HMC-based validity statistics we can check.
```{r calculate_pnbd_onlineretail_fixed4_hmc_diagnostics}
#| echo: TRUE
pnbd_onlineretail_fixed4_stanfit$cmdstan_diagnose()
```
## Visual Diagnostics of the Sample Validity
Now that we have a sample from the posterior distribution we need to create a
few different visualisations of the diagnostics.
```{r plot_pnbd_onlineretail_fixed4_lambda_traceplots}
#| echo: TRUE
parameter_subset <- c(
"lambda[1]", "lambda[2]", "lambda[3]", "lambda[4]",
"mu[1]", "mu[2]", "mu[3]", "mu[4]"
)
pnbd_onlineretail_fixed4_stanfit$draws(inc_warmup = FALSE) |>
mcmc_trace(pars = parameter_subset) +
expand_limits(y = 0) +
labs(
x = "Iteration",
y = "Value",
title = "Traceplot of Sample of Lambda and Mu Values"
) +
theme(axis.text.x = element_text(size = 10))
```
We want to check the $N_{eff}$ statistics also.
```{r plot_pnbd_onlineretail_fixed4_parameter_neffratio}
#| echo: TRUE
pnbd_onlineretail_fixed4_stanfit |>
neff_ratio(pars = c("lambda", "mu")) |>
mcmc_neff() +
ggtitle("Plot of Parameter Effective Sample Sizes")
```
Finally, we want to check out the energy diagnostic, which is often indicative
of problems with the posterior mixing.
```{r plot_pnbd_onlineretail_fixed4_energy}
#| echo: true
pnbd_onlineretail_fixed4_stanfit |>
nuts_params() |>
mcmc_nuts_energy(binwidth = 50)
```
## Assess the Model
As we intend to run the same logic to assess each of our models, we have
combined all this logic into a single function `run_model_assessment`, to
run the simulations and combine the datasets.
```{r run_pnbd_onlineretail_fixed4_assessment}
#| echo: TRUE
pnbd_stanfit <- pnbd_onlineretail_fixed4_stanfit |>
recover_types(customer_fit_stats_tbl)
pnbd_onlineretail_fixed4_assess_data_lst <- run_model_assessment(
model_stanfit = pnbd_stanfit,
insample_tbl = customer_fit_subset_tbl,
fit_label = "pnbd_onlineretail_fixed4",
fit_end_dttm = use_fit_end_date |> as.POSIXct(),
valid_start_dttm = use_valid_start_date |> as.POSIXct(),
valid_end_dttm = use_valid_end_date |> as.POSIXct(),
sim_seed = 1040
)
pnbd_onlineretail_fixed4_assess_data_lst |> glimpse()
```
### Check In-Sample Data Validation
We first check the model against the in-sample data.