-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_data.py
333 lines (267 loc) · 10.4 KB
/
generate_data.py
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
# -*- coding: utf-8 -*-
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
import numpy as np
from numpy import random
import pandas as pd
def beta_geometric_nbd_model(T, r, alpha, a, b, size=1):
"""
Generate artificial data according to the BG/NBD model.
See [1] for model details
Parameters
----------
T: array_like
The length of time observing new customers.
r, alpha, a, b: float
Parameters in the model. See [1]_
size: int, optional
The number of customers to generate
Returns
-------
DataFrame
With index as customer_ids and the following columns:
'frequency', 'recency', 'T', 'lambda', 'p', 'alive', 'customer_id'
References
----------
.. [1]: '"Counting Your Customers" the Easy Way: An Alternative to the Pareto/NBD Model'
(http://brucehardie.com/papers/bgnbd_2004-04-20.pdf)
"""
if type(T) in [float, int]:
T = T * np.ones(size)
else:
T = np.asarray(T)
probability_of_post_purchase_death = random.beta(a, b, size=size)
lambda_ = random.gamma(r, scale=1.0 / alpha, size=size)
columns = ["frequency", "recency", "T", "lambda", "p", "alive", "customer_id"]
df = pd.DataFrame(np.zeros((size, len(columns))), columns=columns)
for i in range(size):
p = probability_of_post_purchase_death[i]
l = lambda_[i]
# hacky until I can find something better
times = []
next_purchase_in = random.exponential(scale=1.0 / l)
alive = True
while (np.sum(times) + next_purchase_in < T[i]) and alive:
times.append(next_purchase_in)
next_purchase_in = random.exponential(scale=1.0 / l)
alive = random.random() > p
times = np.array(times).cumsum()
df.iloc[i] = (
np.unique(np.array(times).astype(int)).shape[0],
np.max(times if times.shape[0] > 0 else 0),
T[i],
l,
p,
alive,
i,
)
return df.set_index("customer_id")
def beta_geometric_nbd_model_transactional_data(T, r, alpha, a, b, observation_period_end="2019-1-1", freq="D", size=1):
"""
Generate artificial transactional data according to the BG/NBD model.
See [1] for model details
Parameters
----------
T: int, float or array_like
The length of time observing new customers.
r, alpha, a, b: float
Parameters in the model. See [1]_
observation_period_end: date_like
The date observation ends
freq: string, optional
Default 'D' for days, 'W' for weeks, 'h' for hours
size: int, optional
The number of customers to generate
Returns
-------
DataFrame
The following columns:
'customer_id', 'date'
References
----------
.. [1]: '"Counting Your Customers" the Easy Way: An Alternative to the Pareto/NBD Model'
(http://brucehardie.com/papers/bgnbd_2004-04-20.pdf)
"""
observation_period_end = pd.to_datetime(observation_period_end)
if type(T) in [float, int]:
start_date = [observation_period_end - pd.Timedelta(T - 1, unit=freq)] * size
T = T * np.ones(size)
else:
start_date = [observation_period_end - pd.Timedelta(T[i] - 1, unit=freq) for i in range(size)]
T = np.asarray(T)
probability_of_post_purchase_death = random.beta(a, b, size=size)
lambda_ = random.gamma(r, scale=1.0 / alpha, size=size)
columns = ["customer_id", "date"]
df = pd.DataFrame(columns=columns)
for i in range(size):
s = start_date[i]
p = probability_of_post_purchase_death[i]
l = lambda_[i]
age = T[i]
purchases = [[i, s - pd.Timedelta(1, unit=freq)]]
next_purchase_in = random.exponential(scale=1.0 / l)
alive = True
while next_purchase_in < age and alive:
purchases.append([i, s + pd.Timedelta(next_purchase_in, unit=freq)])
next_purchase_in += random.exponential(scale=1.0 / l)
alive = random.random() > p
df = df.append(pd.DataFrame(purchases, columns=columns))
return df.reset_index(drop=True)
def pareto_nbd_model(T, r, alpha, s, beta, size=1):
"""
Generate artificial data according to the Pareto/NBD model.
See [2]_ for model details.
Parameters
----------
T: array_like
The length of time observing new customers.
r, alpha, s, beta: float
Parameters in the model. See [1]_
size: int, optional
The number of customers to generate
Returns
-------
:obj: DataFrame
with index as customer_ids and the following columns:
'frequency', 'recency', 'T', 'lambda', 'mu', 'alive', 'customer_id'
References
----------
.. [2]: Fader, Peter S. and Bruce G. S. Hardie (2005), "A Note on Deriving the Pareto/NBD Model
and Related Expressions," <http://brucehardie.com/notes/009/>.
"""
if type(T) in [float, int]:
T = T * np.ones(size)
else:
T = np.asarray(T)
lambda_ = random.gamma(r, scale=1.0 / alpha, size=size)
mus = random.gamma(s, scale=1.0 / beta, size=size)
columns = ["frequency", "recency", "T", "lambda", "mu", "alive", "customer_id"]
df = pd.DataFrame(np.zeros((size, len(columns))), columns=columns)
for i in range(size):
l = lambda_[i]
mu = mus[i]
time_of_death = random.exponential(scale=1.0 / mu)
# hacky until I can find something better
times = []
next_purchase_in = random.exponential(scale=1.0 / l)
while np.sum(times) + next_purchase_in < min(time_of_death, T[i]):
times.append(next_purchase_in)
next_purchase_in = random.exponential(scale=1.0 / l)
times = np.array(times).cumsum()
df.iloc[i] = (
np.unique(np.array(times).astype(int)).shape[0],
np.max(times if times.shape[0] > 0 else 0),
T[i],
l,
mu,
time_of_death > T[i],
i,
)
return df.set_index("customer_id")
def modified_beta_geometric_nbd_model(T, r, alpha, a, b, size=1):
"""
Generate artificial data according to the MBG/NBD model.
See [3]_, [4]_ for model details
Parameters
----------
T: array_like
The length of time observing new customers.
r, alpha, a, b: float
Parameters in the model. See [1]_
size: int, optional
The number of customers to generate
Returns
-------
DataFrame
with index as customer_ids and the following columns:
'frequency', 'recency', 'T', 'lambda', 'p', 'alive', 'customer_id'
References
----------
.. [1]: '"Counting Your Customers" the Easy Way: An Alternative to the Pareto/NBD Model'
(http://brucehardie.com/papers/bgnbd_2004-04-20.pdf)
.. [2] Batislam, E.P., M. Denizel, A. Filiztekin (2007),
"Empirical validation and comparison of models for customer base analysis,"
International Journal of Research in Marketing, 24 (3), 201-209.
"""
if type(T) in [float, int]:
T = T * np.ones(size)
else:
T = np.asarray(T)
probability_of_post_purchase_death = random.beta(a, b, size=size)
lambda_ = random.gamma(r, scale=1.0 / alpha, size=size)
columns = ["frequency", "recency", "T", "lambda", "p", "alive", "customer_id"]
df = pd.DataFrame(np.zeros((size, len(columns))), columns=columns)
for i in range(size):
p = probability_of_post_purchase_death[i]
l = lambda_[i]
# hacky until I can find something better
times = []
next_purchase_in = random.exponential(scale=1.0 / l)
alive = random.random() > p # essentially the difference between this model and BG/NBD
while (np.sum(times) + next_purchase_in < T[i]) and alive:
times.append(next_purchase_in)
next_purchase_in = random.exponential(scale=1.0 / l)
alive = random.random() > p
times = np.array(times).cumsum()
df.iloc[i] = (
np.unique(np.array(times).astype(int)).shape[0],
np.max(times if times.shape[0] > 0 else 0),
T[i],
l,
p,
alive,
i,
)
return df.set_index("customer_id")
def beta_geometric_beta_binom_model(N, alpha, beta, gamma, delta, size=1):
"""
Generate artificial data according to the Beta-Geometric/Beta-Binomial
Model.
You may wonder why we can have frequency = n_periods, when frequency excludes their
first order. When a customer purchases something, they are born, _and in the next
period_ we start asking questions about their alive-ness. So really they customer has
bought frequency + 1, and been observed for n_periods + 1
Parameters
----------
N: array_like
Number of transaction opportunities for new customers.
alpha, beta, gamma, delta: float
Parameters in the model. See [1]_
size: int, optional
The number of customers to generate
Returns
-------
DataFrame
with index as customer_ids and the following columns:
'frequency', 'recency', 'n_periods', 'lambda', 'p', 'alive', 'customer_id'
References
----------
.. [1] Fader, Peter S., Bruce G.S. Hardie, and Jen Shang (2010),
"Customer-Base Analysis in a Discrete-Time Noncontractual Setting,"
Marketing Science, 29 (6), 1086-1108.
"""
if type(N) in [float, int, np.int64]:
N = N * np.ones(size)
else:
N = np.asarray(N)
probability_of_post_purchase_death = random.beta(a=alpha, b=beta, size=size)
thetas = random.beta(a=gamma, b=delta, size=size)
columns = ["frequency", "recency", "n_periods", "p", "theta", "alive", "customer_id"]
df = pd.DataFrame(np.zeros((size, len(columns))), columns=columns)
for i in range(size):
p = probability_of_post_purchase_death[i]
theta = thetas[i]
# hacky until I can find something better
current_t = 0
alive = True
times = []
while current_t < N[i] and alive:
alive = random.binomial(1, theta) == 0
if alive and random.binomial(1, p) == 1:
times.append(current_t)
current_t += 1
# adding in final death opportunity to agree with [1]
if alive:
alive = random.binomial(1, theta) == 0
df.iloc[i] = len(times), times[-1] + 1 if len(times) != 0 else 0, N[i], p, theta, alive, i
return df