{ "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 }