<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Davide Altomare on Medium]]></title>
        <description><![CDATA[Stories by Davide Altomare on Medium]]></description>
        <link>https://medium.com/@davide.altomare?source=rss-bec4a2b7e113------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8ByNQnVP4yKjsBjeiXrhSw.png</url>
            <title>Stories by Davide Altomare on Medium</title>
            <link>https://medium.com/@davide.altomare?source=rss-bec4a2b7e113------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 23:17:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davide.altomare/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Is Your Data-Driven Attribution Model Better Than a Simply Last Touch Model?]]></title>
            <link>https://medium.com/@davide.altomare/is-your-data-driven-attribution-model-better-than-a-simply-last-touch-model-a1e702643ebf?source=rss-bec4a2b7e113------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e702643ebf</guid>
            <category><![CDATA[multi-touch-attribution]]></category>
            <category><![CDATA[digital-marketing]]></category>
            <category><![CDATA[marketing-attribution]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-driven-marketing]]></category>
            <dc:creator><![CDATA[Davide Altomare]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 15:23:02 GMT</pubDate>
            <atom:updated>2025-10-02T15:23:02.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yK9ZcQi3xWtbsmpSd8AumQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/it/@eliomendes">Elio Santo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>You spent lots of effort to build a <strong>Data-Driven Attribution Model</strong> to evaluate the return of investments of your marketing channels. The model is ready to be put on production but …</blockquote><blockquote>Do you really be confident that your attribution model is better than a simply heuristic methodology?</blockquote><h3>Introduction</h3><p><strong>Marketing attribution</strong> is the way of splitting credit (conversions and/or conversion value) between marketing channels. It is crucial for evaluating the return on investment (<strong>ROI</strong>) of your channels and thus to decide how to split your budget among them.</p><p>Marketing attribution models can be categorized into two main types: <strong>heuristic methodologies</strong> and <strong>probabilistic models</strong>.</p><p>The evaluation of the performance of attribution models is largely based on their <strong>predictive performance</strong>, leaving non-probabilistic methodologies without a measure of performance. It means that you can’t compare a probabilistic model with a non-probabilistic one. However, non-probabilistic models also incorporate non-trivial methodologies, such as the Shapley value. Thus, you can’t evaluate the performance of a <strong>Shapley model</strong>.</p><p>This article presents a new approach to compare attribution models by evaluating their performance in a <strong>traffic allocation problem</strong>. This approach allows the evaluation of both heuristic and probabilistic attribution methodologies, enabling you to choose the right model for <strong>your data</strong>.</p><p>I will guide you through all the <strong>Python code</strong> you need to apply the methodology proposed with any attribution model and your data.</p><h3>Attribution Models</h3><p>There are two primary classes of attribution methodologies, as we described before — <strong>heuristic methods</strong> and <strong>probabilistic models</strong>.</p><p>A <strong>heuristic attribution model</strong> is a rule-based approach. Some frequent types are first-touch, last-touch, and linear models. The heuristic models assign credit according to a specified rule, assigning all the credit to the channel that comes first in the customer journey (first-touch model) or dividing the credit evenly across all touchpoints (linear model). Although simple to implement and easy to interpret, these models can over-simplify the complexity of customer behavior and fall short in measuring multi-touch interactions.</p><p>With <strong>probabilistic attribution models</strong>, statistics are used to estimate the probability that a touchpoint influenced the conversion. These are data-driven models (usually based on machine learning) that analyze the patterns observed in customer journeys and assign credits considering the actual probability of contribution for each touchpoint. They likely capture more complex interactions between channels and should provide better attributions. They may, however, need high volumes of data and computing resources, and can complicate the interpretability of results.</p><h3><strong>Separation of Prediction Quality and Attribution Quality</strong></h3><p>Probabilistic attribution uses a statistical model, but accurate prediction doesn’t guarantee well-grounded attribution. Predictive performance tells you how well the model forecasts outcomes; it doesn’t test whether the credit assigned to channels reflects their causal impact. For example, a model might predict conversions very well yet under-credit certain touchpoints and over-credit others because of spurious correlations.</p><h3>Compare Attribution Models in a Traffic Allocation Problem</h3><p>The methodology we’ll propose is the following:</p><ol><li><strong>Simulate Paths</strong>: generate a synthetic dataset of customer journeys based on historical paths and traffic for different channels.</li><li><strong>Perform Attribution</strong>: apply the chosen attribution models for distributing traffic across channels.</li><li><strong>Distribute Traffic</strong>: based on the attributions, redistribute traffic to your channels and simulate new paths.</li><li><strong>Evaluate Conversion Rate</strong>: check the conversion rates generated through different models and rank their performances.</li></ol><h3>Code Implementation</h3><p>In the following, we’ll show a <strong>Python implementation</strong> of the model comparison methodology introduced in the previous paragraph.</p><p>We will compare three attribution models: <strong>first-touch</strong>, <strong>last-touch</strong>, and <strong>linear-touch</strong>. The methodology can be extended to evaluate other models, whether heuristic or probabilistic.</p><p>First, we load the necessary libraries and a Python DataFrame containing a list of customer journeys (path) and a variable (is.converting) that indicates whether a customer journey resulted in a conversion (1) or not (0).</p><pre>import pandas as pd<br>from collections import Counter<br>import numpy as np<br><br>df=pd.read_csv(&quot;https://app.channelattribution.io/Data/data_cj.csv&quot;,sep=&quot;;&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n47buV3oZeqmBZxPwlKtJg.png" /></figure><p>Now we need to build some functions to be used in the main part of the algorithm.</p><p><strong>string_to_df</strong> converts a string of channels, separated by “ &gt; “, into a DataFrame. It calculates the occurrence of each channel in the string using the Counter class and returns a DataFrame with two columns: channel and traffic0, where traffic0 indicates the count of each channel.</p><pre>def string_to_df(s):<br>    &quot;&quot;&quot;<br>    Converts a path string into a DataFrame that shows the frequency of each channel in the path.<br><br>    Parameters:<br>        s (str): A string representing a sequence of channels separated by &#39; &gt; &#39;. <br>                 For example: &#39;A &gt; B &gt; C &gt; A &gt; D&#39;.<br>    Returns:<br>        pd.DataFrame: A DataFrame with two columns:<br>                      - &#39;channel&#39;: The name of each channel in the path.<br>                      - &#39;traffic0&#39;: The count of how many times each channel appears in the path.<br>    &quot;&quot;&quot;<br>    items = s.split(&#39; &gt; &#39;)<br>    counts = Counter(items)<br>    df = pd.DataFrame(counts.items(), columns=[&#39;channel&#39;, &#39;traffic0&#39;]).reset_index(drop=True)<br><br>    return df</pre><p><strong>first_touch_attribution</strong> identifies the first channel in each path where a conversion occurred and assigns full attribution to that channel. The output is a DataFrame showing the attribution scores for each channel, sorted in descending order.</p><pre>def first_touch_attribution(df, path_col=&#39;path&#39;, convert_col=&#39;is.converting&#39;):<br>    &quot;&quot;&quot;<br>    This function applies the First-Touch Attribution model to the provided data.<br>    It attributes all conversions to the first channel in the user path that led to a conversion.<br><br>    Parameters:<br>        df (pd.DataFrame): A DataFrame containing the data, with at least two columns: <br>                           - path_col: A column containing the paths of user interactions (default &#39;path&#39;).<br>                           - convert_col: A column indicating whether the user converted (default &#39;is.converting&#39;).<br>        path_col (str): The name of the column containing the user paths (default &#39;path&#39;).<br>        convert_col (str): The name of the column indicating whether the conversion occurred (default &#39;is.converting&#39;).<br>    Returns:<br>        pd.DataFrame: A DataFrame with two columns:<br>            - &#39;channel&#39;: The name of the channel (touchpoint).<br>            - &#39;attribution&#39;: The number of conversions attributed to that channel.<br>            The DataFrame is sorted by &#39;attribution&#39; in descending order, with the most attributed channels at the top.<br>    &quot;&quot;&quot;<br>    attribution = {}<br>    converting_paths = df[df[convert_col] == 1]<br>    for path in converting_paths[path_col]:<br>        first_touch = path.split(&#39; &gt; &#39;)[0]<br>        attribution[first_touch] = attribution.get(first_touch, 0) + 1<br>    attribution_df = pd.DataFrame(list(attribution.items()), columns=[&#39;channel&#39;, &#39;attribution&#39;])<br>    attribution_df = attribution_df.sort_values(by=&#39;attribution&#39;, ascending=False).reset_index(drop=True)<br><br>    return attribution_df</pre><p><strong>last_touch_attribution</strong> attributes the entire credit for a conversion to the last channel in each converting path. The result is a DataFrame with channels and their attribution scores, sorted in descending order.</p><pre>def last_touch_attribution(df, path_col=&#39;path&#39;, convert_col=&#39;is.converting&#39;):<br>    &quot;&quot;&quot;<br>    Computes the last-touch attribution for marketing channels.   <br>    <br>    The function attributes the full credit for a conversion to the last touchpoint<br>    (i.e., the last channel in the path that leads to a conversion).<br>    Parameters:<br>        df (pd.DataFrame): Input DataFrame containing paths and conversion flags.<br>        path_col (str): Name of the column containing the path strings.<br>                        Each path is expected to be a string of touchpoints separated by &#39; &gt; &#39;.<br>                        Default is &#39;path&#39;.<br>        convert_col (str): Name of the column indicating whether a path converted (1) or not (0).<br>                           Default is &#39;is.converting&#39;.<br>    Returns:<br>        pd.DataFrame: A DataFrame with two columns:<br>            - &#39;channel&#39;: The marketing channel (last touchpoint).<br>            - &#39;attribution&#39;: The number of conversions attributed to each channel.<br>            The DataFrame is sorted in descending order of attribution.<br>    &quot;&quot;&quot;<br>    attribution = {}<br>    converting_paths = df[df[convert_col] == 1]<br>    for path in converting_paths[path_col]:<br>        last_touchpoint = path.split(&#39; &gt; &#39;)[-1]<br>        attribution[last_touchpoint] = attribution.get(last_touchpoint, 0) + 1<br>    attribution_df = pd.DataFrame(list(attribution.items()), columns=[&#39;channel&#39;, &#39;attribution&#39;])<br>    attribution_df = attribution_df.sort_values(by=&#39;attribution&#39;, ascending=False).reset_index(drop=True)<br>    <br>    return attribution_df<br></pre><p><strong>linear_touch_attribution</strong> distributes the conversion credit equally across all channels in a converting path. It calculates the total attribution for each channel and returns a DataFrame of channels and their scores, sorted in descending order.</p><pre>def linear_touch_attribution(df, path_col=&#39;path&#39;, convert_col=&#39;is.converting&#39;):<br>    &quot;&quot;&quot;<br>    Calculates linear attribution for marketing channels based on user paths.<br>   <br>    In a linear attribution model, the credit for a conversion is distributed equally <br>    across all touchpoints in the user&#39;s path.<br>    Parameters:<br>        df (pd.DataFrame): Input DataFrame containing user paths and conversion status.<br>        path_col (str): Column name in the DataFrame that contains the user paths.<br>                        Each path is a string with touchpoints separated by &#39; &gt; &#39;.<br>        convert_col (str): Column name in the DataFrame indicating whether a path resulted in a conversion (1) or not (0).<br>    Returns:<br>        pd.DataFrame: A DataFrame with two columns:<br>            - &#39;channel&#39;: The marketing channel.<br>            - &#39;attribution&#39;: The total attribution value assigned to the channel, based on all converting paths.<br>                          Channels are sorted in descending order of attribution.<br>    &quot;&quot;&quot;<br>    converting_paths = df[df[convert_col] == 1]<br>    attribution = {}<br>    for path in converting_paths[path_col]:<br>        touchpoints = path.split(&#39; &gt; &#39;)<br>        attribution_value = 1 / len(touchpoints)<br>        for touchpoint in touchpoints:<br>            attribution[touchpoint] = attribution.get(touchpoint, 0) + attribution_value<br>    attribution_df = pd.DataFrame(list(attribution.items()), columns=[&#39;channel&#39;, &#39;attribution&#39;])<br>    attribution_df = attribution_df.sort_values(by=&#39;attribution&#39;, ascending=False).reset_index(drop=True)<br>    <br>    return attribution_df</pre><p><strong>compute_channel_touches</strong> computes the sum of touches for each channel over all paths in the provided column of the DataFrame. It will output a DataFrame that contains channel and touches, sorted by touches in descending order.</p><pre>def compute_channel_touches(df, path_column):<br>    &quot;&quot;&quot;<br>    Computes the number of touches for each channel in the specified path column of a DataFrame.<br>    <br>    Parameters:<br>        df (pd.DataFrame): Input DataFrame containing the path data.<br>                          Each row represents a user journey, with channels listed in the specified path_column.<br>        path_column (str): The column name in the DataFrame that contains the journey paths.<br>                          Paths are assumed to be strings with channels separated by &quot; &gt; &quot;.<br>    Returns:<br>        pd.DataFrame: A DataFrame with two columns:<br>                      - &#39;channel&#39;: The name of the marketing channel.<br>                      - &#39;touches&#39;: The total number of touches for each channel, sorted in descending order.<br>    &quot;&quot;&quot;<br>    channel_touches = {}<br><br>    for path in df[path_column]:<br>        channels = path.split(&quot; &gt; &quot;)<br>        for channel in channels:<br>            channel_touches[channel] = channel_touches.get(channel, 0) + 1<br>    touches_df = pd.DataFrame(list(channel_touches.items()), columns=[&quot;channel&quot;, &quot;touches&quot;])<br>    touches_df = touches_df.sort_values(by=&quot;touches&quot;, ascending=False).reset_index(drop=True)<br><br>    return touches_df</pre><p><strong>new_traffic_allocation </strong>reallocates traffic among channels based on their current touches and attribution scores. It ensures a minimum traffic allocation to each channel and adjusts traffic based on reallocation percentages. The output is a DataFrame with updated traffic allocations for each channel.</p><pre>def new_traffic_allocation(df_gen, attr, perc_reall=0.1, min_perc_traffic=0.01):<br>    &quot;&quot;&quot;<br>    Computes a new traffic allocation for channels based on their current traffic <br>    and attribution values.<br><br>    Parameters:<br>        df_gen (pd.DataFrame): A DataFrame containing the generated paths with traffic data.<br>        attr (pd.DataFrame): A DataFrame containing attribution scores for each channel.<br>                             Must include a &#39;channel&#39; column and an &#39;attribution&#39; column.<br>        perc_reall (float): The percentage of traffic to be reallocated based on attribution <br>                            scores. Default is 0.1 (10%).<br>        min_perc_traffic (float): The minimum percentage of traffic to be allocated to each <br>                                  channel, regardless of attribution. Default is 0.01 (1%).<br>    Returns:<br>        pd.DataFrame: A DataFrame with columns &#39;channel&#39; and &#39;new_traffic_allocation&#39;, <br>                      where &#39;new_traffic_allocation&#39; contains the recalculated traffic values <br>                      for each channel.<br>    Description:<br>        1. Computes the current traffic distribution for each channel using the `compute_channel_touches` function.<br>        2. Merges the attribution DataFrame (`attr`) with the computed traffic distribution.<br>        3. Calculates the new traffic allocation as a weighted combination of:<br>           - Current traffic distribution,<br>           - A uniform minimum traffic allocation,<br>           - Attribution-based reallocation of the specified percentage (`perc_reall`).<br>        4. Cleans up intermediate columns and returns the updated traffic allocation.<br>    &quot;&quot;&quot;<br>    traffic = compute_channel_touches(df_gen, &quot;path&quot;)<br>    tab = pd.merge(attr, traffic, on=&#39;channel&#39;, how=&#39;left&#39;)<br>    tab = tab.fillna(0)  # Replace any missing values with 0<br>    tab[&#39;new_traffic_allocation&#39;] = (<br>        (1 - min_perc_traffic - perc_reall) * tab[&#39;touches&#39;] + <br>        (min_perc_traffic / len(tab[&#39;attribution&#39;]) * tab[&#39;touches&#39;].sum()) + <br>        (tab[&#39;attribution&#39;] / tab[&#39;attribution&#39;].sum() * perc_reall * tab[&#39;touches&#39;].sum())<br>    )<br>    del tab[&#39;attribution&#39;]<br>    del tab[&#39;touches&#39;]<br><br>    return tab</pre><p><strong>randomly_distribute_traffic</strong> simulates what the conversion rate looks like after redistributing traffic based on the considered attribution models. It calculates the channel scores through the attribution model provided by you, redistributes traffic, creates new paths, and calculates conversion rates. Return a float representing the simulated conversion rate.</p><pre>def randomly_distribute_traffic(df, channel_column, total_traffic):<br>    &quot;&quot;&quot;<br>    Randomly distributes a given total traffic across all channels, ensuring:<br>    - Each channel receives some traffic (no channel gets zero).<br>    - The total allocated traffic equals the specified total_traffic.<br><br>    Parameters:<br>        df (pd.DataFrame): <br>            Input DataFrame containing the channel data.<br>            Each row represents a channel.<br>        channel_column (str): <br>            The column name containing the channel names.<br>            This column is used to identify the unique channels in the DataFrame.<br>        total_traffic (float): <br>            The total amount of traffic to be allocated across all channels.<br>    Returns:<br>        pd.DataFrame: <br>            A modified DataFrame containing the original data and an additional<br>            column, &#39;traffic&#39;, which specifies the allocated traffic for each channel.<br>    &quot;&quot;&quot;<br>    random_values = np.random.rand(len(df))  # Create a random value for each channel in the DataFrame.<br>    normalized_values = random_values / random_values.sum()<br>    df[&#39;traffic&#39;] = normalized_values * total_traffic<br><br>    return df</pre><p><strong>generate_paths</strong> generates new paths based on the traffic allocation DataFrame. It selects paths from the input DataFrame, updates the traffic allocation, and excludes channels with zero traffic. The result is a new DataFrame of generated paths.</p><pre>def generate_paths(df, df_traffic, ngen_path):<br>    &quot;&quot;&quot;<br>    Generates a new set of paths based on the initial traffic allocation and sampling.<br><br>    Parameters:<br>        df (pd.DataFrame): The input DataFrame containing original paths and their attributes. <br>                           Expected to have a &#39;path&#39; column representing channel paths.<br>        df_traffic (pd.DataFrame): A DataFrame containing traffic allocations per channel. <br>                                   Expected to have columns [&#39;channel&#39;, &#39;traffic&#39;].<br>        ngen_path (int): The number of paths to generate.<br>    Returns:<br>        pd.DataFrame: A DataFrame containing the generated paths. Each row corresponds to <br>                      a sampled path with adjusted traffic allocation.<br>    Steps:<br>        1. Initializes an empty list `df_gen` to store generated paths.<br>        2. Copies the traffic allocation DataFrame to avoid modifying the original.<br>        3. Iteratively samples paths and adjusts traffic allocation:<br>            - Sample one path randomly from `df`.<br>            - Convert the sampled path into a channel-based traffic DataFrame using `string_to_df`.<br>            - Merge the sampled traffic with the current traffic allocation and adjust traffic counts.<br>            - Identify and remove channels with no remaining traffic.<br>        4. If no valid paths remain in `df`, the process stops early.<br>        5. Concatenates all generated paths into a final DataFrame.<br>    &quot;&quot;&quot;<br>    df_gen = []  <br>    df_traffic1 = df_traffic.copy()  <br>    for k in range(ngen_path):<br>        row = df.sample(n=1)<br>        path = row[&#39;path&#39;].values[0]<br>        df_traffic0 = string_to_df(path)<br>        df_traffic1 = pd.merge(df_traffic1, df_traffic0, on=&#39;channel&#39;, how=&#39;left&#39;)<br>        df_traffic1 = df_traffic1.fillna(0)<br>        df_traffic1[&#39;traffic&#39;] = df_traffic1[&#39;traffic&#39;] - df_traffic1[&#39;traffic0&#39;]<br>        del df_traffic1[&#39;traffic0&#39;]<br>        vchannel_to_rm = df_traffic1[df_traffic1[&#39;traffic&#39;] &lt;= 0][&#39;channel&#39;]<br>        if len(vchannel_to_rm) &gt; 0:<br>            for channel_to_rm in vchannel_to_rm:<br>                df = df[~df[&quot;path&quot;].str.contains(channel_to_rm + &#39; &#39;)]<br>                df = df[~df[&quot;path&quot;].str.contains(&#39; &#39; + channel_to_rm)]<br>                df_traffic1 = df_traffic1[df_traffic1[&#39;channel&#39;] != channel_to_rm]<br>        else:<br>            df_gen = df_gen + [row]<br>        if len(df) == 0:<br>            break<br>    df_gen = pd.concat(df_gen).reset_index(drop=True)<br><br>    return df_gen<br></pre><p><strong>simulate_conversion_rate</strong> simulates the conversion rate after reallocating traffic based on an attribution model. It uses the provided attribution model to calculate channel scores, reallocates traffic, generates new paths, and computes the conversion rate. The result is the simulated conversion rate as a float.</p><pre>def simulate_conversion_rate(<br>    df_gen, df_channels, df, df_traffic_start, <br>    attribution_model, perc_realloc=0.1, min_perc_traffic=0.01<br>):<br>    &quot;&quot;&quot;<br>    Simulates conversion rates based on traffic allocation and a generic attribution model.<br><br>    Parameters:<br>        df_gen (pd.DataFrame): The initial DataFrame containing generated paths, where each row represents a <br>            simulated customer journey. It includes information about whether the journey results in a conversion.<br>        df_channels (pd.DataFrame): A DataFrame containing channel information, such as channel names <br>            and any relevant metadata needed for traffic allocation.<br>        df (pd.DataFrame): The source DataFrame used for generating paths. This includes real or historical <br>            data on user journeys.<br>        df_traffic_start (pd.DataFrame): The initial traffic allocation DataFrame. This provides the starting <br>            distribution of traffic across channels.<br>        attribution_model (callable): A function that calculates channel attribution. It should take a DataFrame <br>            as input (e.g., `df_gen`) and return a DataFrame containing attribution scores for each channel.<br>        perc_realloc (float): The percentage of traffic to reallocate based on attribution results. Default is 0.1 (10%).<br>        min_perc_traffic (float): The minimum percentage of traffic allocated to each channel, ensuring no channel <br>            receives zero traffic. Default is 0.01 (1%).<br>    Returns:<br>        float: The conversion rate (`cr`), calculated as the ratio of converting journeys to the total number of journeys.<br>    &quot;&quot;&quot;<br>    attr = attribution_model(df_gen)<br>    attr = pd.merge(df_channels, attr, on=&#39;channel&#39;, how=&#39;left&#39;)<br>    attr = attr.fillna(0)<br>    df_traffic = new_traffic_allocation(<br>        df_gen, attr, perc_reall=perc_realloc, min_perc_traffic=min_perc_traffic<br>    )<br>    df_gen = generate_paths(df, df_traffic_start, ngen_path=len(df_gen))<br>    cr = float(df_gen[&#39;is.converting&#39;].sum() / len(df_gen))<br><br>    return cr</pre><p>Now we are ready for the main part of the algorithm. The code performs a simulation to compare the conversion rates (vcr) for three different attribution models: first-touch, last-touch, and linear-touch. It simulates a specified number of iterations (num_simulation = 10), each with a set number of simulated paths (ngen_path = 1000) and a total traffic allocation (total_traffic = 1000).</p><p>For each simulation iteration, the following steps occur:</p><p><strong>Traffic Distribution</strong>: Traffic is randomly distributed across channels using the randomly_distribute_traffic function. The initial traffic allocation is stored in df_traffic_start.</p><p><strong>Path Generation</strong>: Paths are generated using the generate_paths function, which creates simulated user journeys based on the traffic allocation. The generated paths are stored in df_gen_start.</p><p><strong>Conversion Rate Calculation</strong>: For each generated dataset (df_gen), the conversion rate is calculated separately for the three attribution models (first_touch_attribution, last_touch_attribution, and linear_touch_attribution). The simulate_conversion_rate function is used for each model, and the resulting conversion rates are stored in the lists vcr_first_touch, vcr_last_touch, and vcr_linear_touch.</p><p>After running all the simulations, the code compares the conversion rates for the three attribution models across all iterations. This allows an evaluation of how each model performs under varying traffic conditions</p><pre>ngen_path=1000<br>total_traffic=1000<br>num_simulation=10<br><br>vcr_first_touch=[]<br>vcr_last_touch=[]<br>vcr_linear_touch=[]<br>for i in range(num_simulation):<br>    print(&quot;Number simulation: &quot; + str(i+1))<br>    df_traffic_start=df_channels.copy()<br>    df_traffic_start=randomly_distribute_traffic(df_traffic_start, channel_column=&quot;channel&quot;, total_traffic=total_traffic)<br>    df_gen_start=generate_paths(df,df_traffic_start,ngen_path)<br>    df_gen=df_gen_start.copy()<br>    vcr_first_touch=vcr_first_touch + [simulate_conversion_rate(df_gen, df_channels, df, df_traffic_start, first_touch_attribution)]<br>    vcr_last_touch=vcr_last_touch + [simulate_conversion_rate(df_gen, df_channels, df, df_traffic_start, last_touch_attribution)]<br>    vcr_linear_touch=vcr_linear_touch + [simulate_conversion_rate(df_gen, df_channels, df, df_traffic_start, linear_touch_attribution)]</pre><p>We can plot the distribution of the simulated conversion rates for each attribution model.</p><pre>import matplotlib.pyplot as plt<br><br>tab_res=pd.DataFrame({&#39;first_touch&#39;:vcr_first_touch,&#39;last_touch&#39;:vcr_last_touch,&#39;linear_touch&#39;:vcr_linear_touch})<br># Create a box plot<br>plt.figure(figsize=(8, 6))<br>tab_res.boxplot(column=[&quot;first_touch&quot;, &quot;last_touch&quot;, &quot;linear_touch&quot;], grid=False)<br>plt.title(&quot;Attribution Model Comparison&quot;)<br>plt.ylabel(&quot;Values&quot;)<br>plt.xlabel(&quot;Attribution Models&quot;)<br>plt.xticks(rotation=45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuhwn0ER76wpxIS619n4Yg.png" /></figure><p><a href="https://channelattribution.io/"><strong>ChannelAttributionPro</strong></a> is a Python and R package for marketing attribution and budget allocation. You can line up heuristic models against probabilistic ones and see the different performance. The compare_models() call does the side-by-side in one line, and the heavy lifting runs in optimized C++, so it stays quick even on big datasets. It’s free for students and researchers. Companies can test it end-to-end at no cost and only pay when they move it into production.</p><pre>#Load library and data<br>import pandas as pd<br>from ChannelAttributionPro import *<br>import matplotlib.pyplot as plt<br><br>df_paths = pd.read_csv(&quot;https://app.channelattribution.io/data/Data.csv&quot;,sep=&quot;;&quot;)<br><br>#Get a free password here https://channelattribution.io/form<br>password=&quot;yourpassword&quot;<br><br>#Compare MTA models<br>res=compare_models(df_paths,var_path=&quot;path&quot;,var_conv=&quot;total_conversions&quot;,<br>    var_null=&quot;total_null&quot;,cha_sep=&quot;&gt;&quot;,perc_reall=0.1,perc_sample=0.10,<br>    max_nsim=10000,min_perc_traffic=0.005,niter=30,flg_extra_path=1,<br>    max_markov_order=4,seed=1234567,verbose=1,<br>    server=&quot;app.channelattribution.io&quot;,password=password)<br><br>#Plot results<br>res[&quot;performance&quot;].columns=res[&quot;performance&quot;].columns.str.replace(&#39;markov_model_order&#39;,&#39;markov_m_order&#39;)<br>fig=res[&quot;performance&quot;].boxplot()<br>plt.rcParams[&quot;figure.figsize&quot;] = (10,12)<br>plt.title(&#39;Simulated Conversion Rate&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXNa-l3Xqc2r6wP2DN8yRQ.png" /></figure><h3>Conclusion</h3><p>Selecting the right attribution model is critical for making informed marketing decisions. While probabilistic models rely on predictive performance, heuristic models require alternative evaluation methods. The methodology presented here offers a flexible and practical approach to compare attribution models by simulating traffic allocation and measuring their impact on conversions. With Python, this framework can be adapted to evaluate a wide range of attribution models, enabling data-driven marketing strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e702643ebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-touch attribution and budget allocation]]></title>
            <link>https://medium.com/@davide.altomare/multi-touch-attribution-and-budget-allocation-ce04b492604d?source=rss-bec4a2b7e113------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce04b492604d</guid>
            <category><![CDATA[multi-touch-attribution]]></category>
            <category><![CDATA[budget-allocation]]></category>
            <category><![CDATA[markov-models]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[digital-marketing]]></category>
            <dc:creator><![CDATA[Davide Altomare]]></dc:creator>
            <pubDate>Fri, 25 Mar 2022 13:39:46 GMT</pubDate>
            <atom:updated>2023-04-11T19:26:19.526Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparison between different multi-touch attribution models in a budget allocation problem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*9m0NAZjckW4fqe-Z2v5xsQ.png" /></figure><p><em>Budget allocation in digital marketing is nowadays widely based on multi-touch attribution and return on investment (ROI). Multi-touch attribution often relies on heuristic methodologies (e.g. last-touch, first-touch, linear, and weighted attribution) despite advanced methods being available (e.g. logistic regression, Shapley value, and Markov model). Heuristics are easy to understand and implement while advanced methodologies instead are not so immediate and often require more computations. In this paper, we will go in-depth on multi-touch attribution and budget allocation when high-frequency and/or dependent touch-points are present and we will present a simulation use case in which different attribution methodologies will be compared in terms of generated profit. We will show that if attribution is performed using odds calculated from Markov model then a greater profit can be reached with respect to other models.</em></p><h4>1. Introduction</h4><p>Multi-touch attribution evaluates the contribution each digital touch-point has in making conversions using customer journeys recorded through web cookies.</p><p>Multi-touch attribution has been introduced after cookies started to be used in digital marketing to track users. Cookies were created in 1994 to allow people to store their items in shopping carts. Within a year, the existing advertising companies have started to track users and follow them around with ad campaigns.</p><p>At the beginning of the tracking era, it was natural to start using simple heuristic methodologies to quantify the importance each touch-point has in making conversions. At the beginning of the 2010s other methodologies, such as logistic regression<strong>²</strong> and Shapley value⁴ and Markov model¹, were introduced in the attribution arena. In 2015 the open-source library <a href="https://channelattribution.io/">ChannelAttribution</a> was published letting feasible and fast the application of Markov models to real use cases. But despite this, many companies continue to use attribution using heuristic methodologies, last-touch overall.</p><h4>2. Multi-touch attribution</h4><p>Suppose we have two touch-points: email (<em>E</em>) and banner (<em>B</em>). (<em>E</em>) is a high-frequency touch-point thus it is highly probable that it is present in a customer journey without any contribution to making conversions. Suppose we observe the following customer journeys (paths):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*WmNbW8-C6Q7zNUfYz7y3Cg.png" /></figure><p>If we perform attribution using last-touch we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*bfgeHg2CUjt41JMbCJa8jA.png" /></figure><p>And all the conversions are attributed to (<em>E</em>) despite it being clear that the contribution of (<em>E</em>) in path</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*h5F5CEGNThoS8wujgNXp-Q.png" /></figure><p>is almost null. Instead what we would have expected in this example is the following attribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*xOVhcXa5tVaGgLWisRIwvw.png" /></figure><p>and last-touch is clearly far from this result.</p><p>Now we try to perform attribution using a first-order Markov model. First, we need to build a Markov graph from the customer journeys we have observed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*Y5vtzrIGi1ROFKPPgbGLGg.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*XY8YTxz2rtAul6P3tFOAlg.png" /></figure><p>The overall conversion probability can be calculated considering the probability of all the paths that reach the conversion state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*4XWc4x7JQBnvdqDG_7X3CQ.png" /></figure><p>Attribution through Markov model is usually performed using removal effects. Removal effects for channel α are the difference between the conversion probability of the full graph minus the conversion probability between the graph obtained removing channel α. In our example, the probabilities of the graphs obtained removing each touch-point once at a time are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*fmfr9vh0J48ReOIGFR1lrg.png" /></figure><p>Thus removal effects for <em>E</em> and <em>B</em> are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*EKgxRXiB8tsao1UHh2NpWA.png" /></figure><p>Then removal effects are normalized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*iD3Y1lFSQHxyWOJeB_HF4Q.png" /></figure><p>and used to perform path-level attribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*htW5iG_3BmU3UPwEdBO9Wg.png" /></figure><p>Markov model with removal effects attributes 0.085 conversions to <em>B</em> instead of 0 as last-touch did. And also in this case the value is highly underestimated since we know that <em>E</em> is almost non-influential in the conversion process.</p><p>Hence we would provide an alternative measure that could assign a reasonable value of conversions to <em>B</em>. Let P[<em>C</em>](<em>G</em>|α) be the conversion probability if touch-point α has been observed and P[<em>N</em>](<em>G</em>|α) be the null probability if touch-point α has been observed. We can define:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*ih3ruK0xm-Ec6aeBobvzgA.png" /></figure><p>O(α) is the odds for touch-point α.</p><p>Now we calculate odds for touch-point <em>E</em> and <em>B</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*RhT9Zfoh7whoNVas804YuA.png" /></figure><p>Odds can be normalized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*ubMIgg0-YFZ5dvsRn2NWLg.png" /></figure><p>We can apply these weights to each path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*SIoIqBVirFNzXjy3yPhVnw.png" /></figure><p>And we see that first-order Markov model with odds increases the conversion attributed to B to 0.910 which is very near to 1, the expected value for B. Thus we can conclude that <em>odds is the natural quantity to perform path-level attribution with Markov model</em>.</p><p>In this paragraph, we have seen that last-touch approach can easily bring to an incorrect attribution when high-frequency touch-points are present. Instead, Markov model with odds is able to find a more accurate path-level attribution.</p><h4>3. Budget allocation</h4><p>In the last paragraph, we have seen that a non-probabilistic approach such as last-touch can lead to a non-realistic attribution in case there are high-frequency touch-points in customer journeys. That is because last-touch attribution is strongly influenced by the frequency of touch-points in customer journeys. Markov model with removal effects as weights for attribution partially suffers the same issue if it is used for path-level attribution. But we have seen that it is sufficient to replace removal effects with odds to solve the problem. We say <em>realistic</em> because we do not know the real generation process of our data. We have only observed some paths and we have inferred that <em>E</em> is not relevant in making conversions. That has been possible considering the conversion capacity of each touch-point. Thus considering only the converting paths is not enough, as heuristic methodologies do. Non-converting paths are equally important in the attribution process and must be considered.<br>After attribution is made, the natural question is how it can be used to allocate budget among touch-points. The obvious answer is through <strong>ROI</strong> (return on investment). ROI for touch-point α is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*Sv6UwdjKSMvvg7wPuC9ftg.png" /></figure><p>Now consider the following example. We have two touch-points: email (<em>E</em>) and banner (<em>B</em>). Moreover, the following assumptions are valid:</p><ol><li>conversion rates are constant over time hence there are no external factors with any influence;</li><li>total budget is fixed over time;</li><li>all the customer journeys contain only one touch-point;</li><li>conversion rates are respectively 0.01 for <em>E</em> and 0.1 for <em>B</em>;</li><li>each 1 euro invested in <em>E</em> will always lead to 5 touches to <em>E</em> while each 1 euro invested in <em>B</em> will always lead to 1 touch to <em>B</em>;</li><li>At time t=0 we have invested 800 euros in <em>E</em> and 200 euros in <em>B</em>.</li><li>Each conversion is valued 20 euros.</li></ol><p>These assumptions imply that the system evolves in a deterministic way over time. Thus at t=0 we got the following paths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*3WfAry0c8cZW1Mc7E-mzTQ.png" /></figure><p>We have observed 4,200 distinct paths and 60 conversions with a total profit of (60 x 20) -1,000 = 200 euros.</p><p>In this simple example, the attribution process is trivial since we only have mono paths. We see that 40 conversions are due to <em>E</em> while 20 to <em>B</em>.</p><p>At t=1 we use last-touch approach to perform attribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*NjmLRN9OzibU4Or7jvUGEA.png" /></figure><p>In fact, we see that last-touch correctly assigned 40 conversions to <em>E</em> and 20 conversions to <em>B</em>. Moreover, we note that in this simple use case, all the heuristic methodologies (last-touch, first-touch, linear touch, and exponential time decay) lead to the same results.</p><p>But what happens if we use results from last-touch to allocate budget? A strategy we could follow is calculating the ROI for each touch-point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*Y3ATfmelt_F3BktXe7sLnw.png" /></figure><p>and then use those ROIs to split budget among touch-points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*___k0rEEWideHYUtNInxJg.png" /></figure><p>Since initial assumptions are valid, at time t=2 we observed the following paths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*aqKo6_7ivlg88i2mrMxeSA.png" /></figure><p>We had 2,333 paths and 85 conversions. Thus our new budget allocation has increased conversion from 60 to 85 with a total profit of (85 x 20)-1,000 = 700 euros.</p><p>It is not difficult to show that path-level attribution with Markov model and removal effects (or odds) leads to the same result as well because the two touch-points are independent.</p><p>But is this the optimal allocation? The answer is no. It is not difficult to find that the optimal allocation takes place when all the budget is assigned to <em>B</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*pXRT2vD9Glww27MNBmzy3g.png" /></figure><p>Since initial assumptions are valid, at time t=2, adopting this allocation at time t=2 we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*0NltjDQ-Gl9jlZhZAt4UaA.png" /></figure><p>obtaining 6,000 paths and 100 conversion with a profit of (100 x 20) -1,000 = 1,000 euros .</p><p>It is interesting to notice that despite all the attribution models (heuristics methodologies and Markov model) leading to a correct attribution, the budget allocation they suggest through the ROI is not optimal in terms of profit. ROI leads to a sub-optimal allocation, reaching a profit that is 15% lower than the maximum value reachable. But also conversion rates lead to a sub-optimal allocation despite the profit reached being 8 % higher with respect to that reached by last-touch or by Markov model.</p><p>For this reason, some authors<strong>⁴</strong> argue that attribution should not be used to allocate budget. For sure attribution and budget allocation are conceptually different. And we have seen that if attribution is used for budget optimization it leads to a sub-optimal result in terms of profit. In the example presented there is a linear relationship between the budget allocated on touch-points and traffic generated on that touch-point. Moreover, touch-points are also independent. Thus giving all the budget to that touch-point with the higher conversion rate ensures the optimal allocation. But the reality is always more complex. <br>If we decide to abandon attribution and ROI, a global budget optimization strategy is anyhow hard to define. Because we would need to model a complex system that involves many variables and needs many assumptions. Thus finding the optimal allocation in real use-cases is utopian. Considering that, ROI and attribution remain important tools in budget allocation strategy. But if ROI is useful to perform budget allocation then making a correct attribution is crucial to get a greater profit. And a better attribution can be made using a probabilistic approach like Markov model, as we have seen before.</p><h4>4. Comparison between different path-level attribution models</h4><p>Suppose we have K touch-points and we need to allocate budget among them for T time instants. Let B(k,t) the budget allocated to touch-point k at time t, V(k,t) the conversion value attributed to touch-point k at time t, and X(k,t) be the cost associated with touch-point k at time t and B*(t) the total available budget at time t. At each t, B*(t) is split using the following strategy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*5_rfB_SA6F9ycVo6ve8Cbw.png" /></figure><p>Thus for each t, the budget allocated to a touch-point can not be less than [100 x p(1)]% of the total allocated budget. Moreover, for each t, we only vary the {100 x [1-Kp(1)] x [1-p(2)]}% of the total available budget in proportion to ROIs, while the remaining {100 x [1-Kp(1)] x p(2)}% will be allocated in proportion to the allocation made at t-1.</p><p>In the following we will present a simulation study on three touch-points: <em>E</em> (email), <em>S</em> (social), and <em>B</em> (banner) where:</p><ol><li>Total budget B*(t) is equal to 3,000 euros and it remains constant over time;</li><li>p(1)=1% and p(2)=10% thus at each t: the budget allocated to a touch-point can not be less than 1% of the total allocated budget while we only vary the 9.7% of the total allocated budget using ROIs;</li><li>Each conversion is valued 30 euros;</li><li>E costs 0.1 eur/touch, <em>S</em> and <em>B</em> cost 1 eur/touch;</li></ol><p>For generating paths and conversions we split the generation process into three steps:</p><ol><li>Define a model that quantifies how much traffic is generated on each touch-point given the budget allocated;</li><li>Define a model that generates customer journeys for a given traffic level;</li><li>Define a model that for each generated path decides if it ends in a conversion or not.</li></ol><p>First of all, we need to define a function that links the budget allocated to each touch-point, with the traffic generated on that touch-point. For simplicity, we will assume that there is a deterministic relationship between them that follows a logistic curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*7rVgxvPd4p_rWuerHKMF7g.png" /></figure><p>where L(α) is the maximum level of traffic reachable, x(α), the x-value of the sigmoid’s midpoint, and k(α) the logistic growth rate or steepness of the curve. The curve is also been rescaled to let it intersect (0,0). Below the curve for touch-point <em>E</em> is shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*q8YbLvVLvVCTejPHw6T64A.png" /></figure><p>A logistic relationship is more realistic than a linear one because we can not expect that increasing the budget will always increase traffic at the same rate. The following table shows the parameters adopted for each touch-point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*nJDstEZbUv42cCtlhCpa1A.png" /></figure><p>Now for a given budget allocation, we have the traffic generated on each touch-point. Traffic indicates the maximum number of touches we could have for each touch-point. <br>With this information, we can generate customer journeys. Paths are generated once at the time with the following probability function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*rbTt1HvRnARgdIRgs3S4og.png" /></figure><p>After each generation, the available traffic for each touch-point is decreased. When available traffic for touch-point α reaches 0 then all probabilities associated with paths that include α are set to 0. Thus if, for example, traffic of <em>S</em> reaches 0 then the probability function becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*csK1VkCPawT5UzsN724gKg.png" /></figure><p>Once a path is generated we have to decide if it ends with a conversion or not. We use the following probability function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*qe7UXxJnmPCkh5WqJXuWsw.png" /></figure><p>Now we want to evaluate the performance of the following path-level attribution models in terms of generated profit:</p><p><em>roi-last-touch</em></p><p>Attribution is made at path-level using last-touch approach, then budget is split through ROI.</p><p>This is the well-known last-touch approach that we have discussed in section 2.</p><p><em>roi-shapley</em></p><p>Attribution is performed at path-level using Shapley value, then budget is splitted through ROI.<br>Shapley value for a touch-point k is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*lNEYgeQn3c4M-Mg9puIFsg.png" /></figure><p>where <em>K</em>={1,…,K} is the set of touch-points, S a subset of <em>K</em>, |<em>S</em>| the cardinality of <em>S</em> and ν(<em>S</em>) the contribution of <em>S</em>.<br>In our case ν(S) is the conversion rate of <em>S</em>.</p><p><em>roi-logistic</em></p><p>Attribution is made at path-level using logistic regression, then budget is split using ROI.<br>Logistic regression is implemented using the following formulation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*3k6RN-4QjQFFsMFU1ERejg.png" /></figure><p>where Y(i) is equal to 1 if path i converts, C(i, k) is equal to 1 if touch-point k belongs to path i and C(i, kh) is equal to 1 if both touch-point k and touch-point h belong to path i.</p><p><em>roi-markov-re</em></p><p>Attribution is performed at path-level using Markov model and removal effects, then budget is split using ROI.<br>In this case, we use the removal effects calculated from Markov model to perform path-level attribution as we did in section 2. This method is widely used in practice despite it leads to an incorrect attribution when there are high-frequency touch-points.</p><p><em>roi-markov-re-corr</em></p><p>Attribution is performed at path-level using Markov model and corrected removal effects, then budget is split using ROI.<br>In this case, removal effects from Markov model are used at path-level before they are iteratively corrected to let path-level attribution match global attribution.</p><p><em>roi-markov-odds</em></p><p>Attribution is performed at path-level using Markov model and odds, then budget is split through ROI.<br> In this case, odds are calculated from Markov model and used for path-level attribution, as we did in section 2.</p><p>The experiment has been repeated 30 times r=1,…,30 and each time, budget allocation and profit calculation were made for 15 time instances t=1,…,15. <br>For each r at t=1 a random budget allocation is generated. Using all 30 replications we found the following empirical confidence interval for the observed profit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*Q3kFs4hjhwcEC_B2YZnw7A.png" /></figure><p>where profit is the 50th percentile of the empirical distribution of the profits calculated considering all the 30 customer-journey datasets generated, l.b. is the 5th percentile, and u.b. is the 95th percentile. We see that if a random budget allocation is adopted, then we expect a median profit of 1,030 euros. <br> <br>For each r, at t=2 each model proposes a new budget allocation based on ROI. Then customer journeys are generated and profit is calculated. We obtained the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*g9V5SmZ3bToMwkDGBNXWQA.png" /></figure><p>We see that Markov with odds and Markov with corrected removal effects reaches the higher profit while Markov that uses the overall removal effects generates a lower one. This confirms that the practice of using overall removal effects in path-level attribution is not optimal.</p><p>t=2 is quite important because it is the first budget allocation after a random allocation. Our use-case is simple and there are no external factors that affect the system. Thus the capacity to generate profit starting from a random budget allocation can be viewed as the capacity of generating profit when exogenous unpredictable external factors are present. And it seems that Markov model has this capacity much more than the other models.</p><p>The overall results, considering all the 30x15 profits generated for each model are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*UmKWFq0tYwZ8L58LwHIS4g.png" /></figure><p>We can also plot the median profit over time for each model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*PUaaIdbFd2FbPWwJRTTQrQ.png" /></figure><p>These results confirm that <em>Markov model with odds is a valid methodology for path-level attribution when high-frequency and dependent touch-points are present, as it usually happens in real use-cases</em>.</p><h4>6. Path-level attribution with ChannelAttributionPro</h4><p>In the following, it will be shown how easy is to perform transaction-level attribution using <em>ChannelAttributionPro</em> with R or Python.</p><p>For any detail about how to install <em>ChannelAttributioPro</em> and to get a password visit <a href="https://channelattribution.io/">channelattribution.io</a>.</p><p><strong>R</strong></p><pre>library(ChannelAttributionPro)</pre><pre>##########  <br>#Load Data<br>##########  </pre><pre>data(PathData)<br>  <br>password=&quot;youpassword&quot;</pre><pre>######  <br>#Train<br>######  </pre><pre>res=markov_model(Data, var_path=&quot;path&quot;,var_conv=&quot;total_conversions&quot;, var_value=&quot;total_conversion_value&quot;,var_null=&quot;total_null&quot;,order=1, sep=&quot;&gt;&quot;,ncore=1,out_more=TRUE,verbose=TRUE,type=&quot;odds&quot;,password=password)</pre><pre>######################  <br>#Save path attribution<br>######################<br>  <br>res_path_attr=res$path_attribution</pre><p><strong>Python</strong></p><pre>from ChannelAttributionPro import *<br> <br>password=”youpassword”</pre><pre>############## <br>#Download data<br>############## </pre><pre>Data=pd.read_csv(“<a href="https://channelattribution.io/csv/Data.csv">https://channelattribution.io/csv/Data.csv</a>&quot;,sep=&quot;;&quot;)</pre><pre>###### <br>#Train<br>######<br> <br>res=markov_model(Data, var_path=”path”,var_conv=”total_conversions”, var_value=”total_conversion_value”,var_null=”total_null”, order=1, sep=”&gt;”,ncore=1,out_more=True,verbose=True,type=”odds”,password=password)</pre><pre>###################### <br>#Save path attribution<br>###################### </pre><pre>res_path_attr=res[‘path_attribution’]</pre><h4>5. Conclusions</h4><p>Nowadays budget allocation in digital marketing is heavily based on multi-touch attribution and return on investment (ROI) calculation. Attribution and budget allocation are two deeply different concepts and some authors suggest avoiding using attribution for budget allocation purposes. Despite using ROI for budget allocation is not optimal, considering a more complex approach does not ensure that an optimal allocation can be found in any case. That is because real use cases are complex to be modeled and require many assumptions. For this reason, attribution remains crucial in budget allocation strategy.</p><p>ROI is an effective measure in budget allocation only if conversion value is correctly attributed to each touch-point. When high-frequency and/or dependent touch-points are present, as usually happens in real use-cases, then non-probabilistic approaches can perform significantly worse than probabilistic ones. Through a simple but realistic simulation study, we showed that Markov model when used in ROI calculation is able to generate more profit than last-touch. Markov model also outperforms Shapley value and logistic regression.</p><p>Path-level attribution with Markov model is usually implemented using removal effects as weights. We showed that this choice is not able to correctly manage high-frequency touch-points. Hence we have proposed odds as an effective and alternative measure to removal effects. In the use-case presented we have seen that, if path-level attribution is performed using Markov model with odds, better performance in terms of profit can be reached.</p><p><em>ChannelAttributionPro</em> is the professional library available for R and Python intended for companies who want to make a more accurate attribution and budget allocation for increasing their profit. It lets to calculate path-level attribution with Markov model and odds easily and fast. If you need the code to replicate the simulation study presented and/or other information about <em>ChannelAttributionPro</em>, visit <a href="https://channelattribution.io/">channelattribution.io</a>.</p><h4>6. References</h4><p>[1] Anderl E. et al., <em>Mapping the Customer Journey: A Graph-Based Framework for Online Attribution Modeling</em>, 2014, <a href="http://dx.doi.org/10.2139/ssrn.2343077">doi</a></p><p>[2] Xuhui S. and Lexin L.,<em> Data-driven Multi-touch Attribution Models,</em> 2011, <a href="https://doi.org/10.1145/2020408.2020453%7D%7Burl">doi</a><br> <br>[3] Danaher P. and Heerde H., Delusion in Attribution: <em>Caveats in Using Attribution for Multimedia Budget Allocation</em>, 2018, <a href="https://doi.org/10.1177/0022243718802845%7D%7Burl">doi</a><br> <br> [4] Zhao K., Mahboobi S.H., Bagheri S.R., <em>Shapley Value Methods for Attribution Modeling in Online Advertising, 2012, </em><a href="https://doi.org/10.48550/arXiv.1804.05327%7D%7Burl">doi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce04b492604d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Time Series Forecasting with rego in R and Python]]></title>
            <link>https://medium.com/@davide.altomare/automatic-time-series-forecasting-with-rego-in-r-and-python-192b0016f23f?source=rss-bec4a2b7e113------2</link>
            <guid isPermaLink="false">https://medium.com/p/192b0016f23f</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[timeseries]]></category>
            <dc:creator><![CDATA[Davide Altomare]]></dc:creator>
            <pubDate>Tue, 11 Jan 2022 14:32:56 GMT</pubDate>
            <atom:updated>2023-04-21T07:02:43.026Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A tutorial to learn how to use </em><strong><em>rego</em></strong><em>, a new machine learning library for automatic time series forecasting available for R and Python.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5afNkV8_yXvvsY0LEbGkQ.png" /></figure><h4>1. What is rego?</h4><p><strong><em>rego</em></strong> is a new machine learning algorithm for predicting and imputing time series. It can automatically set all the parameters needed, thus in the minimal configuration it only requires the target variable and the dependent variables if present. It can address large problems with hundreds or thousands of dependent variables and problems in which the number of dependent variables is greater than the number of observations. Moreover, it can be used not only with time series but also with any other real-valued target variable. The algorithm implemented includes a Bayesian stochastic search methodology for model selection and a robust estimation based on bootstrapping. <strong><em>rego</em></strong> is fast because all the code is C++.</p><h4>2. What you will learn?</h4><p>During this tutorial you will learn how to:</p><ul><li>install <strong><em>rego</em></strong> in R and Python</li><li>forecast time series using <strong><em>rego </em></strong>in R and Python.</li></ul><h4>3. How to install rego in R</h4><p>You can install <strong><em>rego</em></strong> directly from CRAN.</p><pre>install.packages(&quot;rego&quot;)</pre><h4>3. How to install rego in Python</h4><p>You can install <strong><em>rego</em></strong> using PIP, after having installed its dependencies: setuptools, Cython and pandas.</p><pre>pip install --upgrade setuptools<br>pip install Cython<br>pip install pandas</pre><pre>pip install rego</pre><h4>4. How to forecast time series with rego</h4><p>Now we are ready to try <strong><em>rego</em></strong> using a real-time series. First of all, we need to load our data: a univariate time series.</p><p><strong><em>#R</em></strong></p><pre>library(rego)</pre><pre>Data=read.csv(&quot;https://app.channelattribution.net/data/Data_air.csv&quot;,sep=&quot;;&quot;,header=FALSE) <br>colnames(Data)=c(&quot;target&quot;)</pre><p><strong><em>#Python</em></strong></p><pre>import pandas as pd <br>from rego import * <br>import plotly.express as px</pre><pre>Data=pd.read_csv(&quot;https://app.channelattribution.net/data/Data_air.csv&quot;,sep=&quot;;&quot;,header=None) <br>Data.columns=[&quot;target&quot;]</pre><p>As you can see our data is stored in a pandas DataFrame with the target variable as the first column. But <strong><em>rego</em></strong> can also accept dependent variables that have to be stored from the second column onwards.</p><p>We can plot our target variable.</p><p>More information can be found on the official page of the project.</p><p><strong><em>#R</em></strong></p><pre>plot(Data$target,type=&quot;l&quot;,ylab=&quot;target&quot;)</pre><p><strong><em>#Python</em></strong></p><pre>fig = px.line(Data,y=&quot;target&quot;) <br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NH4XqJUJZ9tl1lgYkjcDsg.png" /></figure><p>As you can see our target variable is a seasonal time series with an increasing trend. Moreover, there are some missing observations in the middle of the time series. There are also some missing observations at the end of the time series that represent our forecast horizon. I mean that the missing observations at the end of the time series were artificially added to let rego make predictions on them. Thus <strong><em>rego</em></strong> makes predictions on all the missing observations present.</p><p><strong><em>rego</em></strong> includes a function called <em>regpred</em> which can be used to make predictions.</p><p><strong>#R</strong> and <strong>#Python</strong></p><pre>res=regpred(Data)</pre><p><em>regpred</em> takes as input the DataFrame with the target variable and returns a list containing a Dataframe with predictions and prediction interval that can be finally plotted.</p><p><strong>#R</strong></p><pre>predictions=res$prediction<br> plot(predictions$real,type=&quot;l&quot;,ylim=c(min(predictions,na.rm=TRUE)*0.95,max(predictions,na.rm=TRUE)*1.05)) lines(predictions$predicted,col=”blue”) lines(predictions$lower_bound,col=”red”) lines(predictions$upper_bound,col=”red”)</pre><p><strong>#Python</strong></p><pre>predictions=res[&quot;prediction&quot;] </pre><pre>fig = px.line(predictions) <br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*UowigK6LH0lZvYMZqsLZ8A.png" /></figure><h4>4. Relevant links</h4><p><a href="https://channelattribution.io/pdf/RegoDocs.pdf">Documentation</a></p><p><a href="https://cran.r-project.org/web/packages/rego/index.html">R CRAN</a></p><p><a href="https://pypi.org/project/rego/1.2.2/">Python PYPI</a></p><p><a href="https://github.com/DavideAltomare/rego">GIT</a></p><h4>5. Conclusion</h4><p>In this tutorial, we have shown how it is easy to use <strong><em>rego</em></strong> with R and Python to automatically predict univariate time series with or without missing values.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192b0016f23f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>