File size: 24,090 Bytes
607b465
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Attribution Modeling Increases Efficiency of Bidding in Display Advertising\n",
    "Eustache Diemert*, Julien Meynet* (Criteo Research), Damien Lefortier (Facebook), Pierre Galland (Criteo)\n",
    "*authors contributed equally.\n",
    "\n",
    "This work was published in:\n",
    "[2017 AdKDD & TargetAd Workshop, in conjunction with\n",
    "The 23rd ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD 2017)](https://adkdd17.wixsite.com/adkddtargetad2017)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "  * This code includes all needed material to reproduce results reported in the paper. This dataset can also be used for further research like: testing alternative attribution models, offline metrics, etc..\n",
    "  * For details about the content of the Dataset, refer to the README file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Preprocessing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%pylab inline\n",
    "import pandas as pd\n",
    "plt.style.use('ggplot')\n",
    "from scipy.optimize import minimize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "DATA_FILE='criteo_attribution_dataset.tsv.gz'\n",
    "df = pd.read_csv(DATA_FILE, sep='\\t', compression='gzip')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "df['day'] = np.floor(df.timestamp / 86400.).astype(int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "df.day.hist(bins=len(df.day.unique()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "df['gap_click_sale'] = -1\n",
    "df.loc[df.conversion == 1, 'gap_click_sale'] = df.conversion_timestamp - df.timestamp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "FEATURES = ['campaign', 'cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', \n",
    "            'cat7', 'cat8']\n",
    "INFOS = ['cost', 'cpo', 'time_since_last_click']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "df['last_click'] = df.attribution * (df.click_pos == df.click_nb - 1).astype(int)\n",
    "df['first_click'] = df.attribution * (df.click_pos == 0).astype(int)\n",
    "df['all_clicks'] = df.attribution\n",
    "df['uniform'] = df.attribution / (df.click_nb).astype(float)\n",
    "INFOS += ['last_click', 'first_click', 'all_clicks', 'uniform']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Learning / Validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.feature_extraction import FeatureHasher\n",
    "from sklearn.metrics import log_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def bootstrap(data, num_samples, statistic, alpha):\n",
    "    \"\"\"Returns bootstrap estimate of 100.0*(1-alpha) CI for statistic.\"\"\"\n",
    "    n = len(data)\n",
    "    data = np.array(data)\n",
    "    stats = []\n",
    "    for _ in range(num_samples):\n",
    "        idx = np.random.randint(0, n, n)\n",
    "        samples = data[idx]\n",
    "        stats += [statistic(samples)]\n",
    "    stats = np.array(sorted(stats))\n",
    "    return (stats[int((alpha/2.0)*num_samples)],\n",
    "            stats[int((1-alpha/2.0)*num_samples)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attribution model\n",
    "Learns exponential decay lambda parameter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def attr_nllh(l,x,y):\n",
    "    loss = 0.0\n",
    "    lamb = l[0]\n",
    "    n = x.shape[0]\n",
    "    for i in range(n):\n",
    "        if y[i] == 1:\n",
    "            loss += lamb*x[i]\n",
    "        else:\n",
    "            loss -= np.log(1 - np.exp(-lamb*x[i]))  \n",
    "    return loss/float(n)\n",
    "\n",
    "def attr_nllh_grad(l,x,y):\n",
    "    grad = 0.0\n",
    "    lamb = l[0]\n",
    "    n = x.shape[0]\n",
    "    for i in range(n):\n",
    "        grad += x[i]*y[i] / (1 - np.exp(-lamb*x[i]))\n",
    "    return np.array([grad/float(n)])\n",
    "\n",
    "\n",
    "def optimize_lambda(tts, attrib):\n",
    "    return minimize(attr_nllh, 1e-3, method='L-BFGS-B', jac=attr_nllh_grad, \n",
    "                    options={'disp': True, 'maxiter': 20 }, bounds=((1e-15, 1e-4),), \n",
    "                    args=(tts,attrib)).x[0]\n",
    "\n",
    "def learn_attribution_model(df_view, test_day, learning_duration, \n",
    "                            verbose=False, ci=False, rescale=1., \n",
    "                            optimizer=optimize_lambda):\n",
    "    df_train = df_view[(df_view.day >= test_day - learning_duration) & (df_view.day < test_day)]\n",
    "    df_conv = df_train[df_train.click_pos == df_train.click_nb - 1]\n",
    "    x = df_conv.gap_click_sale.values\n",
    "    y = df_conv.attribution.values \n",
    "    \n",
    "    avg_tts = x.mean()\n",
    "    tts_ci = bootstrap(x, 100, np.mean, .05)\n",
    "    tts_ci = tts_ci[1] - tts_ci[0]\n",
    "\n",
    "    lamb = optimize_lambda(x, y)\n",
    "    \n",
    "    lambs = []\n",
    "    n_bootstraps = 30\n",
    "    alpha=.05\n",
    "    if ci:\n",
    "        for _ in range(n_bootstraps):\n",
    "            idx = np.random.randint(0, x.shape[0], x.shape)\n",
    "            xx = x[idx]\n",
    "            yy = y[idx]\n",
    "            lambs += [optimize_lambda(xx, yy)]\n",
    "\n",
    "    if verbose:\n",
    "        print('\\t\\t-avg_tts', avg_tts, '+/-', tts_ci, \n",
    "              ' = ', avg_tts / 3600., 'hours = ', avg_tts / 86400., 'days')\n",
    "        if ci:\n",
    "            print('\\t\\t-lambda', lamb, '+/-', (lambs[int((1-alpha/2.)*n_bootstraps)] - lambs[int((alpha/2.)*n_bootstraps)]))\n",
    "        else:\n",
    "            print('\\t\\t-lambda', lamb)\n",
    "    \n",
    "    return avg_tts, lamb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "global_avg_tts, global_lamb =  learn_attribution_model(df, 21, 20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Compute AA attributions on full dataset\n",
    "As explained in the paper, the exponential decay parameter is satble throughout the days. For reducing computation complexity we compute the exponential-based attributions on the full dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def compute_aa_attributions(test_info, normalize=True):\n",
    "    test_info['idx'] = test_info.index\n",
    "    converted =  test_info[test_info.all_clicks==1]\n",
    "    # to propoerly compute  normalized attribution factors, we have to reconstruct the timelines for each conversion\n",
    "    conversion_ids = converted['conversion_id'].unique()\n",
    "    # now reconstruct timeline and apply attribution\n",
    "    by_conversion = converted[['conversion_id', 'timestamp', 'idx', 'bf_pred', 'time_since_last_click', 'last_click']].groupby('conversion_id')\n",
    "    new_clicks_data = []\n",
    "    \n",
    "    s_attr = []\n",
    "    s_attr_lc = []\n",
    "    # for each conversion compute attribution for each click\n",
    "    for conv, evts in by_conversion:\n",
    "        sorted_clicks = sorted(evts.values.tolist(), key=lambda x: x[1])\n",
    "        bf_pred = [_[3] for _ in sorted_clicks]\n",
    "        sum_bf = np.sum(bf_pred)\n",
    "        sum_lc = np.sum([_[5] for _ in sorted_clicks])\n",
    "        sum_attr = 0.0\n",
    "        for pos, (_, _, idx_, bf_, tslc_, lc_) in enumerate(sorted_clicks):\n",
    "            aa_attr = bf_pred[pos]\n",
    "            if normalize:\n",
    "                if sum_bf>0.0:\n",
    "                    aa_attr/=sum_bf\n",
    "                else:\n",
    "                    aa_attr = 0.0\n",
    "            sum_attr += aa_attr\n",
    "            new_clicks_data.append((idx_, aa_attr))\n",
    "        s_attr.append(sum_attr)\n",
    "        s_attr_lc.append(sum_lc)\n",
    "    \n",
    "    # now for each click, apply attribution from computed data\n",
    "    new_clicks_df = pd.DataFrame(columns=['click_idx', 'aa_attribution'])\n",
    "    cidx, attr = zip(*new_clicks_data)\n",
    "    new_clicks_df['click_idx'] = cidx\n",
    "    new_clicks_df['aa_attribution'] = attr\n",
    "    new_clicks_df = new_clicks_df.set_index('click_idx')\n",
    "    joined = test_info.join(new_clicks_df)\n",
    "    joined['aa_attribution'] = joined['aa_attribution'].fillna(value = 0.0)\n",
    "    return joined['aa_attribution']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#learn global attribution model\n",
    "avg_tts, lamb = learn_attribution_model(df, 21, 20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# compute the bid factor from aa attribution for each display\n",
    "gap_test = df.time_since_last_click.values\n",
    "previous_tslc_mask = (df.time_since_last_click >=0).astype(float)\n",
    "attr_pred = np.exp(-lamb*gap_test)\n",
    "attr_pred *= previous_tslc_mask\n",
    "bf_pred = 1 - attr_pred\n",
    "df['bf_pred'] = bf_pred\n",
    "df['AA_normed'] = compute_aa_attributions(df, normalize=True)\n",
    "df['AA_not_normed'] = compute_aa_attributions(df, normalize=False)\n",
    "INFOS += ['bf_pred', 'AA_normed', 'AA_not_normed']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Validation Code\n",
    "Utility methods for performing validation (test on 1 day, learn on previous x days and slide)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_train_test_slice(df_view, test_day, learning_duration, label, features=None, \n",
    "                         hash_space=2**24, nrows=None, infos=None):\n",
    "    df_test = df_view[df_view.day == test_day]\n",
    "    if nrows is not None:\n",
    "        df_test = df_test[:nrows]\n",
    "    if features is None:\n",
    "        features = FEATURES\n",
    "    if infos is None:\n",
    "        infos = INFOS\n",
    "    df_train = df_view[(df_view.day >= test_day - learning_duration) & (df_view.day < test_day)]\n",
    "    if nrows is not None:\n",
    "        df_train = df_train[:nrows]\n",
    "  \n",
    "    X_train = df_train[features]\n",
    "    X_test = df_test[features]\n",
    "    \n",
    "    hasher = FeatureHasher(n_features=hash_space, non_negative=1)\n",
    "    \n",
    "    def to_dict_values(df_view):\n",
    "        return [dict([(_[0]+str(_[1]),1) for _ in zip(features,l)]) for l in df_view.values]\n",
    "    \n",
    "    X_train_h = hasher.fit_transform(to_dict_values(X_train))\n",
    "    X_test_h = hasher.transform(to_dict_values(X_test))\n",
    "    y_train = df_train[label]\n",
    "    y_test = df_test[label]\n",
    "    return (X_train_h, y_train), (X_test_h, y_test), df_test[infos], df_train.last_click.mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Compute Utilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from scipy.special import gammainc\n",
    "def empirical_utility(a, v, c, p):\n",
    "    won = np.array(p*v > c, dtype=np.int)\n",
    "    return (a*v)*won, -c*won\n",
    "\n",
    "def expected_utility(a, v, c, p, beta=1000):\n",
    "    return a*v*gammainc(beta*c+1, beta*p*v) - ((beta*c+1)/beta)*gammainc(beta*c+2, beta*p*v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def evaluate_utility(y_pred, utilities, betas, test_info):\n",
    "    partial_score = dict()\n",
    "    for utility in utilities:\n",
    "        attribution = test_info[utility]\n",
    "        for beta in betas:\n",
    "            if np.isinf(beta):\n",
    "                est_utility = empirical_utility(attribution, test_info.cpo, test_info.cost, y_pred)\n",
    "            else:\n",
    "                est_utility = expected_utility(attribution, test_info.cpo, test_info.cost, y_pred, beta=beta)\n",
    "            beta_str = str(beta) if not np.isinf(beta) else 'inf'\n",
    "            partial_score['utility-'+utility+'-beta'+beta_str] = est_utility\n",
    "    return partial_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_naive_baseline(y_train, X_test):\n",
    "    return np.mean(y_train)*np.ones(X_test.shape[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def evaluate_day_for_bidder(df_view, test_day, learning_duration, bidder, utilities, betas,\n",
    "                            hash_space=None, features=None, clf=None, AA_bidder_label=None, recalibrate=True):\n",
    "    score = dict()\n",
    "    bid_profile = dict()\n",
    "    label = bidder\n",
    "    if bidder == 'AA':\n",
    "        label = AA_bidder_label\n",
    "    # get data slice\n",
    "    (X_train, y_train), (X_test, y_test), test_info, y_train_lc_mean = get_train_test_slice(df_view,\n",
    "                                                                           test_day,\n",
    "                                                                           learning_duration,\n",
    "                                                                           label=label, \n",
    "                                                                           hash_space = hash_space,\n",
    "                                                                           features=features)           \n",
    "    \n",
    "    # learn the model\n",
    "    clf.fit(X_train, y_train)\n",
    "    \n",
    "    # get test predictions\n",
    "    y_pred = clf.predict_proba(X_test)[:,1]            \n",
    "    \n",
    "    # if aa bidder: modulate the bids by bid_factor computed from attribution model\n",
    "    if bidder == 'AA':\n",
    "        y_pred *= test_info['bf_pred']\n",
    "    \n",
    "    # compute the loss\n",
    "    loss = log_loss(y_test, y_pred, normalize=0)\n",
    "    \n",
    "    # loss of baseline model\n",
    "    baseline_loss = log_loss(y_test, get_naive_baseline(y_train, X_test), normalize=0)\n",
    "    score['nllh'] = loss\n",
    "    score['nllh_naive'] = baseline_loss\n",
    "    \n",
    "    # do we recalibrate output? (i.e recalibrate mean prediction). This is usually done by a control system.\n",
    "    if recalibrate:\n",
    "        y_pred *= (y_train_lc_mean / y_pred.mean())\n",
    "    \n",
    "    #how many displays are won?\n",
    "    won = (y_pred*test_info.cpo > test_info.cost).astype(int)\n",
    "    score['won'] = np.sum(won)\n",
    "    score['n_auctions'] = y_pred.shape[0]\n",
    "    \n",
    "    # compute the scores on this slice\n",
    "    score.update(evaluate_utility(y_pred, utilities, betas, test_info))\n",
    "    \n",
    "    #store bid profiles\n",
    "    bid_profile['time_since_last_click'] = test_info.time_since_last_click\n",
    "    bid_profile['bid'] = y_pred\n",
    "    \n",
    "    return score, bid_profile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Simple utility functions to manipulate scores"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def merge_utility_score(score):\n",
    "    updates = dict()\n",
    "    for k,v in score.items():\n",
    "        if not 'utility' in k:\n",
    "            continue\n",
    "        if 'inf' in k:\n",
    "            revenue, cost = v\n",
    "            updates[k] = np.sum(cost) + np.sum(revenue)\n",
    "            updates[k+'~revenue'] = np.sum(revenue)\n",
    "            updates[k+'~cost'] = np.sum(cost)\n",
    "            v = revenue + cost\n",
    "        else:\n",
    "            updates[k] = np.sum(v)\n",
    "        bounds = bootstrap(v, 100, np.sum, .05)\n",
    "        delta = (bounds[1]-bounds[0])/2.\n",
    "        updates[k+'-delta'] = delta\n",
    "    score.update(updates)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def update_score(partial_score, score):\n",
    "    for k, v in partial_score.items():\n",
    "        if 'utility' in k:\n",
    "            if 'inf' in k:\n",
    "                revenue, cost = v\n",
    "                print('\\t\\t', k, np.sum(cost)+np.sum(revenue))\n",
    "                current_revenue, current_cost = score.get(k, (np.array([]),np.array([])))\n",
    "                score[k] = (\n",
    "                    np.append(current_revenue, revenue),\n",
    "                    np.append(current_cost, cost)\n",
    "                )\n",
    "            else:\n",
    "                print('\\t\\t', k, np.sum(v))\n",
    "                score[k] = np.append(score.get(k, np.array([])), v)\n",
    "        else:\n",
    "            print('\\t\\t', k, v)\n",
    "            score[k] = score.get(k, 0) + v"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Evaluate several bidders on several utility metric variants"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from datetime import datetime, timedelta\n",
    "def evaluate_slices(df_view,\n",
    "                    bidders=['last_click', 'first_click', 'AA'],\n",
    "                    utilities=['last_click','first_click', 'AA_normed', 'AA_not_normed'],\n",
    "                    betas=[np.inf, 10, 1000],\n",
    "                    test_days=[22],\n",
    "                    learning_duration=21,\n",
    "                    hash_space=2**24,\n",
    "                    features=None,\n",
    "                    AA_bidder_label='all_clicks',\n",
    "                    clf = LogisticRegression(solver='lbfgs', n_jobs=4),\n",
    "                    recalibrate = True):\n",
    "    bid_profiles = []\n",
    "    scores = []\n",
    "    for bidder in bidders:\n",
    "        print ('*'*80)\n",
    "        print(\"EVALUATING BIDDER:\", bidder)\n",
    "        score = dict()\n",
    "        bid_profile = dict()\n",
    "        for test_day in test_days:\n",
    "            start = datetime.now()\n",
    "            print('\\t- day:', test_day)\n",
    "            partial_score, partial_bid_profile = evaluate_day_for_bidder(\n",
    "                df_view, test_day, learning_duration, bidder, \n",
    "                utilities, betas,\n",
    "                hash_space=hash_space, features=features, clf=clf, \n",
    "                AA_bidder_label=AA_bidder_label, recalibrate=recalibrate\n",
    "            )\n",
    "            update_score(partial_score, score)\n",
    "            for k, v in partial_bid_profile.items():\n",
    "                bid_profile[k] = np.append(bid_profile.get(k, np.array([])), v)\n",
    "            print('\\t- took', datetime.now() - start)\n",
    "        score['bidder'] = bidder\n",
    "        bid_profile['bidder'] = bidder\n",
    "        score['nllh_comp_vn'] = (score['nllh_naive'] - score['nllh']) / np.abs(score['nllh_naive'])\n",
    "        score['win_rate'] = score['won'] / score['n_auctions']\n",
    "        merge_utility_score(score)\n",
    "        scores.append(score)\n",
    "        bid_profiles.append(bid_profile)\n",
    "    return pd.DataFrame(scores), pd.DataFrame(bid_profiles)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run & Results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "#full run\n",
    "if False:\n",
    "    scores, bid_profiles = evaluate_slices(df,\n",
    "                                       bidders=['last_click',\n",
    "                                                'first_click',\n",
    "                                                'AA'],\n",
    "                                       utilities=['last_click',\n",
    "                                                  'first_click',\n",
    "                                                  'AA_normed',\n",
    "                                                  'AA_not_normed'],\n",
    "                                       test_days=range(22,29),\n",
    "                                       learning_duration=21,\n",
    "                                       hash_space = 2**18,\n",
    "                                       AA_bidder_label='all_clicks')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "#simple debug run\n",
    "if True:\n",
    "    scores, bid_profiles = evaluate_slices(df,\n",
    "                                       bidders=['last_click',\n",
    "                                                'AA'],\n",
    "                                       utilities=['last_click',\n",
    "                                                  'AA_normed'],\n",
    "                                       test_days=range(22,23),\n",
    "                                       learning_duration=5,\n",
    "                                       hash_space = 2**13,\n",
    "                                       AA_bidder_label='all_clicks')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "scores"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}