-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBG-NBD-Model-Stan.qmd
1662 lines (1318 loc) · 60.1 KB
/
BG-NBD-Model-Stan.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: BG/NBD Model - Stan Implementation
author: Abdullah Mahmood
date: last-modified
format:
html:
theme: cosmo
highlight-style: atom-one
mainfont: Palatino
fontcolor: black
monobackgroundcolor: white
monofont: Menlo, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace
fontsize: 13pt
linestretch: 1.4
toc: true
toc-location: right
toc-depth: 4
code-fold: true
code-copy: true
cap-location: bottom
format-links: false
embed-resources: true
anchor-sections: true
code-links:
- text: GitHub Repo
icon: github
href: https://github.com/abdullahau/customer-analytics/
- text: Quarto Markdown
icon: file-code
href: https://github.com/abdullahau/customer-analytics/blob/main/BG-NBD-Model-Stan.qmd
html-math-method:
method: mathjax
url: https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
---
In this notebook we show how to fit a BG/NBD model in Stan. We compare the results with the [`lifetimes`](https://github.com/CamDavidsonPilon/lifetimes) package. The model is presented in the paper: Fader, P. S., Hardie, B. G., & Lee, K. L. (2005). [“Counting your customers” the easy way: An alternative to the Pareto/NBD model. Marketing science, 24(2), 275-284.](http://www.brucehardie.com/papers/bgnbd_2004-04-20.pdf)
## Introduction
Faced with a database containing information on the *frequency* and *timing of transactions* for a list of customers, it is natural to try to make forecasts about future purchasing. These projections often range from **aggregate sales trajectories** (e.g., for the next 52 weeks), to **individual-level conditional expectations** (i.e., the best guess about a particular customer’s future purchasing, given information about his past behavior). The Pareto/NBD is robust model used for this purpose. It was introduced in “Counting Your Customers” framework originally proposed by Schmittlein, Morrison, and Colombo (1987), hereafter SMC. This model describes repeat-buying behavior in settings where customer “dropout” is unobserved: it assumes that customers buy at a steady rate (albeit in a stochastic manner) for a period of time, and then become inactive. More specifically, time to “dropout” is modeled using the **Pareto (exponential-gamma mixture) timing model**, and repeat-buying behavior while active is modeled using the **NBD (Poisson-gamma mixture) counting model**.
In this notebook, we implement the **beta-geometric/negative binomial distribution** (BG/NBD), which represents a slight variation in the behavioral "story" that lies at the heart of SMC's original work, but it is vastly easier to implement. The model parameters can be obtained quite easily using Python and Stan, with no appreciable loss in the model's ability to fit or predict customer purchasing patterns. We will introduce the BG/NBD model from first principles, and present the expressions required for making individual-level statements about future buying behavior.
Before developing the BG/NBD model, we briefly review the Pareto/NBD model. Then we outline the assumptions of the BG/NBD model, deriving the key expressions at the individual-level, and for a randomly-chosen individual.
### Pareto/NBD
The Pareto/NBD model is based on five assumptions:
1. While active, the number of transactions made by a customer in a time period of length $t$ is distributed Poisson with **transaction rate** $\lambda_t$.
$$
x \sim \text{Poisson}(\lambda)
$$
2. Heterogeneity in transaction rates across customers follows a gamma distribution with shape parameter $r$ and scale parameter $\alpha$.
$$
\lambda \sim \text{Gamma}(r, \alpha)
$$
3. Each customer has an unobserved "lifetime" of length $\tau$. This point at which the customer becomes inactive is distributed exponential with **dropout rate** $\mu$.
$$
\tau \sim \text{Exponential}(\mu)
$$
4. Heterogeneity in dropout rates across customers follows a gamma distribution with shape parameter $s$ and scale parameter $\beta$.
$$
\mu \sim \text{Gamma}(s, \beta)
$$
5. The transaction rate $\lambda$ and the dropout rate $\mu$ vary independently across customers.
The Pareto/NBD (and, as we will see shortly, the BG/NBD ) requires only two pieces of information about each customer's past purchasing history: his "recency" (when his last transaction occurred) and "frequency" (how many transactions he made in a specified time period). The notation used to represent this information is $\left(X=x, t_{x}, T\right)$, where $x$ is the number of transactions observed in the time period $(0, T]$ and $t_{x}\left(0<t_{x} \leq T\right)$ is the time of the last transaction. Using these two key summary statistics, SMC derive expressions for a number of managerially relevant quantities, such as:
- $E[X(t)]$, the **expected number of transactions in a time period** of length $t$, which is central to computing the expected transaction volume for the whole customer base over time.
- $P(X(t)=x)$, the probability of observing $x$ transactions in a time period of length $t$.
- $E\left(Y(t) \mid X=x, t_{x}, T\right)$, the expected number of transactions in the period $(T, T+t]$ for an individual with observed behavior ( $X=x, t_{x}, T$ ).
The likelihood function associated with the Pareto/NBD model is quite complex, involving numerous evaluations of the Gaussian hypergeometric function. Multiple evaluations of the Gaussian hypergeometric are very demanding from a computational standpoint. Furthermore, the precision of some numerical procedures used to evaluate this function can vary substantially over the parameter space; this can cause major problems for numerical optimization routines as they search for the maximum of the likelihood function. In contrast, the BG/NBD model, can be implemented very quickly and efficiently via MLE and MCMC.
### BG/NBD Assumptions
Most aspects of the BG/NBD model directly mirror those of the Pareto/NBD. The only difference lies in the story being told about how/when customers become inactive. The Pareto timing model assumes that dropout can occur at any point in time, independent of the occurrence of actual purchases. If we assume instead that dropout occurs immediately after a purchase, we can model this process using the beta-geometric (BG) model.
More formally, the BG/NBD model is based on the following five assumptions (the first two of which are identical to the corresponding Pareto/NBD assumptions):
1. While active, the number of transactions made by a customer follows a Poisson process with transaction rate $\lambda$. This is equivalent to assuming that the time between transactions is distributed exponential with transaction rate $\lambda$, i.e.,
$$
f\left(t_{j} \mid t_{j-1} ; \lambda\right)=\lambda e^{-\lambda\left(t_{j}-t_{j-1}\right)}, \quad t_{j}>t_{j-1} \geq 0
$$
$$
\text{"Wait"} \sim \text{Exponential}(\lambda)
$$
2. Heterogeneity in $\lambda$ follows a gamma distribution with pdf
$$
\begin{equation*}
f(\lambda \mid r, \alpha)=\frac{\alpha^{r} \lambda^{r-1} e^{-\lambda \alpha}}{\Gamma(r)}, \quad \lambda>0
\end{equation*}
$$
$$
\lambda \sim \text{Gamma}(r,\alpha)
$$
3. After any transaction, a customer becomes inactive with probability $p$. Therefore the point at which the customer "drops out" is distributed across transactions according to a (shifted) geometric distribution with pmf
$$
P(\text { inactive immediately after } j \text { th transaction })=p(1-p)^{j-1}, \quad j=1,2,3, \ldots
$$
$$
\text{"Drop Out"} \sim \text{Bernoulli}(p)
$$
4. Heterogeneity in $p$ follows a beta distribution with pdf
$$
\begin{equation*}
f(p \mid a, b)=\frac{p^{a-1}(1-p)^{b-1}}{B(a, b)}, \quad 0 \leq p \leq 1
\end{equation*}
$$
where $B(a, b)$ is the beta function, which can be expressed in terms of gamma functions: $B(a, b)=\Gamma(a) \Gamma(b) / \Gamma(a+b)$.
$$
p \sim \text{Beta}(a, b)
$$
5. The transaction rate $\lambda$ and the dropout probability $p$ vary independently across customers.
### Model Development at the Individual Level
#### Derivation of the Likelihood Function
Consider a customer who had $x$ transactions in the period $(0, T]$ with the transactions occurring at $t_{1}, t_{2}, \ldots, t_{x}$ :
{fig-align="center" width="342"}
We derive the individual-level likelihood function in the following manner:
- the likelihood of the first transaction occurring at $t_{1}$ is a standard exponential likelihood component, which equals $\lambda e^{-\lambda t_{1}}$.
- the likelihood of the second transaction occurring at $t_{2}$ is the probability of remaining active at $t_{1}$ times the standard exponential likelihood component, which equals $(1-p) \lambda e^{-\lambda\left(t_{2}-t_{1}\right)}$.
- the likelihood of the $x$ th transaction occurring at $t_{x}$ is the probability of remaining active at $t_{x-1}$ times the standard exponential likelihood component, which equals ( $1-$ p) $\lambda e^{-\lambda\left(t_{x}-t_{x-1}\right)}$.
- Finally, the likelihood of observing zero purchases in $\left(t_{x}, T\right]$ is the probability the customer became inactive at $t_{x}$, plus the probability he remained active but made no purchases in this interval, which equals $p+(1-p) e^{-\lambda\left(T-t_{x}\right)}$.
Therefore,
$$
\begin{aligned}
L\left(\lambda, p \mid t_{1}, t_{2}, \ldots, t_{x}, T\right) & =\lambda e^{-\lambda t_{1}}(1-p) \lambda e^{-\lambda\left(t_{2}-t_{1}\right)} \cdots(1-p) \lambda e^{-\lambda\left(t_{x}-t_{x-1}\right)}\left\{p+(1-p) e^{-\lambda\left(T-t_{x}\right)}\right\} \\
& =p(1-p)^{x-1} \lambda^{x} e^{-\lambda t_{x}}+(1-p)^{x} \lambda^{x} e^{-\lambda T}
\end{aligned}
$$
As pointed out earlier for the Pareto/NBD, note that information on the timing of the $x$ transactions is not required; a sufficient summary of the customer's purchase history is $\left(X=x, t_{x}, T\right)$.
Similar to SMC, we assume that all customers are active at the beginning of the observation period; therefore the likelihood function for a customer making 0 purchases in the interval $(0, T]$ is the standard exponential survival function:
$$
L(\lambda \mid X=0, T)=e^{-\lambda T}
$$
Thus we can write the individual-level likelihood function as
$$
\begin{equation*}
L(\lambda, p \mid X=x, T)=(1-p)^{x} \lambda^{x} e^{-\lambda T}+\delta_{x>0} p(1-p)^{x-1} \lambda^{x} e^{-\lambda t_{x}}
\end{equation*}
$$
where $\delta_{x>0}=1$ if $x>0,0$ otherwise.
#### Derivation of $P(X(t)=x)$
Let the random variable $X(t)$ denote the number of transactions occurring in a time period of length $t$ (with a time origin of 0 ). To derive an expression for the $P(X(t)=x)$, we recall the fundamental relationship between inter-event times and the number of events: $X(t) \geq x \Leftrightarrow$ $T_{x} \leq t$ where $T_{x}$ is the random variable denoting the time of the $x$ th transaction. Given our assumption regarding the nature of the dropout process,
$$
\begin{align*}
P(X(t)=x)=& P \text{(active after } x \text{th purchase}) \\
&\cdot P\left(T_{x} \leq t \text { and } T_{x+1}>t\right) +\delta_{x>0} \\
&\cdot P(\text { becomes inactive after } x \text { th purchase }) \\
&\cdot P\left(T_{x} \leq t\right)
\end{align*}
$$ {#eq-numtrans}
Given the assumption that the time between transactions is characterized by the exponential distribution, $P\left(T_{x} \leq t\right.$ and $\left.T_{x+1}>t\right)$ is simply the Poisson probability that $X(t)=x$, and $P\left(T_{x} \leq t\right)$ is the Erlang- $x$ cdf. Therefore
$$
\begin{equation*}
P(X(t)=x \mid \lambda, p)=(1-p)^{x} \frac{(\lambda t)^{x} e^{-\lambda t}}{x!}+\delta_{x>0} p(1-p)^{x-1}\cdot\left[1-e^{-\lambda t} \sum_{j=0}^{x-1} \frac{(\lambda t)^{j}}{j!}\right]
\end{equation*}
$$ {#eq-numtrans2}
#### Derivation of $E[X(t)]$
Given that the number of transactions follows a Poisson process, $E[X(t)]$ is simply $\lambda t$ if the customer is active at $t$. For a customer who becomes inactive at $\tau \leq t$, the expected number of transactions in the period $(0, \tau]$ is $\lambda \tau$.
But what is the likelihood that a customer becomes inactive at $\tau$ ? Conditional on $\lambda$ and $p$,
$$
\begin{aligned}
P(\tau>t)=P(\text { active at } t \mid \lambda, p) & =\sum_{j=0}^{\infty}(1-p)^{j} \frac{(\lambda t)^{j} e^{-\lambda t}}{j!} \\
& =e^{-\lambda p t}
\end{aligned}
$$
This implies that the pdf of the dropout time is given by $g(\tau \mid \lambda, p)=\lambda p e^{-\lambda p \tau}$. (Note that this takes on an exponential form. But it features an explicit association with the transaction rate $\lambda$, in contrast with the Pareto/NBD, which has an exponential dropout process that is independent of the transaction rate.) It follows that the expected number of transactions in a time period of length $t$ is given by
$$
\begin{align*}
E(X(t) \mid \lambda, p) & =\lambda t \cdot P(\tau>t)+\int_{0}^{t} \lambda \tau g(\tau \mid \lambda, p) d \tau \\
& =\frac{1}{p}-\frac{1}{p} e^{-\lambda p t}
\end{align*}
$$
### Model Development for a Randomly-Chosen Individual
All the expressions developed above are conditional on the transaction rate $\lambda$ and the dropout probability $p$, both of which are unobserved. To derive the equivalent expressions for a randomly chosen customer, we take the expectation of the individual-level result over the mixing distributions for $\lambda$ and $p$, as given in (1) and (2). This yields the follow results.
- Taking the expectation of (3) over the distribution of $\lambda$ and $p$ results in the following expression for the likelihood function for a randomly-chosen customer with purchase history $\left(X=x, t_{x}, T\right):$
$$
\begin{align*}
L\left(r, \alpha, a, b \mid X=x, t_{x}, T\right)&=\frac{B(a, b+x)}{B(a, b)} \frac{\Gamma(r+x) \alpha^{r}}{\Gamma(r)(\alpha+T)^{r+x}} \\
&+\delta_{x>0} \frac{B(a+1, b+x-1)}{B(a, b)} \frac{\Gamma(r+x) \alpha^{r}}{\Gamma(r)\left(\alpha+t_{x}\right)^{r+x}}
\end{align*}
$$
The four BG/NBD model parameters $(r, \alpha, a, b)$ can be estimated via the method of maximum likelihood in the following manner. Suppose we have a sample of $N$ customers, where customer $i$ had $X_{i}=x_{i}$ transactions in the period $(0, T_{i}]$, with the last transaction occurring at $t_{x_{i}}$. The sample log-likelihood function given by is
$$
\begin{equation*}
L L(r, \alpha, a, b)=\sum_{i=1}^{N} \ln \left[L\left(r, \alpha, a, b \mid X_{i}=x_{i}, t_{x_{i}}, T_{i}\right)\right]
\end{equation*}
$$
This can be maximized using standard numerical optimization routines.
- Taking the expectation of (4) over the distribution of $\lambda$ and $p$ results in the following expression for the probability of observing $x$ purchases in a time period of length $t$ :
$$
\begin{align*}
P(X(t)= x \mid r, \alpha, a, b) &=\frac{B(a, b+x)}{B(a, b)} \frac{\Gamma(r+x)}{\Gamma(r) x!}\left(\frac{\alpha}{\alpha+t}\right)^{r}\left(\frac{t}{\alpha+t}\right)^{x} \\
&+\delta_{x>0} \frac{B(a+1, b+x-1)}{B(a, b)} \\
&\cdot\left[1-\left(\frac{\alpha}{\alpha+t}\right)^{r}\left\{\sum_{j=0}^{x-1} \frac{(\Gamma(r+j)}{\Gamma(r) j!}\left(\frac{t}{\alpha+t}\right)^{j}\right\}\right]
\end{align*}
$$ {#eq-numtrans3}
- Finally, taking the expectation of (5) over the distribution of $\lambda$ and $p$ results in the following expression for the expected number of purchases in a time period of length $t$ :
$$
\begin{equation*}
E(X(t) \mid r, \alpha, a, b)=\frac{a+b-1}{a-1}\left[1-\left(\frac{\alpha}{\alpha+t}\right)^{r}{ }_{2} F_{1}\left(r, b ; a+b-1 ; \frac{t}{\alpha+t}\right)\right]
\end{equation*}
$$
where ${ }_{2} F_{1}(\cdot)$ is the Gaussian hypergeometric function. (See the Appendix for details of the derivation.)
Note that this final expression requires a single evaluation of the Gaussian hypergeometric function. But it is important to emphasize that this expectation is only used after the likelihood function has been maximized. A single evaluation of the Gaussian hypergeometric function for a given set of parameters is relatively straightforward, and can be closely approximated with a polynomial series, even in a modeling environment such as Microsoft Excel.
In order for the BG/NBD model to be of use in a forward-looking customer-base analysis, we need to obtain an expression for the expected number of transactions in a future period of length $t$ for an individual with past observed behavior $\left(X=x, t_{x}, T\right)$. We provide a careful derivation in the Appendix, but here is the key expression:
$$
\begin{align*}
& E\left(Y(t) \mid X=x, t_{x}, T, r, \alpha, a, b\right)= \\
& \qquad \frac{\frac{a+b+x-1}{a-1}\left[1-\left(\frac{\alpha+T}{\alpha+T+t}\right)^{r+x}{ }_{2} F_{1}\left(r+x, b+x ; a+b+x-1 ; \frac{t}{\alpha+T+t}\right)\right]}{1+\delta_{x>0} \frac{a}{b+x-1}\left(\frac{\alpha+T}{\alpha+t_{x}}\right)^{r+x}}
\end{align*}
$$
Once again, this expectation requires a single evaluation of the Gaussian hypergeometric function for any customer of interest, but this is not a burdensome task. The remainder of the expression is simple arithmetic.
Maximum likelihood estimates (MLE) of the model parameters ($r$, $\alpha$, $a$, $b$) are obtained by maximizing the log-likelihood function given in @eq-loglikelihood above. Standard numerical optimization methods are employed, using the SciPy minimize and Stan's optimize method, to obtain the parameter estimates. To implement the model in SciPy, we rewrite the log-likelihood function, @eq-loglikelihood, as
$$
L(r, \alpha, a, b | X = x, t_x, T) = A_1 \cdot A_2 \cdot (A_3 + \delta_{x > 0} A_4)
$$
where
$$
A_1 = \frac{\Gamma(r + x)\alpha^r}{\Gamma(r)} \quad A_2 = \frac{\Gamma(a + b)\Gamma(b + x)}{\Gamma(b)\Gamma(a + b + x)}
$$
$$
A_3 = \left( \frac{1}{\alpha + T} \right)^{r + x} \quad A_4 = \left( \frac{a}{b + x - 1} \right) \left( \frac{1}{\alpha + t_x} \right)^{r + x}
$$
### Imports
#### Packages
```{python}
from utils import CDNOW, Stan, StanQuap
from scipy.optimize import minimize
import arviz as az
import polars as pl
import numpy as np
import matplotlib.pyplot as plt
%config InlineBackend.figure_formats = ['svg']
```
#### Data
```{python}
# | code-fold: false
data = CDNOW(master=False, calib_p=273) # 39 week calibration period
rfm_data = data.rfm_summary().select("P1X", "t_x", "T").collect().to_numpy()
p1x, t_x, T = rfm_data[:, 0], rfm_data[:, 1], rfm_data[:, 2]
```
Recall from the paper the following definitions:
- `p1x` represents the number of repeat purchases the customer has made. This means that it’s one less than the total number of purchases. This is actually slightly wrong. It’s the count of time periods the customer had a purchase in. So if using days as units, then it’s the count of days the customer had a purchase on.
- `T` represents the age of the customer in whatever time units chosen (weekly, in the above dataset). This is equal to the duration between a customer’s first purchase and the end of the period under study.
- `t_x` represents the age of the customer when they made their most recent purchases. This is equal to the duration between a customer’s first purchase and their latest purchase. (Thus if they have made only 1 purchase, the recency is 0.)
## Model Specification
The BG/NBD model is a probabilistic model that describes the buying behavior of a customer in the non-contractual setting. It is based on the following assumptions for each customer:
### Frequency Process
1. While active, the time between transactions is distributed exponential with transaction rate, i.e.
$$
f(t_{j} \mid t_{j-1}; \lambda) = \lambda \exp(-\lambda (t_{j} - t_{j - 1})), \quad t_{j} \geq t_{j - 1} \geq 0
$$
2. Heterogeneity in $\lambda$ follows a gamma distribution with pdf
$$
f(\lambda \mid r, \alpha) = \frac{\alpha^{r}\lambda^{r - 1}\exp(-\lambda \alpha)}{\Gamma(r)}, \quad \\lambda > 0
$$
### Dropout Process
3. After any transaction, a customer becomes inactive with probability $p$.
4. Heterogeneity in $p$ follows a beta distribution with pdf
$$
f(p \mid a, b) = \frac{\Gamma(a + b)}{\Gamma(a) \Gamma(b)} p^{a - 1}(1 - p)^{b - 1}, \quad 0 \leq p \leq 1
$$
5. The transaction rate $\lambda$ and the dropout probability $p$ vary independently across customers.
Instead of estimating $\lambda$ and $p$ for each specific customer, we do it for a randomly chosen customer, i.e. we work with the expected values of the parameters. Hence, we are interesting in finding the posterior distribution of the parameters $r$, $\alpha$, $a$, and $b$.
## Analytical MLE
Let us implement the standard approach highlighted in the paper and find the parameters $r, \alpha, a, \text{ and } b$ that maximize the posterior log-likelihood function.
### Standard SciPy Implementation
```{python}
import numpy as np
from scipy.special import gammaln, hyp2f1, gamma, factorial
def bgnbd_ll(x, p1x, t_x, T):
r, alpha, a, b = x
# Logarithm calculations with numerical stability
log_alpha = np.log(
np.clip(alpha, 1e-10, None)
) # Avoid log(0) by clipping to a small value
log_alpha_t_x = np.log(np.clip(alpha + t_x, 1e-10, None))
# Components of the log-likelihood
D_1 = (
gammaln(r + p1x)
- gammaln(r)
+ gammaln(a + b)
+ gammaln(b + p1x)
- gammaln(b)
- gammaln(a + b + p1x)
)
D_2 = r * log_alpha - (r + p1x) * log_alpha_t_x
C_3 = ((alpha + t_x) / (alpha + T)) ** (r + p1x)
C_4 = a / (b + p1x - 1)
# Handle cases where p1x > 0 and apply log to valid values
log_term = np.log(np.clip(C_3 + C_4, 1e-10, None))
result = D_1 + D_2 + np.where(p1x > 0, log_term, np.log(np.clip(C_3, 1e-10, None)))
return -np.sum(result)
def bgnbd_est():
guess = {"r": 0.01, "alpha": 0.01, "a": 0.01, "b": 0.01}
# Bounds for the optimization
bnds = [(1e-6, np.inf) for _ in range(4)]
# Optimization using minimize
return minimize(
bgnbd_ll, x0=list(guess.values()), method="BFGS", args=(p1x, t_x, T)
)
result = bgnbd_est()
r, alpha, a, b = result.x
ll = result.fun
print(
f"""r = {r:0.4f}
α = {alpha:0.4f}
a = {a:0.4f}
b = {b:0.4f}
Log-Likelihood = {-ll:0.4f}"""
)
index = ["r", "α", "a", "b"]
scipy_params = result.x
var_mat = result.hess_inv
se = np.sqrt(np.diag(var_mat))
plo = scipy_params - 1.96 * se
phi = scipy_params + 1.96 * se
pl.DataFrame(
{
"Parameter": index,
"Coef": scipy_params,
"SE (Coef)": se,
"5.5%": plo,
"94.5%": phi,
}
)
```
### **Cameron Davidson-Pilon's `lifetimes`** Implementation
Source: [BetaGeoFitter](https://github.com/CamDavidsonPilon/lifetimes/blob/master/lifetimes/fitters/beta_geo_fitter.py), [fit function](https://github.com/CamDavidsonPilon/lifetimes/blob/master/lifetimes/fitters/__init__.py)
```{python}
import autograd.numpy as np
from autograd.scipy.special import gammaln, beta, gamma
from autograd import value_and_grad, hessian
def negative_log_likelihood(log_params, x, t_x, T):
params = np.exp(log_params)
r, alpha, a, b = params
A_1 = gammaln(r + x) - gammaln(r) + r * np.log(alpha)
A_2 = gammaln(a + b) + gammaln(b + x) - gammaln(b) - gammaln(a + b + x)
A_3 = -(r + x) * np.log(alpha + T)
A_4 = np.log(a) - np.log(b + np.maximum(x, 1) - 1) - (r + x) * np.log(t_x + alpha)
max_A_3_A_4 = np.maximum(A_3, A_4)
ll = (
A_1
+ A_2
+ np.log(np.exp(A_3 - max_A_3_A_4) + np.exp(A_4 - max_A_3_A_4) * (x > 0))
+ max_A_3_A_4
)
return -ll.sum()
def BetaGeoFitter(guess={"r": 0.1, "alpha": 0.1, "a": 0.0, "b": 0.1}):
return minimize(
value_and_grad(negative_log_likelihood),
jac=True,
method=None,
args=(p1x, t_x, T),
tol=1e-7,
x0=list(guess.values()),
options={"disp": True},
)
result = BetaGeoFitter()
r, alpha, a, b = np.exp(result.x)
ll = result.fun
print(
f"""r = {r:0.4f}
α = {alpha:0.4f}
a = {a:0.4f}
b = {b:0.4f}
Log-Likelihood = {-ll:0.4f}"""
)
index = index = ["r", "α", "a", "b"]
lifetimes_params = np.exp(result.x)
hessian_mat = hessian(negative_log_likelihood)(result.x, p1x, t_x, T)
var_mat = (lifetimes_params**2) * np.linalg.inv(
hessian_mat
) # Variance-Covariance Matrix
se = np.sqrt(np.diag(var_mat)) # Standard Error
plo = lifetimes_params - 1.96 * se
phi = lifetimes_params + 1.96 * se
pl.DataFrame(
{
"Parameter": index,
"Coef": lifetimes_params,
"SE (Coef)": se,
"5.5%": plo,
"94.5%": phi,
}
)
```
## Stan Model
We will now set-up a Stan model and run both, the optimization algorithm and the MCMC sampler.
### Standard Parameters
```{python}
# | code-fold: false
import numpy as np
stan_code = '''
data {
int<lower=0> N; // Number of customers
array[N] int<lower=0> X; // Number of transactions per customer
vector<lower=0>[N] T; // Total observation time per customer
vector<lower=0>[N] t_x; // Time of last transaction (0 if X=0)
}
parameters {
real<lower=0> r; // Gamma shape (r)
real<lower=0> alpha; // Gamma scale (alpha)
real<lower=0, upper=5> a; // Beta shape 1 (a)
real<lower=0, upper=5> b; // Beta shape 2 (b)
}
model {
// Weakly informative priors
r ~ weibull(2, 1);
alpha ~ weibull(2, 10);
a ~ uniform(0, 5);
b ~ uniform(0, 5);
for (n in 1:N) {
int x = X[n];
real tx = t_x[n];
real t = T[n];
// Term 1: B(a, b + x)/B(a, b) * Γ(r + x)/Γ(r) * (alpha/(alpha + t))^(r + x)
real log_term1 = (
lbeta(a, b + x) - lbeta(a, b) +
lgamma(r + x) - lgamma(r) +
r * log(alpha) - (r + x) * log(alpha + t)
);
// Term 2: B(a + 1, b + x - 1)/B(a, b) * Γ(r + x)/Γ(r) * (alpha/(alpha + tx))^(r + x)
real log_term2 = negative_infinity();
if (x > 0) {
log_term2 = (
lbeta(a + 1, b + x - 1) - lbeta(a, b) +
lgamma(r + x) - lgamma(r) +
r * log(alpha) - (r + x) * log(alpha + tx)
);
}
target += log_sum_exp(log_term1, log_term2);
}
}
'''
```
```{python}
data = {
"N": len(p1x),
"X": p1x.flatten().astype(int).tolist(),
"T": T.flatten().tolist(),
"t_x": t_x.flatten().tolist(),
}
stan_model = StanQuap(
stan_file="stan_models/bg-nbd",
stan_code=stan_code,
data=data,
algorithm="LBFGS",
jacobian=False,
tol_rel_grad=1e-7,
iter=5000,
)
index = ["r", "α", "a", "b"]
params = np.array(list(stan_model.opt_model.stan_variables().values()))
var_mat = stan_model.vcov_matrix() # Variance-Covariance Matrix
se = np.sqrt(np.diag(var_mat)) # Standard Error
plo = params - 1.96 * se
phi = params + 1.96 * se
pl.DataFrame(
{
"Parameter": index,
"Coef": params,
"SE (Coef)": se,
"5.5%": plo,
"94.5%": phi,
}
)
```
```{python}
x = [
stan_model.opt_model.optimized_params_pd["r"][0],
stan_model.opt_model.optimized_params_pd["alpha"][0],
stan_model.opt_model.optimized_params_pd["a"][0],
stan_model.opt_model.optimized_params_pd["b"][0]
]
print("Log-Likelihood:", bgnbd_ll(x, p1x, t_x, T))
# print(negative_log_likelihood(np.log(np.array(x)), p1x, t_x, T))
```
### Modified Parameters
```{python}
# | code-fold: false
stan_code = '''
data {
int<lower=0> N; // Number of customers
array[N] int<lower=0> X; // Number of transactions per customer
vector<lower=0>[N] T; // Total observation time per customer
vector<lower=0>[N] t_x; // Time of last transaction (0 if X=0)
}
parameters {
real<lower=0> r; // Shape parameter for the Gamma prior on purchase rate
real<lower=0> alpha; // Scale parameter for purchase rate
real<lower=0, upper=1> phi_dropout; // Mixture weight for dropout process (Uniform prior)
real<lower=1> kappa_dropout; // Scale parameter for dropout (Pareto prior)
}
transformed parameters {
real a = phi_dropout * kappa_dropout; // Dropout shape parameter (controls early dropout likelihood)
real b = (1 - phi_dropout) * kappa_dropout; // Dropout scale parameter (controls later dropout likelihood)
}
model {
// Priors:
r ~ weibull(2, 1); // Prior on r (purchase rate shape parameter)
alpha ~ weibull(2, 10); // Prior on alpha (purchase rate scale parameter)
phi_dropout ~ uniform(0,1); // Mixture component for dropout process
kappa_dropout ~ pareto(1,1); // Scale of dropout process
for (n in 1:N) {
int x = X[n]; // Number of transactions for customer n
real tx = t_x[n]; // Time of last transaction
real t = T[n]; // Total observation time
if (x == 0) {
// Likelihood for customers with zero transactions:
// Probability of no purchases during (0, T): (alpha/(alpha + t))^r
// Likelihood for X=0: (alpha/(alpha + t))^r
target += r * (log(alpha) - log(alpha + t));
} else {
// Term 1: Probability of surviving until T and making x purchases
// Term 1: B(a, b + x)/B(a, b) * Γ(r + x)/Γ(r) * (alpha/(alpha + t))^(r + x)
real beta_term1 = lbeta(a, b + x) - lbeta(a, b); // Beta function term
real gamma_term = lgamma(r + x) - lgamma(r); // Gamma function term
real term1 = gamma_term + beta_term1 + r * log(alpha) - (r + x) * log(alpha + t);
// Term 2: Probability of surviving until t_x, then dropping out
// Term 2: B(a + 1, b + x - 1)/B(a, b) * Γ(r + x)/Γ(r) * (alpha/(alpha + tx))^(r + x)
real beta_term2 = lbeta(a + 1, b + x - 1) - lbeta(a, b);
real term2 = gamma_term + beta_term2 + r * log(alpha) - (r + x) * log(alpha + tx);
// Log-sum-exp for numerical stability
target += log_sum_exp(term1, term2);
}
}
}
'''
```
```{python}
data = {
"N": len(p1x),
"X": p1x.flatten().astype(int).tolist(),
"T": T.flatten().tolist(),
"t_x": t_x.flatten().tolist(),
}
stan_model = StanQuap(
stan_file="stan_models/bg-nbd-1",
stan_code=stan_code,
data=data,
algorithm="LBFGS",
jacobian=False,
tol_rel_grad=1e-7,
iter=5000,
generated_var=["a", "b"],
)
index = ["r", "α", "phi", "kappa", "a", "b"]
MAP_params = np.array(list(stan_model.opt_model.stan_variables().values()))
var_mat = stan_model.vcov_matrix() # Variance-Covariance Matrix
se = np.sqrt(np.diag(var_mat)) # Standard Error
se = np.concatenate((se, np.array([se[-2] * se[-1], (1 - se[-2]) * se[-1]])))
plo = MAP_params - 1.96 * se
phi = MAP_params + 1.96 * se
pl.DataFrame(
{
"Parameter": index,
"Coef": MAP_params,
"SE (Coef)": se,
"5.5%": plo,
"94.5%": phi,
}
)
```
```{python}
x = [
stan_model.opt_model.optimized_params_pd["r"][0],
stan_model.opt_model.optimized_params_pd["alpha"][0],
stan_model.opt_model.optimized_params_pd["a"][0],
stan_model.opt_model.optimized_params_pd["b"][0],
]
print("Log-Likelihood:", bgnbd_ll(x, p1x, t_x, T))
# print(negative_log_likelihood(np.log(np.array(x)), p1x, t_x, T))
```
### MCMC Model Fitting
```{python}
# | code-fold: false
mcmc = stan_model.stan_model.sample(data=data)
inf_data = az.from_cmdstanpy(mcmc)
print(mcmc.diagnose())
```
#### Model Summary
```{python}
mcmc.summary()
```
#### Model Trace Plot
```{python}
axes = az.plot_trace(
data=inf_data,
compact=True,
kind="rank_bars",
backend_kwargs={"figsize": (12, 9), "layout": "constrained"},
)
plt.gcf().suptitle("BG/NBD Model Trace", fontsize=18, fontweight="bold")
plt.tight_layout();
```
#### Model Posterior Plot
```{python}
fig, axes = plt.subplots(2, 2, figsize=(12, 9), sharex=False, sharey=False)
axes = axes.flatten()
for i, var_name in enumerate(["r", "alpha", "a", "b"]):
ax = axes[i]
az.plot_posterior(
inf_data.posterior[var_name].values.flatten(),
color="C0",
point_estimate="mean",
ax=ax,
label="MCMC",
)
ax.axvline(
x=stan_model.opt_model.stan_variable(var_name),
color="C1",
linestyle="--",
label="Stan MAP",
)
ax.axvline(x=lifetimes_params[i], color="C2", linestyle="--", label="Lifetimes")
ax.axvline(x=scipy_params[i], color="C3", linestyle="--", label="SciPy")
ax.legend(loc="upper right")
ax.set_title(var_name)
plt.gcf().suptitle("BG/NBD Model Parameters", fontsize=18, fontweight="bold")
plt.tight_layout();
```
The `r` and `alpha` purchase rate parameters are quite similar for all three models, but the `a` and `b` dropout parameters are better approximated with the `phi_dropout` and `kappa_dropout` parameters when fitted with MCMC.
## Prior and Posterior Predictive Checks
PPCs allow us to check the efficacy of our priors, and the performance of the fitted posteriors. For prior predictive check, we generate random numbers of the parameters based on the prior distribution. In contrast, for posterior predictive check, we generate replicated data according to the posterior predictive distribution.
Note that in addition to generating random numbers of the priors or sampling parameters from the posterior, we are computing the predicted number of transactions for each customer during their observation period $T$. This will be computed in two ways:
- In Stan, we will us @eq-numtrans and @eq-numtrans2 given the nature of the dropout process and the time between transactions:
- Transaction Process:
$$
\text{Time between transactions} \sim \text{Exponential}(\lambda)
$$
- Dropout Process:
$$
\text{Dropout after transaction} \sim \text{Bernoulli}(p)
$$
- Population Distributions:
$$
\lambda \sim \text{Gamma}(r, \alpha), \quad p \sim \text{Beta}(a, b)
$$
- We will also compute the number of transactions for each customer using @eq-numtrans3.
```{python}
# probability of observing x purchases in a time period of length t
def P_X_t(x, t, r, alpha, a, b):
A = np.cumsum(
gamma(r + x[:-1])
/ (gamma(r) * factorial(x[:-1]))
* (t / (alpha + t)) ** x[:-1],
axis=0,
)
pmf = (
beta(a, b + x)
/ beta(a, b)
* gamma(r + x)
/ (gamma(r) * factorial(x))
* (alpha / (alpha + t)) ** r
* (t / (alpha + t)) ** x
)
pmf[1:] += (
beta(a + 1, b + x[1:] - 1) / beta(a, b) * (1 - (alpha / (alpha + t)) ** r * A)
)
return pmf
def bgnbd_predict_trans_dist(x, n_t, T, r, alpha, a, b):
"""
x - range of purchase quantites, shape (x, 1, 1)
n_t - number of customers who have the time of birth t, shape (n_t,)
t - age of the customer with time origin of 0, shape (1, t, 1)
*params - parameters, shape (1,1,params)
return: shape (x, param)
"""
pmf = P_X_t(x, T, r, alpha, a, b)
pmf[-1] = 1 - np.sum(pmf[:-1], axis=0)
return np.tensordot(pmf, n_t, axes=([1], [0]))
```
### Prior Predictive Check
Let’s see how the model performs in a prior predictive check, where we sample from the default priors before fitting the model:
```{python}
# | code-fold: false
stan_prior_code = '''
data {
int<lower=0> N;
vector<lower=0>[N] T;
}
generated quantities {
real r = weibull_rng(2, 1);
real alpha = weibull_rng(2, 10);
real phi_dropout = uniform_rng(0, 1);
real kappa_dropout = pareto_rng(1, 1);
real a = phi_dropout * kappa_dropout;
real b = (1 - phi_dropout) * kappa_dropout;
array[N] int X_rep;
vector[N] t_x_rep;
for (n in 1:N) {
real lambda_n = gamma_rng(r, alpha);
real p_n = beta_rng(a, b);
real current_time = 0;
int x = 0;
real tx = 0;
int active = 1;
while (active && current_time < T[n]) {
real wait = exponential_rng(lambda_n);
if (current_time + wait > T[n]) {
break;
} else {
current_time += wait;
x += 1;
tx = current_time;
if (bernoulli_rng(p_n)) {
active = 0;
}
}
}
X_rep[n] = x;
t_x_rep[n] = tx;
}
}
'''
```
```{python}
data = {
"N": len(p1x),
"T": T.flatten().tolist(),
}
stan_model = Stan(stan_file="stan_models/bg-nbd-prior", stan_code=stan_prior_code)
prior_fit = stan_model.sample(data=data)
```
```{python}
prior_samples = prior_fit.stan_variable("X_rep").astype(int)
# Compute prior frequency distribution
max_purch = 9
prior_freq_counts = np.zeros((prior_samples.shape[0], max_purch + 1))
for i in range(prior_samples.shape[0]):
counts = np.bincount(prior_samples[i], minlength=max_purch + 1)
prior_freq_counts[i] = counts[: max_purch + 1] / data["N"]
mean_frequency = prior_freq_counts.mean(axis=0)
hdi = az.hdi(prior_freq_counts, hdi_prob=0.89)
observed_counts = np.bincount(p1x.flatten().astype(int), minlength=max_purch + 1)
observed_frequency = observed_counts[: max_purch + 1] / data["N"]
plt.clf()
plt.bar(
np.arange(max_purch + 1) + 0.2,
mean_frequency,
width=0.4,
label="Estimated",
color="white",
edgecolor="black",
linewidth=0.5,
yerr=[mean_frequency - hdi[:, 0], hdi[:, 1] - mean_frequency],
)
plt.bar(
np.arange(max_purch + 1) - 0.2,
observed_frequency,
0.4,
label="Observed",
color="black",
)
plt.xlabel(f"Number of Repeat Purchases (0-{max_purch + 1}+)")
plt.ylabel("% of Customer Population")
plt.title("Prior Predictive Check: Customer Purchase Frequency")
plt.xticks(
ticks=np.arange(max_purch + 1),
labels=[
f"{i}" if i < max_purch else f"{max_purch + 1}+" for i in range(max_purch + 1)
],
)
plt.legend();
```
Now, let's compute the probability of observing $x$ purchases in a time period of length $t$ using a closed-form function (@eq-numtrans3):
```{python}
max_purch = 7
params = [
prior_fit.stan_variable(param).reshape(1, 1, -1)
for param in ["r", "alpha", "a", "b"]
]
T_unique, n_t = np.unique(T, return_counts=True)
frequency_counts = (
bgnbd_predict_trans_dist(
np.arange(max_purch + 1).reshape(-1, 1, 1),
n_t,
T_unique.reshape(1, -1, 1),
*params,
)
/ data["N"]
)
mean_frequency = np.nanmean(frequency_counts, axis=1)
hdi = az.hdi(frequency_counts.T, hdi_prob=0.89)
observed_counts = np.bincount(p1x.flatten().astype(int), minlength=max_purch + 1)
observed_counts_cen = observed_counts[: max_purch + 1]
observed_counts_cen[-1] += np.sum(observed_counts[max_purch + 1 :])
observed_frequency = observed_counts_cen / data["N"]
plt.clf()
plt.bar(
np.arange(max_purch + 1) + 0.2,
mean_frequency,
width=0.4,
label="Estimated",
color="white",
edgecolor="black",
linewidth=0.5,
yerr=[mean_frequency - hdi[:, 0], hdi[:, 1] - mean_frequency],
)
plt.bar(
np.arange(max_purch + 1) - 0.2,