-
Notifications
You must be signed in to change notification settings - Fork 37
/
pnbd.R
1863 lines (1758 loc) · 76.1 KB
/
pnbd.R
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
################################################## Pareto/NBD estimation, visualization functions
library(hypergeo)
library(optimx)
#' Define general parameters
#'
#' This is to ensure consistency across all functions that require the
#' likelihood function, or the log of it, and to make sure that the same
#' implementation of the hypergeometric function is used everywhere for building
#' \code{A0}.
#'
#' This function is only ever called by either \code{\link{pnbd.LL}} or
#' \code{\link{pnbd.PAlive}} so it returns directly the output that is expected
#' from those calling functions: either the log likelihood for a set of
#' customers, or the probability that a set of customers with characteristics
#' given by \code{x}, \code{t.x} and \code{T.cal}, having estimated a set of
#' \code{params}, is still alive. Either set of customers can be of size 1.
#' @inheritParams pnbd.LL
#' @param func name of the function calling dc.InputCheck; either \code{pnbd.LL}
#' or \code{pnbd.PAlive}.
#' @return A vector of log likelihood values if \code{func} is \code{pnbd.LL},
#' or a vector of probabilities that a customer is still alive if \code{func}
#' is \code{pnbd.PAlive}.
#' @seealso \code{\link{pnbd.LL}}
#' @seealso \code{\link{pnbd.PAlive}}
#' @seealso \code{\link{pnbd.DERT}}
pnbd.generalParams <- function(params,
x,
t.x,
T.cal,
func,
hardie = TRUE) {
# Since pnbd.LL and pnbd.pAlive are the only options
# for func, we don't need a printnames argument
# in the pnbd.generalParams wrapper.
stopifnot(func %in% c('pnbd.LL', 'pnbd.PAlive'))
inputs <- try(dc.InputCheck(params = params,
func = func,
printnames = c("r", "alpha", "s", "beta"),
x = x,
t.x = t.x,
T.cal = T.cal))
if('try-error' == class(inputs)) return(str(inputs)$message)
x <- inputs$x
t.x <- inputs$t.x
T.cal <- inputs$T.cal
r <- params[1]
alpha <- params[2]
s <- params[3]
beta <- params[4]
maxab <- max(alpha, beta)
absab <- abs(alpha - beta)
param2 <- s + 1
if (alpha < beta) {
param2 <- r + x
}
a <- alpha + T.cal
b <- maxab + t.x
c <- beta + T.cal
d <- maxab + T.cal
w <- r + s + x
if(hardie == TRUE) {
F1 <- h2f1(a = w,
b = param2,
c = w + 1,
z = absab / b)
F2 <- h2f1(a = w,
b = param2,
c = w + 1,
z = absab / d)
} else {
F1 <- Re(hypergeo(A = w,
B = param2,
C = w + 1,
z = absab / b))
F2 <- Re(hypergeo(A = w,
B = param2,
C = w + 1,
z = absab / d))
}
A0 <- F1/(b^w) - F2/(d^w)
# You only ever call this function from two other
# places: pnbd.LL or pnbd.PAlive.
if(func == 'pnbd.LL') {
# this returns the log likelihood for one random customer
part1 <- r * log(alpha) +
s * log(beta) +
lgamma(r + x) -
lgamma(r)
part2 <- 1 / (a^(w - s) * c^s)
return(part1 + log(part2) + log(1 + (s/w) * A0 / part2))
}
else if(func == 'pnbd.PAlive') {
# This returns the probability that a random customer is still alive
return(1 / (1 + s/w * a^(w - s) * c^s * A0))
} else {
return(NULL)
}
}
#' Use Bruce Hardie's Gaussian hypergeometric implementation
#'
#' In benchmarking \code{\link{pnbd.LL}} runs more quickly and
#' it returns the same results if it uses this helper instead of
#' \code{\link[hypergeo]{hypergeo}}, which is the default. But \code{h2f1}
#' is such a barebones function that in some edge cases it will keep
#' going until you get a segfault, where \code{\link[hypergeo]{hypergeo}}
#' would have failed with a proper error message.
#'
#' @param a, counterpart to A in \code{\link[hypergeo]{hypergeo}}
#' @param b, counterpart to B in \code{\link[hypergeo]{hypergeo}}
#' @param c, counterpart to C in \code{\link[hypergeo]{hypergeo}}
#' @param z, counterpart to z in \code{\link[hypergeo]{hypergeo}}
#' @seealso \code{\link[hypergeo]{hypergeo}}
#' @references Fader, Peter S., and Bruce G.S. Hardie. "A Note on Deriving the Pareto/NBD Model and
#' Related Expressions." November. 2005. Web. \url{http://www.brucehardie.com/notes/008/}
h2f1 <- function(a, b, c, z) {
lenz <- length(z)
j = 0
uj <- 1:lenz
uj <- uj/uj
y <- uj
lteps <- 0
while (lteps < lenz) {
lasty <- y
j <- j + 1
uj <- uj * (a + j - 1) * (b + j - 1)/(c + j - 1) * z/j
y <- y + uj
lteps <- sum(y == lasty)
}
return(y)
}
#' Pareto/NBD Log-Likelihood
#'
#' Calculates the log-likelihood of the Pareto/NBD model.
#'
#' @param params Pareto/NBD parameters - a vector with r, alpha, s, and beta, in
#' that order. r and alpha are unobserved parameters for the NBD transaction
#' process. s and beta are unobserved parameters for the Pareto (exponential
#' gamma) dropout process.
#' @param x number of repeat transactions in the calibration period T.cal, or a
#' vector of transaction frequencies.
#' @param t.x time of most recent repeat transaction, or a vector of recencies.
#' @param T.cal length of calibration period, or a vector of calibration period
#' lengths.
#' @param hardie if TRUE, use \code{\link{h2f1}} instead of
#' \code{\link[hypergeo]{hypergeo}}.
#'
#' @seealso \code{\link{pnbd.EstimateParameters}}
#'
#' @return A vector of log-likelihoods as long as the longest input vector (x,
#' t.x, or T.cal).
#' @references Fader, Peter S., and Bruce G.S. Hardie. "A Note on Deriving the
#' Pareto/NBD Model and Related Expressions." November. 2005. Web.
#' \url{http://www.brucehardie.com/notes/008/}
#'
#' @examples
#' # Returns the log likelihood of the parameters for a customer who
#' # made 3 transactions in a calibration period that ended at t=6,
#' # with the last transaction occurring at t=4.
#' pnbd.LL(params, x=3, t.x=4, T.cal=6, hardie = TRUE)
#'
#' # We can also give vectors as function parameters:
#' set.seed(7)
#' x <- sample(1:4, 10, replace = TRUE)
#' t.x <- sample(1:4, 10, replace = TRUE)
#' T.cal <- rep(4, 10)
#' pnbd.LL(params, x, t.x, T.cal, hardie = TRUE)
pnbd.LL <- function(params,
x,
t.x,
T.cal,
hardie = TRUE) {
pnbd.generalParams(params = params,
x = x,
t.x = t.x,
T.cal = T.cal,
func = 'pnbd.LL',
hardie = hardie)
}
#' Pareto/NBD P(Alive)
#'
#' Uses Pareto/NBD model parameters and a customer's past transaction behavior
#' to return the probability that they are still alive at the end of the
#' calibration period.
#'
#' P(Alive | X=x, t.x, T.cal, r, alpha, s, beta)
#'
#' x, t.x, and T.cal may be vectors. The standard rules for vector operations
#' apply - if they are not of the same length, shorter vectors will be recycled
#' (start over at the first element) until they are as long as the longest
#' vector. It is advisable to keep vectors to the same length and to use single
#' values for parameters that are to be the same for all calculations. If one of
#' these parameters has a length greater than one, the output will be a vector
#' of probabilities.
#'
#' @inheritParams pnbd.LL
#'
#' @return Probability that the customer is still alive at the end of the
#' calibration period. If x, t.x, and/or T.cal has a length greater than one,
#' then this will be a vector of probabilities (containing one element
#' matching each element of the longest input vector).
#' @references Fader, Peter S., and Bruce G.S. Hardie. "A Note on Deriving the
#' Pareto/NBD Model and Related Expressions." November. 2005. Web.
#' \url{http://www.brucehardie.com/notes/008/}
#'
#' @examples
#' data(cdnowSummary)
#' cbs <- cdnowSummary$cbs
#' params <- pnbd.EstimateParameters(cbs, hardie = TRUE)
#'
#' pnbd.PAlive(params, x=0, t.x=0, T.cal=39, TRUE)
#' # 0.2941633; P(Alive) of a customer who made no repeat transactions.
#'
#' pnbd.PAlive(params, x=23, t.x=39, T.cal=39, TRUE)
#' # 1; P(Alive) of a customer who has the same recency and total
#' # time observed.
#'
#' pnbd.PAlive(params, x=5:20, t.x=30, T.cal=39, TRUE)
#' # Note the "increasing frequency paradox".
#'
#' # To visualize the distribution of P(Alive) across customers:
#' p.alives <- pnbd.PAlive(params, cbs[,"x"], cbs[,"t.x"], cbs[,"T.cal"], TRUE)
#' plot(density(p.alives))
pnbd.PAlive <- function(params,
x,
t.x,
T.cal,
hardie = TRUE) {
pnbd.generalParams(params = params,
x = x,
t.x = t.x,
T.cal = T.cal,
func = 'pnbd.PAlive',
hardie = hardie)
}
#' Pareto/NBD Discounted Expected Residual Transactions
#'
#' Calculates the discounted expected residual transactions of a customer, given
#' their behavior during the calibration period.
#'
#' DERT(d | r, alpha, s, beta, X = x, t.x, T.cal)
#'
#' x, t.x, T.cal may be vectors. The standard rules for vector operations apply
#' - if they are not of the same length, shorter vectors will be recycled (start
#' over at the first element) until they are as long as the longest vector. It
#' is advisable to keep vectors to the same length and to use single values for
#' parameters that are to be the same for all calculations. If one of these
#' parameters has a length greater than one, the output will be also be a
#' vector.
#'
#' @inheritParams pnbd.LL
#' @param d the discount rate to be used. Make sure that it matches up with your
#' chosen time period (do not use an annual rate for monthly data, for
#' example).
#'
#' @return The number of discounted expected residual transactions for a
#' customer with a particular purchase pattern during the calibration period.
#' @references Fader, Peter S., Bruce G.S. Hardie, and Ka L. Lee. "RFM and CLV:
#' Using Iso-Value Curves for Customer Base Analysis." Journal of Marketing
#' Research Vol.42, pp.415-430. November. 2005.
#' \url{http://www.brucehardie.com/papers.html}
#' @references See equation 2.
#' @references Note that this paper refers to what this package is calling
#' discounted expected residual transactions (DERT) simply as discounted
#' expected transactions (DET).
#'
#' @examples
#' # elog <- dc.ReadLines(system.file("data/cdnowElog.csv", package="BTYD2"),2,3)
#' # elog[, 'date'] <- as.Date(elog[, 'date'], format = '%Y%m%d')
#' # cal.cbs <- dc.ElogToCbsCbt(elog)$cal$cbs
#' # params <- pnbd.EstimateParameters(cal.cbs, hardie = TRUE)
#' params <- c(0.5629966, 12.5590370, 0.4081095, 10.5148048)
#'
#' # 15% compounded annually has been converted to 0.0027 compounded continuously,
#' # as we are dealing with weekly data and not annual data.
#' d <- 0.0027
#'
#' # calculate the discounted expected residual transactions of a customer
#' # who made 7 transactions in a calibration period that was 77.86
#' # weeks long, with the last transaction occurring at the end of
#' # the 35th week.
#' pnbd.DERT(params,
#' x = 7,
#' t.x = 35,
#' T.cal = 77.86,
#' d,
#' hardie = TRUE)
#'
#' # We can also use vectors to compute DERT for several customers:
#' pnbd.DERT(params,
#' x = 1:10,
#' t.x = 30,
#' T.cal = 77.86,
#' d,
#' hardie = TRUE)
pnbd.DERT <- function(params,
x,
t.x,
T.cal,
d,
hardie = TRUE) {
loglike <- try(pnbd.LL(params = params,
x = x,
t.x = t.x,
T.cal = T.cal,
hardie = hardie))
if('try-error' %in% class(loglike)) return(loglike)
# This is the remainder of the original pnbd.DERT function def.
# No need to get too clever here. Revert to explicit assignment
# of params to r, alpha, s, beta the old-school way.
r <- params[1]
alpha <- params[2]
s <- params[3]
beta <- params[4]
z <- d * (beta + T.cal)
tricomi.part.1 = ((z)^(1 - s))/(s - 1) *
genhypergeo(U = c(1),
L = c(2 - s),
z = z,
check_mod = FALSE)
tricomi.part.2 = gamma(1 - s) *
genhypergeo(U = c(s),
L = c(s),
z = z,
check_mod = FALSE)
tricomi = tricomi.part.1 + tricomi.part.2
result <- exp(r * log(alpha) +
s * log(beta) +
(s - 1) * log(d) +
lgamma(r + x + 1) +
log(tricomi) -
lgamma(r) -
(r + x + 1) * log(alpha + T.cal) -
loglike)
return(result)
}
#' Pareto/NBD Log-Likelihood
#'
#' Calculates the log-likelihood of the Pareto/NBD model.
#'
#' @inheritParams pnbd.LL
#' @param cal.cbs calibration period CBS (customer by sufficient statistic). It
#' must contain columns for frequency ("x"), recency ("t.x"), and total time
#' observed ("T.cal"). Note that recency must be the time between the start of
#' the calibration period and the customer's last transaction, not the time
#' between the customer's last transaction and the end of the calibration
#' period. If your data is compressed (see \code{\link{dc.compress.cbs}}), a
#' fourth column labelled "custs" (number of customers with a specific
#' combination of recency, frequency and length of calibration period) will
#' make this function faster.
#' @seealso \code{\link{pnbd.EstimateParameters}}
#' @seealso \code{\link{pnbd.LL}}
#' @return The log-likelihood of the provided data.
#' @references Fader, Peter S., and Bruce G.S. Hardie. "A Note on Deriving the
#' Pareto/NBD Model and Related Expressions." November. 2005. Web.
#' \url{http://www.brucehardie.com/notes/008/}
#'
#' @examples
#' data(cdnowSummary)
#' cal.cbs <- cdnowSummary$cbs
#' # cal.cbs already has column names required by method
#'
#' # random assignment of parameters
#' params <- c(0.5, 8, 0.7, 10)
#' # returns the log-likelihood of the given parameters
#' pnbd.cbs.LL (params, cal.cbs, TRUE)
#'
#' # compare the speed and results to the following:
#' cal.cbs.compressed <- dc.compress.cbs(cal.cbs)
#' pnbd.cbs.LL (params, cal.cbs.compressed, TRUE)
pnbd.cbs.LL <- function(params,
cal.cbs,
hardie = TRUE) {
dc.check.model.params(printnames = c("r", "alpha", "s", "beta"),
params = params,
func = "pnbd.cbs.LL")
# Check that you have the right columns.
# They should be 'x', 't.x', 'T.cal' and optionally 'custs'
# in this order. They stand for, respectively
# -- x: frequency
# -- t.x: recency
# -- T.cal: observed calendar time
# -- custs: number of customers with this (x, t.x, T.cal) combo
foo <- colnames(cal.cbs)
stopifnot(foo[1] == 'x' &
foo[2] == 't.x' &
foo[3] == 'T.cal')
x <- cal.cbs[,'x']
t.x <- cal.cbs[,'t.x']
T.cal <- cal.cbs[,'T.cal']
if ("custs" %in% foo) {
custs <- cal.cbs[, "custs"]
} else {
custs <- rep(1, length(x))
}
return(sum(custs * pnbd.LL(params, x, t.x, T.cal, hardie)))
}
#' Pareto/NBD Parameter Estimation
#'
#' The best-fitting parameters are determined using the
#' \code{\link{pnbd.cbs.LL}} function. The sum of the log-likelihood for each
#' customer (for a set of parameters) is maximized in order to estimate
#' parameters.
#'
#' A set of starting parameters must be provided for this method. If no
#' parameters are provided, (1,1,1,1) is used as a default. It may be useful to
#' use starting values for r and s that represent your best guess of the
#' heterogeneity in the buy and die rate of customers. It may be necessary to
#' run the estimation from multiple starting points to ensure that it converges.
#' To compare the log-likelihoods of different parameters, use
#' \code{\link{pnbd.cbs.LL}}.
#'
#' The lower bound on the parameters to be estimated is always zero, since
#' Pareto/NBD parameters cannot be negative. The upper bound can be set with the
#' max.param.value parameter.
#'
#' This function may take some time to run. It uses \code{\link[optimx]{optimx}}
#' for maximum likelihood estimation, not \code{\link[stats]{optim}}.
#'
#' @param cal.cbs calibration period CBS (customer by sufficient statistic). It
#' must contain columns for frequency ("x"), recency ("t.x"), and total time
#' observed ("T.cal"). Note that recency must be the time between the start of
#' the calibration period and the customer's last transaction, not the time
#' between the customer's last transaction and the end of the calibration
#' period. If your data is compressed (see \code{\link{dc.compress.cbs}}), a
#' fourth column labelled "custs" (number of customers with a specific
#' combination of recency, frequency and length of calibration period) will
#' make this function faster.
#' @param par.start initial Pareto/NBD parameters - a vector with r, alpha, s,
#' and beta, in that order. r and alpha are unobserved parameters for the NBD
#' transaction process. s and beta are unobserved parameters for the Pareto
#' (exponential gamma) dropout process.
#' @param max.param.value the upper bound on parameters.
#' @param method the optimization method(s).
#' @param hardie if TRUE, have \code{\link{pnbd.LL}} use \code{\link{h2f1}}
#' instead of \code{\link[hypergeo]{hypergeo}}.
#' @param hessian set it to TRUE if you want the Hessian matrix, and then you
#' might as well have the complete \code{\link[optimx]{optimx}} object
#' returned.
#'
#' @return Unnamed vector of estimated parameters by default, \code{optimx}
#' object with everything if \code{hessian} is TRUE.
#' @seealso \code{\link{pnbd.cbs.LL}}
#' @references Fader, Peter S.; Hardie, and Bruce G.S.. "Overcoming the BG/NBD
#' Model's #NUM! Error Problem." December. 2013. Web.
#' \url{http://brucehardie.com/notes/027/bgnbd_num_error.pdf}
#'
#' @examples
#' data(cdnowSummary)
#'
#' cal.cbs <- cdnowSummary$cbs
#' # cal.cbs already has column names required by method
#'
#' # starting-point parameters
#' startingparams <- c(0.5, 6, 0.9, 8)
#'
#' # estimated parameters
#' est.params <- pnbd.EstimateParameters(cal.cbs = cal.cbs,
#' par.start = startingparams,
#' method = 'L-BFGS-B',
#' hardie = TRUE)
#'
#' # complete object returned by \code{\link[optimx]{optimx}}
#' optimx.set <- pnbd.EstimateParameters(cal.cbs = cal.cbs,
#' par.start = startingparams,
#' hardie = TRUE,
#' hessian = TRUE)
#'
#' # log-likelihood of estimated parameters
#' pnbd.cbs.LL(est.params, cal.cbs, TRUE)
pnbd.EstimateParameters <- function(cal.cbs,
par.start = c(1, 1, 1, 1),
max.param.value = 10000,
method = 'L-BFGS-B',
hardie = TRUE,
hessian = FALSE) {
dc.check.model.params(printnames = c("r", "alpha", "s", "beta"),
params = par.start,
func = "pnbd.EstimateParameters")
## helper function to be optimized
pnbd.eLL <- function(params, cal.cbs, hardie) {
params <- exp(params)
params[params > max.param.value] <- max.param.value
return(-1 * pnbd.cbs.LL(params = params,
cal.cbs = cal.cbs,
hardie = hardie))
}
logparams <- log(par.start)
if(hessian == TRUE) {
return(optimx(par = logparams,
fn = pnbd.eLL,
method = method,
cal.cbs = cal.cbs,
hardie = hardie,
hessian = hessian))
}
results <- optimx(par = logparams,
fn = pnbd.eLL,
method = method,
cal.cbs = cal.cbs,
hardie = hardie)
params <- exp(unname(unlist(results[method, c('p1', 'p2', 'p3', 'p4')])))
return(params)
}
#' Generalized Pareto/NBD Probability Mass Function
#'
#' Generalized probability mass function for the Pareto/NBD.
#'
#' P(X(t.start, t.end)=x | r, alpha, s, beta). Returns the probability that a
#' customer makes x repeat transactions in the time interval (t.start, t.end].
#'
#' It is impossible for a customer to make a negative number of repeat
#' transactions. This function will return an error if it is given negative
#' times or a negative number of repeat transactions. This function will also
#' return an error if t.end is less than t.start.
#'
#' \code{t.start}, \code{t.end}, and \code{x} may be vectors. The standard rules
#' for vector operations apply - if they are not of the same length, shorter
#' vectors will be recycled (start over at the first element) until they are as
#' long as the longest vector. It is advisable to keep vectors to the same
#' length and to use single values for parameters that are to be the same for
#' all calculations. If one of these parameters has a length greater than one,
#' the output will be a vector of probabilities.
#'
#' @param params Pareto/NBD parameters - a vector with r, alpha, s, and beta, in
#' that order. r and alpha are unobserved parameters for the NBD transaction
#' process. s and beta are unobserved parameters for the Pareto (exponential
#' gamma) dropout process.
#' @param t.start start of time period for which probability is being
#' calculated. It can also be a vector of values.
#' @param t.end end of time period for which probability is being calculated. It
#' can also be a vector of values.
#' @param x number of repeat transactions by a random customer in the period
#' defined by (t.start, t.end]. It can also be a vector of values.
#' @param hardie if TRUE, use \code{\link{h2f1}} instead of
#' \code{\link[hypergeo]{hypergeo}}.
#'
#' @return Probability of x transaction occuring between t.start and t.end
#' conditional on model parameters. If t.start, t.end, and/or x has a length
#' greater than one, a vector of probabilities will be returned.
#' @references Fader, Peter S., and Bruce G.S. Hardie. "Deriving an Expression
#' for P (X(t) = x) Under the Pareto/NBD Model." Sept. 2006. Web.
#' \url{http://www.brucehardie.com/notes/012/}
#' @references Fader, Peter S., Bruce G.S. Hardie, and Kinshuk Jerath. "Deriving
#' an Expression for P (X(t, t + tau) = x) Under the Pareto/NBD Model." Sept.
#' 2006. Web. \url{http://www.brucehardie.com/notes/013/}
#'
#' @examples
#' # probability that a customer will make 10 repeat transactions in the
#' # time interval (1,2]
#' data("cdnowSummary")
#' cal.cbs <- cdnowSummary$cbs
#' params <- pnbd.EstimateParameters(cal.cbs = cal.cbs,
#' method = "L-BFGS-B",
#' hardie = TRUE)
#' pnbd.pmf.General(params, t.start=1, t.end=2, x=10, hardie = TRUE)
#' # probability that a customer will make no repeat transactions in the
#' # time interval (39,78]
#' pnbd.pmf.General(params,
#' t.start = 39,
#' t.end = 78,
#' x = 0,
#' hardie = TRUE)
pnbd.pmf.General <- function(params,
t.start,
t.end,
x,
hardie = TRUE) {
if (any(t.start > t.end)) {
stop("Error in pnbd.pmf.General: t.start > t.end.")
}
inputs <- try(dc.InputCheck(params = params,
func = "pnbd.pmf.General",
printnames = c("r", "alpha", "s", "beta"),
t.start = t.start,
t.end = t.end,
x = x))
if('try-error' == class(inputs)) return(str(inputs)$message)
t.start <- inputs$t.start
t.end <- inputs$t.end
x <- inputs$x
max.length <- nrow(inputs)
r <- params[1]
alpha <- params[2]
s <- params[3]
beta <- params[4]
equation.part.0 <- rep(0, max.length)
equation.part.0[x == 0] <- 1 - exp(s * log(beta) - s * log(beta + t.start))
## (t.end - t.start)^x is left outside the exp() in equation.part.1
## because when t.end = t.start and x = 0, exp() gets us into trouble:
## -- exp(0 * log(0)) = NaN;
## -- doing directly 0^0 instead gets us 0^0=1
## -- 1 is much better than NaN.
equation.part.1 <- exp(lgamma(r + x) -
lgamma(r) -
lfactorial(x) +
r * log(alpha) -
r * log(alpha + t.end - t.start) -
x * log(alpha + t.end - t.start) +
s * log(beta) -
s * log(beta + t.end)) *
(t.end - t.start)^x
equation.part.2 <- r * log(alpha) + s * log(beta) + lbeta(r + x, s + 1) - lbeta(r, s)
# Marshal the parameters of the hypergeometric and the
# denominator in the expressions of B1 and B2 shown in
# http://www.brucehardie.com/notes/013/Pareto_NBD_interval_pmf_rev.pdf
B1B2 <- function(hardie,
r,
alpha,
s,
beta,
x,
t.start,
t.end = 0,
ii = 0) {
myalpha <- alpha
mybeta <- beta + t.start
maxab <- max(myalpha, mybeta) + t.end
absab <- abs(myalpha - mybeta)
param2 <- s + 1
if (myalpha < mybeta) {
# < same as <= in the case of
# the hypergeometric, because =
# case is trivial.
param2 <- r + x
}
w <- r + s + ii
a <- w
b <- param2
c <- r + s + x + 1
z <- absab/maxab
den <- maxab^w
if(hardie == TRUE) return(h2f1(a, b, c, z)/den)
return(Re(hypergeo(a, b, c, z))/den)
}
B.1 <- mapply(x = inputs$x,
t.start = inputs$t.start,
B1B2,
hardie = hardie,
r = r,
alpha = alpha,
s = s,
beta = beta)
#B.1 <- B1B2(hardie, r, alpha, s, beta, x, t.start)
equation.part.2.summation <- rep(NA, max.length)
## In the paper, for i=0 we have t^i / i * B(r+s, i).
## the denominator reduces to:
## i * Gamma (r+s) * Gamma(i) / Gamma (r+s+i) :
## Gamma (r+s) * Gamma(i+1) / Gamma(r+s+i) :
## Gamma (r+s) * Gamma(1) / Gamma(r+s) :
## 1
## The 1 represents this reduced piece of the equation.
for (i in 1:max.length) {
ii <- c(1:x[i])
equation.part.2.summation[i] <- B1B2(hardie, r, alpha, s, beta, x[i], t.start[i], t.end[i], 0)
if (x[i] > 0) {
equation.part.2.summation[i] <- equation.part.2.summation[i] +
sum((t.end[i] - t.start[i])^ii/(ii * beta(r + s, ii)) *
B1B2(hardie, r, alpha, s, beta, x[i], t.start[i], t.end[i], ii))
}
}
return(equation.part.0 +
equation.part.1 +
exp(equation.part.2 +
log(B.1 - equation.part.2.summation)))
}
#' Pareto/NBD Conditional Expected Transactions
#'
#' Uses Pareto/NBD model parameters and a customer's past transaction behavior
#' to return the number of transactions they are expected to make in a given
#' time period.
#'
#' E\[X(T.cal, T.cal + T.star) | x, t.x, r, alpha, s, beta\]
#'
#' \code{T.star}, \code{x}, \code{t.x}, and \code{T.cal} may be vectors. The
#' standard rules for vector operations apply - if they are not of the same
#' length, shorter vectors will be recycled (start over at the first element)
#' until they are as long as the longest vector. It is advisable to keep vectors
#' to the same length and to use single values for parameters that are to be the
#' same for all calculations. If one of these parameters has a length greater
#' than one, the output will be a vector of probabilities.
#'
#' @param params Pareto/NBD parameters - a vector with r, alpha, s, and beta, in
#' that order. r and alpha are unobserved parameters for the NBD transaction
#' process. s and beta are unobserved parameters for the Pareto (exponential
#' gamma) dropout process.
#' @param T.star length of time for which we are calculating the expected number
#' of transactions.
#' @param x number of repeat transactions in the calibration period T.cal, or a
#' vector of calibration period frequencies.
#' @param t.x time of most recent repeat transaction, or a vector of recencies.
#' @param T.cal length of calibration period, or a vector of calibration period
#' lengths.
#' @param hardie if TRUE, have \code{\link{pnbd.PAlive}} use \code{\link{h2f1}}
#' instead of \code{\link[hypergeo]{hypergeo}}.
#'
#' @return Number of transactions a customer is expected to make in a time
#' period of length t, conditional on their past behavior. If any of the input
#' parameters has a length greater than 1, this will be a vector of expected
#' number of transactions.
#' @references Fader, Peter S., and Bruce G.S. Hardie. "A Note on Deriving the
#' Pareto/NBD Model and Related Expressions." November. 2005. Web.
#' \url{http://www.brucehardie.com/notes/008/}
#' @seealso \code{\link{pnbd.Expectation}}
#'
#' @examples
#' params <- c(0.55, 10.56, 0.61, 11.64)
#' # Number of transactions a customer is expected to make in 2 time
#' # intervals, given that they made 10 repeat transactions in a time period
#' # of 39 intervals, with the 10th repeat transaction occurring in the 35th
#' # interval.
#' pnbd.ConditionalExpectedTransactions(params,
#' T.star = 2,
#' x = 10,
#' t.x = 35,
#' T.cal = 39,
#' hardie = TRUE)
#'
#' # We can also compare expected transactions across different
#' # calibration period behaviors:
#' pnbd.ConditionalExpectedTransactions(params,
#' T.star = 2,
#' x = 5:20,
#' t.x = 25,
#' T.cal = 39,
#' hardie = TRUE)
pnbd.ConditionalExpectedTransactions <- function(params,
T.star,
x,
t.x,
T.cal,
hardie = TRUE) {
inputs <- try(dc.InputCheck(params = params,
func = "pnbd.ConditionalExpectedTransactions",
printnames = c("r", "alpha", "s", "beta"),
T.star = T.star,
x = x,
t.x = t.x,
T.cal = T.cal))
if('try-error' == class(inputs)) return(str(inputs)$message)
T.star <- inputs$T.star
x <- inputs$x
t.x <- inputs$t.x
T.cal <- inputs$T.cal
r <- params[1]
alpha <- params[2]
s <- params[3]
beta <- params[4]
P1 <- (r + x) * (beta + T.cal)/((alpha + T.cal) * (s - 1))
P2 <- (1 - ((beta + T.cal)/(beta + T.cal + T.star))^(s - 1))
P3 <- pnbd.PAlive(params = params,
x = x,
t.x = t.x,
T.cal = T.cal,
hardie = hardie)
return(P1 * P2 * P3)
}
#' Pareto/NBD Probability Mass Function
#'
#' Probability mass function for the Pareto/NBD.
#'
#' P(X(t)=x | r, alpha, s, beta). Returns the probability that a customer makes
#' x repeat transactions in the time interval (0, t].
#'
#' Parameters \code{t} and \code{x} may be vectors. The standard rules for
#' vector operations apply - if they are not of the same length, the shorter
#' vector will be recycled (start over at the first element) until it is as long
#' as the longest vector. It is advisable to keep vectors to the same length and
#' to use single values for parameters that are to be the same for all
#' calculations. If one of these parameters has a length greater than one, the
#' output will be a vector of probabilities.
#'
#' @param params Pareto/NBD parameters - a vector with r, alpha, s, and beta, in
#' that order. r and alpha are unobserved parameters for the NBD transaction
#' process. s and beta are unobserved parameters for the Pareto (exponential
#' gamma) dropout process.
#' @param t length end of time period for which probability is being computed.
#' May also be a vector.
#' @param x number of repeat transactions by a random customer in the period
#' defined by t. May also be a vector.
#' @param hardie if TRUE, have \code{\link{pnbd.pmf.General}} use
#' \code{\link{h2f1}} instead of \code{\link[hypergeo]{hypergeo}}.
#'
#' @return Probability of X(t)=x conditional on model parameters. If t and/or x
#' has a length greater than one, a vector of probabilities will be returned.
#' @references Fader, Peter S., and Bruce G.S. Hardie. “Deriving an Expression
#' for P (X(t) = x) Under the Pareto/NBD Model.” Sept. 2006. Web.
#' \url{http://www.brucehardie.com/notes/012/}
#'
#' @examples
#' params <- c(0.55, 10.56, 0.61, 11.64)
#' # probability that a customer will make 10 repeat transactions in the
#' # time interval (0,2]
#' pnbd.pmf(params, t=2, x=10, hardie = TRUE)
#' # probability that a customer will make no repeat transactions in the
#' # time interval (0,39]
#' pnbd.pmf(params, t=39, x=0, hardie = TRUE)
#'
#' # Vectors may also be used as arguments:
#' pnbd.pmf(params = params,
#' t = 30,
#' x = 11:20,
#' hardie = TRUE)
pnbd.pmf <- function(params,
t,
x,
hardie = TRUE) {
inputs <- try(dc.InputCheck(params = params,
func = "pnbd.pmf",
printnames = c("r", "alpha", "s", "beta"),
t = t,
x = x))
if('try-error' == class(inputs)) return(str(inputs)$message)
pnbd.pmf.General(params = params,
t.start = 0,
t.end = inputs$t,
x = inputs$x,
hardie = hardie)
}
#' Pareto/NBD Expectation
#'
#' Returns the number of repeat transactions that a randomly chosen customer
#' (for whom we have no prior information) is expected to make in a given time
#' period.
#'
#' E(X(t) | r, alpha, s, beta)
#'
#' @inheritParams pnbd.LL
#' @param t The length of time for which we are calculating the expected number
#' of repeat transactions.
#' @return Number of repeat transactions a customer is expected to make in a
#' time period of length t.
#' @references Fader, Peter S., and Bruce G.S. Hardie. "A Note on Deriving the
#' Pareto/NBD Model and Related Expressions." November. 2005. Web.
#' \url{http://www.brucehardie.com/notes/008/}
#' @seealso [`pnbd.ConditionalExpectedTransactions`]
#' @examples
#' params <- c(0.55, 10.56, 0.61, 11.64)
#'
#' # Number of repeat transactions a customer is expected to make in 2 time intervals.
#' pnbd.Expectation(params = params,
#' t = 2)
#'
#' # We can also compare expected transactions over time:
#' pnbd.Expectation(params = params,
#' t = 1:10)
#' @md
pnbd.Expectation <- function(params, t) {
dc.check.model.params(printnames = c("r", "alpha", "s", "beta"),
params = params,
func = "pnbd.Expectation")
if (any(t < 0) || !is.numeric(t))
stop("t must be numeric and may not contain negative numbers.")
r = params[1]
alpha = params[2]
s = params[3]
beta = params[4]
return((r * beta)/(alpha * (s - 1)) * (1 - (beta/(beta + t))^(s - 1)))
}
#' Pareto/NBD Expected Cumulative Transactions
#'
#' Calculates the expected cumulative total repeat transactions by all customers
#' for the calibration and holdout periods.
#'
#' The function automatically divides the total period up into n.periods.final
#' time intervals. n.periods.final does not have to be in the same unit of time
#' as the T.cal data. For example: - if your T.cal data is in weeks, and you
#' want cumulative transactions per week, n.periods.final would equal T.star. -
#' if your T.cal data is in weeks, and you want cumulative transactions per day,
#' n.periods.final would equal T.star * 7.
#'
#' The holdout period should immediately follow the calibration period. This
#' function assume that all customers' calibration periods end on the same date,
#' rather than starting on the same date (thus customers' birth periods are
#' determined using max(T.cal) - T.cal rather than assuming that it is 0).
#'
#' @inheritParams pnbd.LL
#' @param T.tot End of holdout period. Must be a single value, not a vector.
#' @param n.periods.final Number of time periods in the calibration and holdout
#' periods. See details.
#' @return Vector of expected cumulative total repeat transactions by all
#' customers.
#' @seealso [`pnbd.Expectation`]
#' @examples
#' data(cdnowSummary)
#'
#' cal.cbs <- cdnowSummary$cbs
#' # cal.cbs already has column names required by method
#'
#' params <- c(0.55, 10.56, 0.61, 11.64)
#'
#' # Returns a vector containing cumulative repeat transactions for 546 days.
#' # All parameters are in weeks; the calibration period lasted 39 weeks
#' # and the holdout period another 39.
#' pnbd.ExpectedCumulativeTransactions(params = params,
#' T.cal = cal.cbs[,"T.cal"],
#' T.tot = 78,
#' n.periods.final = 546)
#' @md
pnbd.ExpectedCumulativeTransactions <- function(params,
T.cal,
T.tot,
n.periods.final) {
inputs <- try(dc.InputCheck(params = params,
func = "pnbd.ExpectedCumulativeTransactions",
printnames = c("r", "alpha", "s", "beta"),
T.cal = T.cal,
T.tot = T.tot,
n.periods.final = n.periods.final))
if('try-error' == class(inputs)) return(str(inputs)$message)
stopit <- "must be a single numeric value and may not be negative."
if (length(T.tot) > 1) stop(paste("T.tot", stopit, sep = " "))
if (length(n.periods.final) > 1) stop(paste("n.periods.final", stopit, sep = " "))
## Divide up time into equal intervals
intervals <- seq(T.tot/n.periods.final,
T.tot,
length.out = n.periods.final)
cust.birth.periods <- max(T.cal) - T.cal
expected.transactions <- sapply(intervals,
function(interval) {
if (interval <= min(cust.birth.periods))
return(0)
sum(pnbd.Expectation(params,
interval - cust.birth.periods[cust.birth.periods <= interval]))
})
return(expected.transactions)
}
#' Pareto/NBD Plot Frequency in Calibration Period
#'
#' Plots a histogram and returns a matrix comparing the actual and expected
#' number of customers who made a certain number of repeat transactions in the
#' calibration period, binned according to calibration period frequencies.
#'
#' This function requires a censor number, which cannot be higher than the
#' highest frequency in the calibration period CBS. The output matrix will have
#' (censor + 1) bins, starting at frequencies of 0 transactions and ending at a
#' bin representing calibration period frequencies at or greater than the censor
#' number. The plot may or may not include a bin for zero frequencies, depending
#' on the plotZero parameter.
#'
#' @param params Pareto/NBD parameters - a vector with r, alpha, s, and beta, in
#' that order. r and alpha are unobserved parameters for the NBD transaction
#' process. s and beta are unobserved parameters for the Pareto (exponential
#' gamma) dropout process.
#' @param cal.cbs calibration period CBS (customer by sufficient statistic). It
#' must contain columns for frequency ("x") and total time observed ("T.cal").
#' @param censor integer used to censor the data. See details.
#' @param hardie if TRUE, have \code{\link{pnbd.pmf}} use \code{\link{h2f1}}
#' instead of \code{\link[hypergeo]{hypergeo}}.
#' @param plotZero if FALSE, the histogram will exclude the zero bin.