<?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 Damien Querbes on Medium]]></title>
        <description><![CDATA[Stories by Damien Querbes on Medium]]></description>
        <link>https://medium.com/@querbes.damien?source=rss-8076ae32af66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A2lnVFoubqdcK-ahqVaxxg.jpeg</url>
            <title>Stories by Damien Querbes on Medium</title>
            <link>https://medium.com/@querbes.damien?source=rss-8076ae32af66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:16:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@querbes.damien/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[The benefits of Bayesian models compared to traditional ones + Intro to Gaussian Processes]]></title>
            <link>https://medium.com/@querbes.damien/the-benefits-of-bayesian-models-compared-to-traditional-ones-0b78f7efdde0?source=rss-8076ae32af66------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b78f7efdde0</guid>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[mmm]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[marketing-mix-modelling]]></category>
            <dc:creator><![CDATA[Damien Querbes]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 10:46:49 GMT</pubDate>
            <atom:updated>2025-04-09T09:15:14.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>The benefits of Bayesian Models compared to Traditional ones for MMM and Intro to Gaussian Processes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9JE9YIbM57DkBU49SsoLA.jpeg" /><figcaption>Bayes’ theorem</figcaption></figure><p>In my <a href="https://medium.com/@querbes.damien/traditional-machine-learning-models-for-marketing-mix-modelling-6bf820124e50">previous article</a>, we explored traditional machine learning approaches for Marketing Mix Modelling (MMM) and identified their strengths and limitations. Linear regression models with adstock and saturation transformations performed well for simple patterns but faltered when faced with complex non linear dynamics that are difficult to incorporate in the features engineering process. On the other hand, SHAP values applied to a Gradient boosting model turned out to be very handy to explain saturation effects and this model also yields some decent performance at predicting future sales. Yet, it was not explainable enough in order to make the right business decisions such as where to allocate budgets.</p><p>This article delves into Bayesian approaches for MMM using <a href="https://www.pymc.io/">PyMC</a>, focusing on how they can address the limitations we encountered previously. We will use the same synthetic datasets from our first article, enabling direct comparison between traditional and Bayesian methods.</p><p>Throughout this article, we’ll explore:</p><ul><li>How Bayesian models work through a quick intro about Markov Chain Monte Carlo sampler</li><li>A step-by-step process to fit a Bayesian model properly in Marketing Mix Modelling</li><li>The main advantages of Bayesian models compared to traditional ML models</li><li>A quick intro about Gaussian process to model complex non linear patterns</li></ul><h3>Quick intro of Bayesian models</h3><p><a href="https://twiecki.io/blog/2015/11/10/mcmc-sampling/">MCMC sampling for dummies</a> from Thomas Wiecki (one of the founders of PyMC lab) is one of the best piece of content I have read that explain the Bayes‘ theorem used for inference and the algorithm to approximate some of its components. My below example is directly inspired from his article (he goes deeper into details though).</p><p>Let’s imagine you get a sample of 10 observations from a Normal(0, 1):</p><pre># 1. Generate synthetic data: 10 samples from a Normal(0, 1)<br>np.random.seed(123)<br>data = np.random.randn(10)<br><br>fig = sns.displot(data, kde=False, binwidth=1)<br>fig.set(title=&#39;Histogram of observed data&#39;, xlabel=&#39;x&#39;, ylabel=&#39;# observations&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*PHK_y__HEJY5wPz0noPudw.png" /><figcaption>Image from the author</figcaption></figure><p>We know that this sample was generated by a Normal distribution but we are not aware of its parameters. Our goal is to recover mu (we simplified and assume the sigma =1). This basically means computing P(mu|data).</p><p><em>Bayes’ theorem</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*9Fag_XXoSUSpi79qV6YbpQ.png" /></figure><p>Until recently, this formula was a vague souvenir from I learnt at school and prep-school and I had no idea how this could applied to real world problems. Yet, we will see below that Bayes’ theorem is powerful to approximate a distribution curve given a small sample.</p><p>Let’s give a closer look at its components:</p><ul><li>P(data∣mu) is the <strong>likelihood</strong>, it <strong>tells you “how well” a particular value of mu <em>fits</em> or <em>generates</em> the <em>observed</em> data — </strong>that is, if mu is a poor guess (doesn’t match the data), that likelihood is low; if it’s a great guess, the likelihood is high.</li><li>P(mu) is the prior, it tells you <strong>how plausible mu is <em>before</em> seeing the data.</strong></li><li>P(data) is the <strong>marginal likelihood</strong> or <strong>evidence</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*A4zc1YXTJcqasPwKmbJK2Q.png" /></figure><p>The numerator of the Bayes’ theorem balances both factors. You want a value of mu that both <strong>fits the data</strong> well <em>and</em> is <strong>reasonable</strong> given your prior beliefs. The product Likelihood x Prior can be seen the score of mu. And good news, these components can be easily computed with a computer.</p><p>The true complexity in this equation lies in its denominator because the above integral is impossible to calculate most of the times in closed form.</p><p>This is where <a href="https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo">Markov Chain Monte Carlo</a> kicks in!</p><p><em>Markov Chain Monte Carlo’s trick</em></p><p>Put simply, as we can’t compute P(data) easily, we want to iterate in new mu values and see how the score of mu_new / score of current_mu — this is called the <strong>acceptance ratio alpha</strong>. When we compute the ratio P(mu_new|data) / P(mu|data), P(data) cancels out and we don’t need it anymore! If the ratio is above 1, it means the mu_new score is better and we should use it for the next iteration. If below 1, we don’t necessarily want to exclude this mu_new; instead, we draw a random number u between 0 and 1:</p><ul><li>if u &lt; acceptance ratio, we keep the new mu (even though the mu_new’s score is worse) to promote exploration and prevent the chain from getting stuck in local optima.</li><li>if u &gt; acceptance ratio, we reject the new_mu and keep the current value.</li></ul><p>Repeating these steps many times creates a “chain” of mu values that (over time) reflects the <em>true</em> posterior distribution — <strong>even though we never had to compute any big scary integrals (the evidence).</strong></p><p>Let’s visualise it with python. For this example, we assumed we had some prior knowledge before having seen the data:</p><ul><li>we are confident enough that data comes from N(-1,2) — which is not very restrictive when comparing with the data sample.</li></ul><pre>import scipy.stats as st<br><br><br># Define the unnormalized posterior: likelihood * prior<br>def posterior(mu, data, mu_prior=-1, sigma_prior=2, sigma=1):<br>    # Likelihood: product of probabilities of each data point<br>    likelihood = np.prod(norm(mu, sigma).pdf(data))<br>    # Prior: assume a Normal(mu_prior, sigma_prior)<br>    prior = norm(mu_prior, sigma_prior).pdf(mu)<br>    return likelihood * prior<br><br># Implement the Metropolis sampler<br>def metropolis_sampler(data, num_samples=10000, mu_init=1.0, proposal_width=0.5):<br>    samples = [mu_init]<br>    current_mu = mu_init<br>    for _ in range(num_samples):<br>        # Propose a new mu by drawing from a normal distribution centered at the current value<br>        proposal = norm(current_mu, proposal_width).rvs()<br>        # Compute the acceptance ratio<br>        p_current = posterior(current_mu, data)<br>        p_proposal = posterior(proposal, data)<br>        acceptance_ratio = p_proposal / p_current<br>        # Accept or reject the proposal based on the acceptance ratio<br>        if np.random.rand() &lt; acceptance_ratio:<br>            current_mu = proposal<br>        samples.append(current_mu)<br>    return np.array(samples)<br><br># Run the sampler<br>samples = metropolis_sampler(data, num_samples=10000, mu_init=1.0, proposal_width=0.5)<br><br># Posterior samples are in &quot;samples&quot;<br>plt.hist(samples, bins=30, density=True, alpha=0.5, label=&#39;Posterior samples&#39;)<br><br># Overlaid approximate KDE for the posterior<br>kde = st.gaussian_kde(samples)<br>mus_dense = np.linspace(-3, 3, 300)<br>plt.plot(mus_dense, kde(mus_dense), label=&#39;KDE of posterior&#39;, linewidth=2)<br><br>plt.xlabel(&#39;mu&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.title(&#39;Posterior Distribution of mu&#39;)<br>plt.legend()<br>plt.show()</pre><p>This gives us the posterior distribution of mu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*incMO2soPtuvvY5NrqbEwA.png" /><figcaption>Image from the author</figcaption></figure><p>Now, to sample over the distribution of all possible mu, we do:</p><pre>posterior_predictive_samples = norm.rvs(loc=samples, scale=sigma)</pre><p>Basically, for each mu in samples, it generates one draw from N(mu_i, sigma).</p><pre>sigma = 1.0<br><br>num_draws = 10000<br><br><br>true_samples = norm(0, 1).rvs(num_draws)<br><br>mus_from_prior = norm(mu_prior, sigma_prior).rvs(num_draws)<br>prior_predictive_samples = norm.rvs(loc=mus_from_prior, scale=sigma)<br><br># Posterior predictive:<br>posterior_predictive_samples = norm.rvs(loc=samples, scale=sigma)<br><br>plt.hist(true_samples, bins=30, density=True, alpha=0.4, label=&#39;True samples&#39;)<br>plt.hist(prior_predictive_samples, bins=30, density=True, alpha=0.5, label=&#39;Prior predictive&#39;)<br>plt.hist(posterior_predictive_samples, bins=30, density=True, alpha=0.5, label=&#39;Posterior predictive&#39;)<br>plt.xlabel(&#39;Predicted x&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.title(&#39;Prior vs. Posterior Predictive Distribution&#39;)<br>plt.legend()<br>plt.show()</pre><p>This gives us the posterior predictive distribution. We can now compare it with the initial distribution from which our sample comes from?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Ud5Qr6srDb0hUH5pZIGibA.png" /><figcaption>Image from the author</figcaption></figure><p>We see that despite a sample of only 10 observations, our model successfully managed to capture the distribution’s parameters of our initial sample. This is the true strength of Bayesian models!</p><h3>Bayesian models in Marketing Mix Modelling</h3><p>In my previous article, we saw how the sales or conversions metrics could be predicted through a multivariate regression model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3sb5sc2GnL4MFnicQbiRQ.png" /></figure><p>To compare Bayesian models with those “traditional models” seen in the previous article, I’ll reuse the same dataset in order to see how it performs on test set (the last 50 observations). I will also use PyMC backend with MCMC sampler that beautifully executes what we explored above.</p><p>My notebook is available <a href="https://github.com/querbesd/marketing-mix-modelling/blob/master/notebooks/1_pymc_vs_traditional_models.ipynb">here</a>.</p><h4>Step by step process</h4><p><strong><em>Setting up time index and test size</em></strong></p><pre>test_size = 50<br><br><br>t = (dataset.date - dataset.date.min()) / (dataset.date.max() - dataset.date.min())<br>t = t.values<br>t_train = t[None:-test_size]<br>t_test = t[-test_size:None]</pre><p>Here, we simply scale the time index before applying our train test split.</p><p><strong><em>Fourier features</em></strong></p><p>For Fourier features, we sticked to what we did in the previous article and we still assume that we have 2 cycles per year (n_order=2).</p><pre># Fourier features<br>n_order = 2<br>periods = dataset.date.dt.dayofyear / 365.25<br>fourier_features = pd.DataFrame(<br>    {<br>        f&quot;{func}_order_{order}&quot;: getattr(np, func)(2 * np.pi * periods * order)<br>        for order in range(1, n_order + 1)<br>        for func in (&quot;sin&quot;, &quot;cos&quot;)<br>    }<br>)</pre><p><strong><em>Scaling data</em></strong></p><pre>dataset[&#39;target_scaled&#39;] = xr.DataArray(<br>    np.zeros((len(dataset.date), len(countries))),<br>    coords={&#39;date&#39;: dataset.date, &#39;country&#39;: countries},<br>    dims=[&#39;date&#39;, &#39;country&#39;]<br>)<br><br>dataset[&#39;z_scaled&#39;] = xr.DataArray(<br>    np.zeros((len(dataset.date), len(channels), len(countries))),<br>    coords={&#39;date&#39;: dataset.date, &#39;channel&#39;: channels, &#39;country&#39;: countries},<br>    dims=[&#39;date&#39;, &#39;channel&#39;, &#39;country&#39;]<br>)<br><br><br># Instantiate scalers<br>target_scaler = MaxAbsScaler()<br>channel_scaler = MaxAbsScaler()<br><br># Fit scalers<br>target = dataset.target.values.reshape(-1, 1)<br>spend = dataset.spends.values.reshape(-1, dataset.spends.shape[-1])<br><br>target_train = target[None:-test_size]<br>target_test = target[-test_size:None]<br><br><br>spend_train = spend[None:-test_size]<br>spend_test = spend[-test_size:None]<br><br>target_scaler.fit(target_train)<br>channel_scaler.fit(spend_train)<br><br><br># Then apply scaling<br>for i, country in enumerate(countries):<br><br>    target_scaled = target_scaler.transform(target_train.reshape(-1,1)).flatten()<br>    target_test_scaled = target_scaler.transform(target_test.reshape(-1,1)).flatten()<br>    z_scaled = channel_scaler.transform(spend_train)<br>    z_test_scaled = channel_scaler.transform(spend_test)</pre><p>We use MaxAbsScaler() to scale the channel spends and the target. This means we work in a [0,1] space.</p><p><strong><em>PyMC model setup</em></strong></p><pre><br># Setup<br>n_order = 2<br>dates = dataset.date.values[None:-test_size]<br>coords = {&quot;channel&quot;: channels, &quot;fourier_mode&quot;: np.arange(2 * n_order)}<br><br><br>with pm.Model(coords=coords) as model:<br>    # --- coords --- #<br>    model.add_coord(name=&quot;date&quot;, values=dates)<br><br>    # --- data containers --- #<br>    data = pm.Data(<br>       &quot;data&quot;,<br>       z_scaled,<br>       dims=(&quot;date&quot;, &quot;channel&quot;),<br>    )<br><br>    fourier_feature_data = pm.Data(<br>        &quot;fourier_features&quot;,<br>        fourier_features[None:-test_size],<br>        dims=(&quot;date&quot;, &quot;fourier_mode&quot;)<br>    )<br><br>    t_data = pm.Data(<br>        &quot;t&quot;,<br>        t_train,<br>        dims=&quot;date&quot;<br>    )<br><br>    sales_data = pm.Data(<br>        &quot;sales&quot;,<br>        target_scaled,<br>        dims=&quot;date&quot;<br>    )<br><br>    # --- priors --- #<br>    ## intercept<br>    a = pm.HalfNormal(name=&quot;a&quot;, sigma=0.5)<br>    ## trend<br>    b_trend = pm.HalfNormal(name=&quot;b_trend&quot;, sigma=2)<br>    ## adstock effect<br>    alpha = pm.Beta(name=&quot;alpha&quot;, alpha=2, beta=2, dims=&quot;channel&quot;)<br>    ## saturation effect<br>    lam = pm.Gamma(name=&quot;lam&quot;, alpha=3, beta=1, dims=&quot;channel&quot;)<br>    ## seasonality<br>    b_fourier = pm.Laplace(name=&quot;b_fourier&quot;, mu=0, b=0.2, dims=&quot;fourier_mode&quot;)<br>    ## regressor<br>    b_z = pm.HalfNormal(name=&quot;b_z&quot;, sigma=channel_share_array.reshape(-1,1).flatten(), dims=&quot;channel&quot;)<br>    ## standard deviation of the normal likelihood<br>    sigma = pm.HalfNormal(name=&quot;sigma&quot;, sigma=0.5)<br>    # degrees of freedom of the t distribution<br>    nu = pm.Gamma(name=&quot;nu&quot;, alpha=25, beta=2)<br><br>    # --- model parametrization --- #<br>    trend = pm.Deterministic(name=&quot;trend&quot;, var=a + b_trend * t_data, dims=&quot;date&quot;)<br>    seasonality = pm.Deterministic(<br>        name=&quot;seasonality&quot;, var=pm.math.dot(fourier_feature_data, b_fourier), dims=&quot;date&quot;<br>    )<br><br>    z_adstock = pm.Deterministic(<br>        name=&quot;z_adstock&quot;, var=geometric_adstock(x=data, alpha=alpha, l_max=8, normalize=True), dims=(&quot;date&quot;,&quot;channel&quot;)<br>    )<br><br>    z_adstock_saturated = pm.Deterministic(<br>        name=&quot;z_adstock_saturated&quot;,<br>        var=logistic_saturation(x=z_adstock, lam=lam),<br>        dims=(&quot;date&quot;,&quot;channel&quot;),<br>    )<br>    z_effect = pm.Deterministic(<br>        name=&quot;z_effect&quot;, var=b_z * z_adstock_saturated, dims=(&quot;date&quot;,&quot;channel&quot;)<br>    )<br><br><br>    mu = pm.Deterministic(name=&quot;mu&quot;, var=trend + seasonality + z_effect.sum(axis=1), dims=&quot;date&quot;)<br><br>    # --- likelihood ---<br>    y = pm.StudentT(name=&quot;likelihood&quot;, nu=nu, mu=mu, sigma=sigma, observed=sales_data, dims=&quot;date&quot;)<br><br><br>    # --- prior samples --- #<br>    adstock_saturation_model_prior_predictive = pm.sample_prior_predictive()<br><br>pm.model_to_graphviz(model=model)</pre><p>Here is a high level walkthrough:</p><ul><li>Create a PyMC model with pm.Model() and define its dimensions through coords variable. Dimensions can be either created before and within the model (as we do with dates).</li><li>Create Data Containers for your pre-processed features and scaled target. Use the dims variable to tell PyMC about the shape of your Data Containers.</li><li>Convey your domain knowledge with Priors definition. More on the next section.</li><li>pm.Deterministic creates named variables in the trace for intermediate calculations (so you can inspect them after sampling).</li><li>Build your likelihood y (remember P(data | mu)) after picking your likelihood distribution. For MMM most common likelihoods are Normal distribution or Student_T that is more resistant to outliers. To understand the likelihood distribution, I really recommend <a href="https://www.youtube.com/watch?v=0_oonRc7Sn8">this video</a>.</li></ul><p><strong><em>Focus on Prior specification</em></strong></p><p>Prior definition is a key process as it allows you to convey your domain knowledge based on past experiments, discussions with field experts, or simply common sense. The more informative (aka restrictive) your priors, the more you calibrate your model (i.e., constrain your model parameters to plausible regions of parameter space). This is especially important when your model incorporates complex relationships which may lead to overfitting without appropriate regularization through priors.</p><p>Let’s focus on each prior individually and show their distribution:</p><ul><li>a is an <strong>intercept</strong> term with a half-normal prior. Why? Because the intercept term is always positive. To study prior distribution, <a href="https://preliz.readthedocs.io/en/latest/">preliz</a> library is of a great help.</li></ul><pre>import preliz as pz<br><br>fig, ax = plt.subplots(figsize=(10, 6))<br>pz.HalfNormal(sigma=0.5).plot_pdf(ax=ax)<br>ax.set(xlabel=r&quot;Intercept&quot;)<br>ax.set_title(label=r&quot;Prior Distribution intercept&quot;, fontsize=18, fontweight=&quot;bold&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-MXwIpKOVZXnLXPxMvIMOg.png" /><figcaption>Image from the author</figcaption></figure><p>The highest density is near 0 which makes sense as the base sales is more likely to be closer to 0 than to 1. Keep in mind our target has been scaled and belongs to [0, 1] space.</p><ul><li>b_trend is a <strong>trend slope</strong> (also half-normal which may make sense as you may assume your trend slope is positive).</li><li>alpha is the <strong>adstock decay</strong> parameter (with a Beta prior, typical for 0–1 range). Here, let’s assume we have very little domain knowledge so we opt for a weakly informative prior.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7wXY9ndRdtooR0CJR9Cnw.png" /><figcaption>Image from the author</figcaption></figure><ul><li>lam is a <strong>saturation</strong> parameter (Gamma prior). Again, our prior is weakly informative here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Rjm38d416gJn0i2DRsx_Q.png" /><figcaption>Image from the author</figcaption></figure><ul><li>b_fourier captures <strong>seasonality</strong> effects (Laplace prior regularize your seasonality coeffecients — the higher b the bigger the distribution tails i.e. you allow higher coefficients). Be careful with high b as it may lead to overfitting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grGOPpzzkXjv1toIPxgleA.png" /></figure><ul><li>b_z are the <strong>regression coefficients</strong> for each channel (half-normal as we expect the channel contribution to be positive). It is a sensitive prior as channel spend is one of your most influential model features. You have several options here: 1/ you can use information from your attribution tool and use a Normal prior centered on the max channel contribution divided by the maximum absolute value of the target (see this discussion <a href="https://github.com/pymc-labs/pymc-marketing/discussions/617#discussioncomment-9244139">here </a>), 2/ you can use the spend share assuming marketing strategies are wisely performed and that the actual channel contributions are not that far away from the spend share breakdown. In our case, we took the second option:</li></ul><pre>channel_share_array = spends.sum(axis=0) / spends.sum().sum()</pre><ul><li>sigma is the <strong>noise</strong> scale (in this case, the StudentT’s scale parameter).</li><li>nu is the <strong>degrees of freedom</strong> for the StudentT. This controls tail heaviness.</li></ul><p><strong><em>Prior Predictive Samples</em></strong></p><p>Before fitting the model, a common good practice is to check the prior predictive samples in order to ensure that our prior beliefs is not too restrictive.</p><pre># useful way to color the distribution<br>palette = &quot;viridis_r&quot;<br>cmap = plt.get_cmap(palette)<br>percs = np.linspace(51, 99, 100)<br>colors = (percs - np.min(percs)) / (np.max(percs) - np.min(percs))<br><br><br>fig, ax = plt.subplots()<br><br>for i, p in enumerate(percs[::-1]):<br>    upper = np.percentile(adstock_saturation_model_prior_predictive.prior_predictive[&quot;likelihood&quot;], p, axis=1)<br>    lower = np.percentile(<br>        adstock_saturation_model_prior_predictive.prior_predictive[&quot;likelihood&quot;], 100 - p, axis=1<br>    )<br>    color_val = colors[i]<br>    ax.fill_between(<br>        x=dates,<br>        y1=upper.flatten(),<br>        y2=lower.flatten(),<br>        color=cmap(color_val),<br>        alpha=0.1,<br>    )<br><br>sns.lineplot(x=dates, y=target_scaled, color=&quot;black&quot;, label=&quot;target (scaled)&quot;, ax=ax)<br>ax.legend()<br>ax.set(title=&quot;Model - Prior Predictive Samples&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rO4QcFoMP6Urm7q5vZZlw.png" /><figcaption>Image from the author</figcaption></figure><p>The range is not too narrow which means that our priors are not too informative which is the expected goal 👍</p><p><strong><em>Model fitting</em></strong></p><pre>with model:<br>    base_model_trace = pm.sample(<br>        nuts_sampler=&quot;numpyro&quot;,<br>        draws=2_000,<br>        target_accept=0.95,<br>        chains=4,<br>        idata_kwargs={&quot;log_likelihood&quot;: True},<br>        random_seed=rng<br>    )<br>    base_model_posterior_predictive = pm.sample_posterior_predictive(<br>        trace=base_model_trace,<br>        random_seed=rng,<br>        var_names=[&quot;likelihood&quot;],<br><br>    )<br><br>    base_model_trace.extend(base_model_posterior_predictive)</pre><p>This launches model training with NUTS algorithm and 4 chains training in parallel. We use <a href="https://num.pyro.ai/en/stable/"><em>numpyro</em></a><em> </em>backend to achieve fast results.</p><p>To check the number of divergences during fitting:</p><pre>base_model_trace[&quot;sample_stats&quot;][&quot;diverging&quot;].sum().item()</pre><p>This returns 0 🚀</p><p><strong><em>Model summary</em></strong></p><p>On top of validating the model haven’t generated any divergences, it’s good practice checking that the traces converged and that the parameters’ distribution follow nice curves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBccm8V89RZ64Mm_D-Q98g.png" /></figure><p>Here, we start exploring one of the main assets of Bayesian models. They provide a range of confidence about the parameters that we are trying to estimate. The more the standard deviation, the less confident the model is.</p><p><strong><em>Posterior Predictive Sample</em></strong></p><p>Next, let’s see how the model predictions have performed over the train set. Below, we compare the poseterior predictive likelihood against the true target (in the original scale).</p><pre>posterior_predictive_likelihood = az.extract(<br>    data=base_model_posterior_predictive,<br>    group=&quot;posterior_predictive&quot;,<br>    var_names=&quot;likelihood&quot;,<br>)<br><br>posterior_predictive_likelihood_inv = target_scaler.inverse_transform(<br>    X=posterior_predictive_likelihood<br>)<br><br>fig, ax = plt.subplots(figsize=(12, 8))<br><br>for i, p in enumerate(percs[::-1]):<br>    upper = np.percentile(posterior_predictive_likelihood_inv, p, axis=1)<br>    lower = np.percentile(posterior_predictive_likelihood_inv, 100 - p, axis=1)<br>    color_val = colors[i]<br>    ax.fill_between(<br>        x=dates,<br>        y1=upper,<br>        y2=lower,<br>        color=cmap(color_val),<br>        alpha=0.1,<br>    )<br><br>sns.lineplot(<br>    x=dates,<br>    y=posterior_predictive_likelihood_inv.mean(axis=1),<br>    color=&quot;C2&quot;,<br>    label=&quot;posterior predictive mean&quot;,<br>    ax=ax,<br>)<br>sns.lineplot(<br>    x=dates,<br>    y=target_train.flatten(),<br>    color=&quot;black&quot;,<br>    label=&quot;target (original scale)&quot;,<br>    ax=ax,<br>)<br>ax.legend(loc=&quot;upper left&quot;)<br>ax.set(title=&quot;Base Model - Posterior Predictive Samples&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ni3syBKxSKFeMoF0k-8tA.png" /><figcaption>Image from the author</figcaption></figure><p>Overall, our model seems quite ok so far 🚀</p><p>Yet, while our model shows excellent performance on the training data, the true test of any statistical model lies in its ability to generalize to unseen data. In-sample fit can be misleading due to potential overfitting, even in Bayesian models where priors provide regularization. Out-of-sample validation is especially important in marketing mix modeling, where the ultimate goal is to make forward-looking budget allocation decisions. Let’s evaluate how our model performs on the test set we reserved earlier.</p><p><strong><em>Out-of-sample predictions</em></strong></p><p>Like any traditional ML model, we want to test our predictions on unseen data. Good news, we have kept the last 50 observations for testing!</p><p>PyMC provides a lot of flexibility to re-use the model’s trace and extend it with new data:</p><pre># First, update your model with the test data<br>with model:<br>    # Now update the data<br>    pm.set_data(new_data={&quot;data&quot;: z_test_scaled,<br>                          &quot;t&quot;: t_test,<br>                          &quot;fourier_features&quot;: fourier_features[-test_size:None],<br>                          &quot;sales&quot;: target_test_scaled,<br>                          }, coords={&quot;date&quot;: dataset.date.values[-test_size:None]})<br><br><br><br>    base_model_trace.extend(<br>    # Generate posterior predictive samples<br>    other = pm.sample_posterior_predictive(<br>        trace=base_model_trace,<br>        predictions=True,<br>        var_names=[&quot;likelihood&quot;],<br>        random_seed=rng,<br>        idata_kwargs={&quot;coords&quot;: {&quot;date&quot;: dataset.date.values[-test_size:None]}}<br>    ),<br>    )</pre><pre>def scaled_to_original(y, pos):<br>    &quot;&quot;&quot;Convert scaled y-values to original scale for display&quot;&quot;&quot;<br>    # Reshape y to match scaler expected format<br>    y_reshaped = np.array([[y]])<br>    # Convert to original scale<br>    y_original = target_scaler.inverse_transform(y_reshaped)[0, 0]<br>    return f&#39;{y_original:.0f}&#39;  # Format as needed<br><br># Set a matplotlib style<br>plt.style.use(&#39;seaborn-darkgrid&#39;)<br>plt.rcParams[&#39;axes.grid&#39;] = False<br><br><br># Create the plot with exactly the same layout<br>fig, ax = plt.subplots(figsize=(15, 7))<br><br># Plot training data predictions and HDI<br>az.plot_hdi(<br>    x=dates,<br>    y=base_model_posterior_predictive[&quot;posterior_predictive&quot;][&quot;likelihood&quot;],<br>    hdi_prob=0.95,<br>    color=&quot;C0&quot;,<br>    fill_kwargs={&quot;alpha&quot;: 0.4, &quot;label&quot;: r&quot;train HDI $95\%$&quot;},<br>    smooth=False,<br>    ax=ax,<br>)<br>az.plot_hdi(<br>    x=dates,<br>    y=base_model_posterior_predictive[&quot;posterior_predictive&quot;][&quot;likelihood&quot;],<br>    hdi_prob=0.5,<br>    color=&quot;C0&quot;,<br>    fill_kwargs={&quot;alpha&quot;: 0.7, &quot;label&quot;: r&quot;train HDI $50\%$&quot;},<br>    smooth=False,<br>    ax=ax,<br>)<br>sns.lineplot(<br>    x=dates,<br>    y=target_scaled,<br>    marker=&quot;o&quot;,<br>    color=&quot;black&quot;,<br>    alpha=0.8,<br>    markersize=4,<br>    markeredgecolor=&quot;black&quot;,<br>    label=&quot;sales (train)&quot;,<br>    ax=ax,<br>)<br><br># Extract test predictions from base_model_trace<br>test_dates = dataset.date.values[-test_size:]<br><br># Check which groups are available in base_model_trace<br>available_groups = list(base_model_trace.groups())<br>print(f&quot;Available groups in base_model_trace: {available_groups}&quot;)<br><br>if &#39;predictions&#39; in available_groups:<br>    # Use posterior_predictive from base_model_trace if available<br>    az.plot_hdi(<br>        x=test_dates,<br>        y=base_model_trace[&quot;predictions&quot;][&quot;likelihood&quot;],<br>        hdi_prob=0.95,<br>        color=&quot;C2&quot;,<br>        fill_kwargs={&quot;alpha&quot;: 0.4, &quot;label&quot;: r&quot;test HDI $95\%$&quot;},<br>        smooth=False,<br>        ax=ax,<br>    )<br>    az.plot_hdi(<br>        x=test_dates,<br>        y=base_model_trace[&quot;predictions&quot;][&quot;likelihood&quot;],<br>        hdi_prob=0.5,<br>        color=&quot;C2&quot;,<br>        fill_kwargs={&quot;alpha&quot;: 0.7, &quot;label&quot;: r&quot;test HDI $50\%$&quot;},<br>        smooth=False,<br>        ax=ax,<br>    )<br><br>    # Calculate test prediction mean for metrics<br>    test_pred_mean = base_model_trace[&quot;predictions&quot;][&quot;likelihood&quot;].mean(dim=[&quot;chain&quot;, &quot;draw&quot;]).values<br>else:<br>    print(&quot;Warning: &#39;predictions&#39; not found in base_model_trace.&quot;)<br>    test_pred_mean = None<br><br>sns.lineplot(<br>    x=test_dates,<br>    y=target_test_scaled,<br>    marker=&quot;o&quot;,<br>    color=&quot;C1&quot;,<br>    alpha=0.8,<br>    markersize=4,<br>    markeredgecolor=&quot;C1&quot;,<br>    label=&quot;sales (test)&quot;,<br>    ax=ax,<br>)<br><br># Add a vertical line at the train/test split<br>train_test_date = dataset.date.values[-test_size]<br>ax.axvline(x=train_test_date, color=&quot;gray&quot;, linestyle=&quot;--&quot;, label=&quot;train/test split&quot;)<br><br># Apply the formatter to show original scale on y-axis<br>ax.yaxis.set_major_formatter(FuncFormatter(scaled_to_original))<br><br>ax.legend(loc=&quot;upper center&quot;, bbox_to_anchor=(0.5, -0.15), ncol=7)<br>ax.set(title=&quot;Base Model - Out of Sample Predictions&quot;)<br>ax.set_ylabel(&quot;Sales&quot;)<br><br>plt.tight_layout()<br>plt.show()<br><br># Display metrics if test predictions are available<br>if test_pred_mean is not None and target_test_scaled is not None:<br>    # Calculate metrics in scaled space<br>    from sklearn.metrics import mean_absolute_error, mean_squared_error<br>    import numpy as np<br><br>    mae_scaled = mean_absolute_error(target_test_scaled, test_pred_mean)<br>    rmse_scaled = np.sqrt(mean_squared_error(target_test_scaled, test_pred_mean))<br><br>    # Calculate metrics in original scale<br>    test_pred_mean_orig = target_scaler.inverse_transform(test_pred_mean.reshape(-1, 1)).flatten()<br>    target_test_orig = target_scaler.inverse_transform(target_test_scaled.reshape(-1, 1)).flatten()<br><br>    mae_orig = mean_absolute_error(target_test_orig, test_pred_mean_orig)<br>    rmse_orig = np.sqrt(mean_squared_error(target_test_orig, test_pred_mean_orig))<br>    mape = np.mean(np.abs((target_test_orig - test_pred_mean_orig) / target_test_orig)) * 100<br><br>    print(f&quot;Test Metrics:&quot;)<br>    print(f&quot;Scaled Space - MAE: {mae_scaled:.4f}, RMSE: {rmse_scaled:.4f}&quot;)<br>    print(f&quot;Original Space - MAE: {mae_orig:.2f}, RMSE: {rmse_orig:.2f}, MAPE: {mape:.2f}%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5-FkJD4x-0rw5Gsu7ZHSw.png" /></figure><p><strong>Test Metrics: </strong>MAE: 6.96, RMSE: 10.40, MAPE: 5.29%</p><p>Hmm… 🤔 Our predictions on the test set seems quite accurate except the period right after the train/test split where the model underestimates the true values. Did we forget anything? Maybe yes 😉</p><p><strong><em>Out-of-sample predictions with carryover effects</em></strong></p><p>We can’t simply handle train and test sets as totally seperated as the first observations of test set contains media carryover from the last observations of train set. Consequently, when building our test set, we must concatenate the last observations of train set with the original test set. Thus, when we generate our posterior predictive samples from this concatenation, we are sure the test set index contains the right carryover effect of train set.</p><pre>l_max = 8  # This should match your adstock&#39;s l_max parameter<br><br># Combine last l_max training observations with test data<br>z_combined = np.vstack([z_scaled[-l_max:], z_test_scaled])<br><br># Combine the dates as well<br>combined_dates = np.concatenate([dataset.date.values[-l_max-test_size:-test_size],<br>                               dataset.date.values[-test_size:]])<br><br><br># Combined t values<br>t_combined = np.concatenate([t_train[-l_max:], t_test])<br><br># Combined fourier features<br>fourier_combined = np.vstack([fourier_features[-l_max-test_size:-test_size],<br>                            fourier_features[-test_size:]])<br><br>if target_test_scaled is not None:<br>    target_combined = np.concatenate([target_scaled[-l_max:], target_test_scaled])<br>else:<br>    target_combined = np.concatenate([target_scaled[-l_max:],<br>                                     np.full(test_size, np.nan)])<br><br># Update model with the combined data<br>with model:<br>    pm.set_data(<br>        new_data={<br>            &quot;data&quot;: z_combined,<br>            &quot;t&quot;: t_combined,<br>           #  &quot;index_scaled_data&quot;: combined_index_scaled,<br>            &quot;fourier_features&quot;: fourier_combined<br>        },<br>        coords={&quot;date&quot;: combined_dates}<br>    )<br><br>    # Generate posterior predictive samples<br>    combined_posterior_predictive = pm.sample_posterior_predictive(<br>        trace=base_model_trace,<br>        var_names=[&quot;likelihood&quot;],<br>        random_seed=rng,<br>        predictions=True,<br>        idata_kwargs={&quot;coords&quot;: {&quot;date&quot;: combined_dates}}<br>    )</pre><pre># Create the plot with exactly the same layout<br>fig, ax = plt.subplots(figsize=(15, 7))<br><br># Plot training data predictions and HDI<br>az.plot_hdi(<br>    x=dates,<br>    y=base_model_posterior_predictive[&quot;posterior_predictive&quot;][&quot;likelihood&quot;],<br>    hdi_prob=0.95,<br>    color=&quot;C0&quot;,<br>    fill_kwargs={&quot;alpha&quot;: 0.4, &quot;label&quot;: r&quot;train HDI $95\%$&quot;},<br>    smooth=False,<br>    ax=ax,<br>)<br>az.plot_hdi(<br>    x=dates,<br>    y=base_model_posterior_predictive[&quot;posterior_predictive&quot;][&quot;likelihood&quot;],<br>    hdi_prob=0.5,<br>    color=&quot;C0&quot;,<br>    fill_kwargs={&quot;alpha&quot;: 0.7, &quot;label&quot;: r&quot;train HDI $50\%$&quot;},<br>    smooth=False,<br>    ax=ax,<br>)<br>sns.lineplot(<br>    x=dates,<br>    y=target_scaled,<br>    marker=&quot;o&quot;,<br>    color=&quot;black&quot;,<br>    alpha=0.8,<br>    markersize=4,<br>    markeredgecolor=&quot;black&quot;,<br>    label=&quot;sales (train)&quot;,<br>    ax=ax,<br>)<br><br># Extract only the test part (skip carryover observations)<br>test_dates = dataset.date.values[-test_size:]<br>test_predictions = combined_posterior_predictive[&quot;predictions&quot;][&quot;likelihood&quot;].isel(date=slice(l_max, None))<br><br>az.plot_hdi(<br>    x=test_dates,<br>    y=test_predictions,<br>    hdi_prob=0.95,<br>    color=&quot;C2&quot;,<br>    fill_kwargs={&quot;alpha&quot;: 0.4, &quot;label&quot;: r&quot;test HDI $95\%$&quot;},<br>    smooth=False,<br>    ax=ax,<br>)<br>az.plot_hdi(<br>    x=test_dates,<br>    y=test_predictions,<br>    hdi_prob=0.5,<br>    color=&quot;C2&quot;,<br>    fill_kwargs={&quot;alpha&quot;: 0.7, &quot;label&quot;: r&quot;test HDI $50\%$&quot;},<br>    smooth=False,<br>    ax=ax,<br>)<br>sns.lineplot(<br>    x=test_dates,<br>    y=target_test_scaled,<br>    marker=&quot;o&quot;,<br>    color=&quot;C1&quot;,<br>    alpha=0.8,<br>    markersize=4,<br>    markeredgecolor=&quot;C1&quot;,<br>    label=&quot;sales (test)&quot;,<br>    ax=ax,<br>)<br><br># Optional: Add a vertical line at the train/test split<br>train_test_date = dataset.date.values[-test_size]<br>ax.axvline(x=train_test_date, color=&quot;gray&quot;, linestyle=&quot;--&quot;, label=&quot;train/test split&quot;)<br><br># Optional: To show carryover period explicitly<br>carryover_dates = dataset.date.values[-l_max-test_size:-test_size]<br>ax.axvspan(carryover_dates[0], carryover_dates[-1], alpha=0.2, color=&#39;gray&#39;, label=&#39;carryover period&#39;)<br><br># Apply the formatter to show original scale on y-axis<br>ax.yaxis.set_major_formatter(FuncFormatter(scaled_to_original))<br><br>ax.legend(loc=&quot;center left&quot;, bbox_to_anchor=(1, 0.5))<br>ax.set_title(&quot;Base Model - Out of Sample Predictions with Marketing Carryover&quot;)<br><br>plt.tight_layout()<br>plt.show()<br><br># Display metrics if you have test data<br>if target_test_scaled is not None:<br>    # Calculate predictions mean<br>    test_pred_mean = test_predictions.mean(dim=[&quot;chain&quot;, &quot;draw&quot;]).values<br><br>    # Calculate metrics in scaled space<br>    from sklearn.metrics import mean_absolute_error, mean_squared_error<br>    import numpy as np<br><br>    mae_scaled = mean_absolute_error(target_test_scaled, test_pred_mean)<br>    rmse_scaled = np.sqrt(mean_squared_error(target_test_scaled, test_pred_mean))<br><br>    # Calculate metrics in original scale<br>    test_pred_mean_orig = target_scaler.inverse_transform(test_pred_mean.reshape(-1, 1)).flatten()<br>    target_test_orig = target_scaler.inverse_transform(target_test_scaled.reshape(-1, 1)).flatten()<br><br>    mae_orig = mean_absolute_error(target_test_orig, test_pred_mean_orig)<br>    rmse_orig = np.sqrt(mean_squared_error(target_test_orig, test_pred_mean_orig))<br>    mape = np.mean(np.abs((target_test_orig - test_pred_mean_orig) / target_test_orig)) * 100<br><br>    print(f&quot;Test Metrics (with carryover effects):&quot;)<br>    print(f&quot;Scaled Space - MAE: {mae_scaled:.4f}, RMSE: {rmse_scaled:.4f}&quot;)<br>    print(f&quot;Original Space - MAE: {mae_orig:.2f}, RMSE: {rmse_orig:.2f}, MAPE: {mape:.2f}%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9Ykui_7GiJd-uNRUaXomQ.png" /><figcaption>Image from the author</figcaption></figure><p><strong>Test Metrics: </strong>MAE: 5.02, RMSE: 6.66, MAPE: 4.04%</p><p>This is much better 🚀</p><p>It also outperformes our best model from my previous article yielded a RMSE of 7.83 and a MAPE of 5.03%!</p><p><strong><em>Model parameter recovery</em></strong></p><p>As the data come from a synthetic dataset, let’s see how our model parameters compare with true values.</p><p><em>PS: In business contexts, we often don’t have a ground truth to compare with but rely on domain experts to see if the posterior estimates are sensible.</em></p><pre># Initialize single scalers for all countries<br>channel_scaler = MaxAbsScaler()<br>target_scaler = MaxAbsScaler()<br><br># Fit scalers on all data<br>all_spends = dataset.spends.values.reshape(-1, len(channels))  # Flatten across countries and dates<br>all_targets = dataset.target.values.reshape(-1, 1)  # Flatten across countries and dates<br><br>channel_scaler.fit(all_spends)<br>target_scaler.fit(all_targets)<br><br># Now recover parameters using these global scalers<br>recovered_params = {}<br>for country in countries:<br>    # Scale posteriors using the global scalers<br>    alphas = base_model_trace.posterior[&quot;alpha&quot;]<br>    lams = base_model_trace.posterior[&quot;lam&quot;] / channel_scaler.scale_<br>    betas = (base_model_trace.posterior[&quot;b_z&quot;] *<br>             target_scaler.scale_) / 10  # Divide by amplitude<br><br>    recovered_params[country] = {<br>        &#39;alphas&#39;: alphas,<br>        &#39;lambdas&#39;: lams,<br>        &#39;effects&#39;: betas<br>    }<br><br># Plot function remains the same<br>def plot_param_comparison(param_name, recovered_params, country_params, countries, channels):<br>    fig, axes = plt.subplots(len(countries), 1, figsize=(10, 4*len(countries)))<br><br>    for i, country in enumerate(countries):<br>        ax = axes[i] if len(countries) &gt; 1 else axes<br>        data = recovered_params[country][param_name]<br>        param_data = []<br>        param_names = []<br><br>        for j, channel in enumerate(channels):<br>            param_data.append(data[:,:,j])<br>            param_names.append(f&quot;{param_name}[C{j+1}]&quot;)<br>            true_val = country_params[country][param_name][channel]<br>            ax.axvline(true_val, color=f&quot;C{j}&quot;, linestyle=&quot;--&quot;, linewidth=2,<br>                      label=f&quot;β_{j+1} (true)&quot;)<br><br>        combined_data = xr.concat(param_data, dim=&#39;channel&#39;)<br>        combined_data = combined_data.assign_coords(channel=param_names)<br><br>        az.plot_forest(data=combined_data, combined=True, hdi_prob=0.94, ax=ax)<br>        ax.legend(loc=&quot;upper left&quot;)<br>        ax.set_title(label=f&quot;{country} - {param_name} Parameter ($94\\%$ HDI)&quot;,<br>                    fontsize=18, fontweight=&quot;bold&quot;)<br><br>    plt.tight_layout()<br><br># Plot each parameter<br>for param in [&#39;alphas&#39;, &#39;lambdas&#39;, &#39;effects&#39;]:<br>    plot_param_comparison(param, recovered_params, country_params, countries, channels)</pre><p>There is some complexity to handle related to the fact our parameter’s posteriors are in a scaled space. Let’s go through the logic of each transformation:</p><ul><li>alpha (the decay parameter for adstock) is dimensionless, so it does <strong>not</strong> need <em>unscaling</em>.</li><li>lam (the saturation parameter) was fit to <em>scaled</em> media. Dividing by channel_scaler.scale_ re‐expresses it in terms of the <strong>original</strong> media range (because the logistic saturation was applied to scaled data).</li><li>b_z is the slope linking <em>scaled </em>saturated media to <em>scaled</em> target. Multiplying by target_scaler.scale_ “undoes” the target scaling, so now it’s in “original output units per scaled input.” We need to divide by 10 then because our raw target was multiplied by 10 in the data generation process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVuHgVCi2Rfp7sC4hJDzOA.png" /><figcaption>Image from the author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtR_WCW3Pt1l4l33gxefJQ.png" /><figcaption>Image from the author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVV7dJDPtOukHTTw7ItDrw.png" /><figcaption>Image from the author</figcaption></figure><p>We observe our model performed quite well at capturing the true channel- related model parameter .</p><p>Instead of providing a single estimated value for the model parameters (as traditional ML/frequentist model do), our Bayesian model provides a interval of probabilities (median, 50% and 94% HDI areas) telling you how confident it is about its estimate. This is of a great help when you need to make decision!</p><p>We can also do the same with other components:</p><pre># compute HDI for all the model parameters<br>model_hdi = az.hdi(ary=base_model_trace)<br><br>fig, ax = plt.subplots(figsize=(10,7))<br><br>for i, var_effect in enumerate([&quot;trend&quot;, &quot;seasonality&quot;]):<br>    ax.fill_between(<br>        x=dates,<br>        y1=model_hdi[var_effect][:, 0],<br>        y2=model_hdi[var_effect][:, 1],<br>        color=f&quot;C{i}&quot;,<br>        alpha=0.3,<br>        label=f&quot;$94\%$ HDI ({var_effect})&quot;,<br>    )<br>    sns.lineplot(<br>        x=dates,<br>        y=base_model_trace.posterior[var_effect]<br>        .stack(sample=(&quot;chain&quot;, &quot;draw&quot;))<br>        .mean(axis=1),<br>        color=f&quot;C{i}&quot;,<br>    )<br><br>true_seasonality = target_scaler.transform(<br>    dataset.seasonality.sel(country=country)[:-test_size].values.reshape(-1, 1)*10<br>).flatten()<br><br># Plot the true seasonality<br>sns.lineplot(<br>    x=dates,<br>    y=true_seasonality,  # Now properly flattened to 1D<br>    color=&quot;orange&quot;,<br>    alpha=0.7,<br>    linestyle=&quot;--&quot;,<br>    label=&quot;true seasonality&quot;,<br>    ax=ax<br>)<br><br><br>true_trend_and_intercept = target_scaler.transform(<br>    dataset.trend.sel(country=country)[:-test_size].values.reshape(-1, 1)*10<br>).flatten() + target_scaler.transform(<br>    dataset.base_sales.sel(country=country)[:-test_size].values.reshape(-1, 1)*10<br>).flatten()<br><br># Plot the true trend<br>sns.lineplot(<br>    x=dates,<br>    y=true_trend_and_intercept,  # Now properly flattened to 1D<br>    color=&quot;blue&quot;,<br>    alpha=0.7,<br>    linestyle=&quot;--&quot;,<br>    label=&quot;true trend&quot;,<br>    ax=ax<br>)<br><br>sns.lineplot(<br>    x=dates, y=target_scaled, color=&quot;black&quot;, alpha=1.0, label=&quot;target (scaled)&quot;, ax=ax<br>)<br><br>ax.legend(loc=&quot;upper center&quot;, bbox_to_anchor=(0.5, -0.15), ncol=4)<br><br><br><br>ax.set(<br>    title=&quot;Base Model Components&quot;,<br>    ylabel=&quot;target (scaled)&quot;,<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJMh6lHb4Ul4KlSZZjdYYw.png" /><figcaption>Image from the author</figcaption></figure><p><strong><em>Channel contributions</em></strong></p><pre>z_effect_posterior_samples = []<br><br># Loop through each channel<br>for channel_idx in range(base_model_trace.posterior[&quot;z_effect&quot;].sizes[&quot;channel&quot;]):<br>    # Extract data for this channel<br>    channel_data = base_model_trace.posterior[&quot;z_effect&quot;].isel(channel=channel_idx)<br><br>    # Apply transformation for this channel<br>    channel_samples = xr.apply_ufunc(<br>        lambda x: target_scaler.inverse_transform(X=x.reshape(1, -1)),<br>        channel_data,<br>        input_core_dims=[[&quot;date&quot;]],<br>        output_core_dims=[[&quot;date&quot;]],<br>        vectorize=True,<br>    )<br><br>    z_effect_posterior_samples.append(channel_samples)<br><br># Combine the results back into a single DataArray with channel dimension<br>z_effect_posterior_samples = xr.concat(z_effect_posterior_samples, dim=&quot;channel&quot;)<br><br># Calculate HDI as before<br>z_effect_hdi = az.hdi(ary=z_effect_posterior_samples)[&quot;z_effect&quot;]<br><br># Plot for each channel<br>fig, axes = plt.subplots(nrows=len(dataset.channel), figsize=(10, 8*len(dataset.channel)))<br>if len(dataset.channel) == 1:<br>    axes = [axes]  # Make it iterable if there&#39;s only one subplot<br><br>for i, (ax, channel) in enumerate(zip(axes, dataset.channel.values)):<br>    ax.fill_between(<br>        x=dataset.date[:-test_size],<br>        y1=z_effect_hdi.sel(channel=channel)[:, 0],<br>        y2=z_effect_hdi.sel(channel=channel)[:, 1],<br>        color=f&quot;C{i}&quot;,<br>        alpha=0.5,<br>        label=f&quot;{channel} z_effect 94% HDI&quot;,<br>    )<br>    ax.axhline(<br>        y=z_effect_posterior_samples.sel(channel=channel).mean(),<br>        color=f&quot;C{i}&quot;,<br>        linestyle=&quot;--&quot;,<br>        label=f&quot;{channel} posterior mean {z_effect_posterior_samples.sel(channel=channel).mean().values: 0.3f}&quot;,<br>    )<br><br>    # Plot the original data for this channel<br>    sns.lineplot(<br>        x=&quot;date&quot;,<br>        y=&quot;media_response&quot;,<br>        color=f&quot;C{i+3}&quot;,<br>        data=(dataset.media_response.sel(channel=channel)*10).to_dataframe().reset_index()[:-test_size],<br>        label=f&quot;{channel} true z_effect&quot;,<br>        ax=ax<br>    )<br><br>    ax.legend(loc=&quot;upper center&quot;, bbox_to_anchor=(0.5, -0.15), ncol=7)<br>    ax.set(title=f&quot;Media Cost Effect on Sales Estimation - {channel} Channel&quot;)<br><br>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zchmG1a9BvdwyWA7agERpQ.png" /></figure><p>True channel media responses lies right in the middle of the model 94% HDI areas — that is our model predictions are accurate (we could have assumed the same as we saw above that our channel model parameters were predicted correctly).</p><p>Uuuhh — we went through a lot of stuff. Let’s step back a minute and review the main differences with traditional ML models we explored in the first article:</p><ul><li>Bayesian models used in MMM are based on a multivariate linear regression — this means <strong><em>they are highly intepretable.</em></strong></li><li>Our Bayesian models (using PyMC) better performed than our best linear regression from our previous article. I guess that if I had increased the amount of Optuna iterations, I would have landed to more or less similar results. However, PyMC goes much faster!</li><li>Bayesian models doesn’t give you a single prediction. Instead, it gives you a range of probabilities which tell you how much you can be confident about this prediction.</li></ul><h3>A more complex case with diminishing returns</h3><p>The Bayesian model we’ve explored so far effectively captures the core dynamics of marketing effects, including adstock decay and saturation, while providing valuable uncertainty quantification through posterior distributions. However, real-world marketing scenarios often exhibit more complex patterns than our current model can represent. In particular, many channels show diminishing marginal returns over time due to market saturation, competitive responses, or audience burnout. This effect goes beyond simple saturation of individual marketing activities and requires more sophisticated modelling approaches. In the following section, we’ll extend our framework using Gaussian Processes to capture these complex non-linear patterns that traditional models struggle to represent.</p><h4>The concepts behind GPs &amp; HSGP</h4><p>In my previous article, we studied how diminishing returns applied to the saturated media response could make the data challenge more complex for our models. In this section, we will see how gaussian processes can help in capturing complex non linear patterns.</p><p><strong><em>Gaussian Processes</em></strong></p><p>A <strong>Gaussian Process (GP)</strong> is essentially a statistical framework that models functions. Instead of saying “my function looks like y = ax² + bx + c” or some other specific form, a GP says: “I assume my function f(x) is drawn from a ‘distribution over functions,’ where any set of points has a joint (multivariate) Normal distribution.”</p><p>What does this mean in practice? Imagine drawing many possible smooth curves that could fit your data — a GP represents the universe of these possibilities. When you observe data points, the GP narrows down which curves are most likely. This lets you <strong>flexibly fit curves</strong> without committing to a specific polynomial or shape beforehand. The GP adapts to your data, naturally capturing complex patterns while providing uncertainty estimates.</p><p>The catch? Standard GPs require inverting an N×N covariance matrix (where N is your number of data points). This becomes computationally expensive when N gets large — scaling as O(N³) in time and O(N²) in memory — making traditional GPs impractical for large datasets.</p><p><strong>HSGP</strong> (Hilbert Space Gaussian Process) offers an elegant solution to this computational bottleneck. Rather than working directly with the massive covariance matrices, HSGP approximates the GP using a clever mathematical approach that projects the process onto a finite set of carefully chosen basis functions in a Hilbert space.</p><p><strong><em>HSGP parameters</em></strong></p><ul><li>ls (lengthscale): This is the most crucial parameter, representing the distance in input space over which function values remain correlated. Smaller lengthscales allow for more rapid changes in the function (capturing local patterns), while larger lengthscales enforce smoother, more global patterns.</li><li>m and c: These parameters control the approximation quality. Parameter m determines the number of basis functions, with higher values providing better approximation at the cost of computation. Parameter c affects the spacing of basis functions in frequency space. Together, they control the trade-off between computational efficiency and approximation accuracy.</li><li>ExpQuad, Matern52 or Matern32 : the covariance kernels which make smoothness/sharpness’ functions curves.</li></ul><p>I really recommend <a href="https://www.pymc.io/projects/examples/en/latest/gaussian_processes/HSGP-Basic.html#example-1-basic-hsgp-usage">PyMC’s post</a> introducing HSGP to better understand the main concepts there. They refer to the heuristics defined in <a href="https://arxiv.org/abs/2004.11408">Ruitort-Mayol et. al.</a> in order to select m and c . This is what I used in approx_hsgp_hyperparam function</p><h4>Let’s code!</h4><p>This time, I’ll go much faster on the code sections as I re-used the same sections as the model used earlier. The full code is available in my notebook here.</p><p><strong><em>Scaling the data</em></strong></p><p>When using HSGP for out-of-sample predictions, consistent data preprocessing is crucial. Otherwise, your model can produce abrupt “jumps” at the boundary between training and out-of-sample data, because it sees them on different scales. A straightforward fix is to apply a standard scaler <strong>across your entire dataset</strong> — including the portion used for out-of-sample predictions. (The <a href="https://www.pymc-marketing.io/">PyMC-Marketing</a> team recently proposed a more sophisticated softmax-based approach, but for simplicity here, we’ll stick to the classical standard scaler.)</p><pre>index_scaler = StandardScaler()<br><br>full_range = np.arange(0, len(dataset.date)).reshape(-1, 1)<br>full_index_scaled = index_scaler.fit_transform(full_range)<br><br># Split into train and test afterward<br>index_train_scaled = full_index_scaled[:len(dataset.date)-test_size]<br>index_test_scaled = full_index_scaled[len(dataset.date)-test_size:]<br></pre><p><strong><em>HSGP parameters</em></strong></p><p>As mentioned above, I used the following heuristics to build approx_hsgp_hyperparam funtion</p><pre># The x values the HSGP will be evaluated over<br><br>Xs = x - x_center<br>S = np.max(np.abs(Xs), axis=0)<br><br>if cov_func.lower() == &quot;expquad&quot;:<br>    a1, a2 = 3.2, 1.75<br><br>elif cov_func.lower() == &quot;matern52&quot;:<br>    a1, a2 = 4.1, 2.65<br><br>elif cov_func.lower() == &quot;matern32&quot;:<br>    a1, a2 = 4.5, 3.42<br><br>else: <br>    None<br><br>c = max(a1 * (lengthscale_max / S), 1.2)<br>m = int(a2 * c / (lengthscale_min / S))</pre><p>About the lengthscale to use, we assume we got some information from the marketing team:</p><blockquote>We are aware one key competitor entered our market and has been constantly increasing its marketing budget over time.</blockquote><p>Consequently, we imagine between 1 and 2 lengthscales over the scaled time space which is centered around 0.</p><p>This translates into:</p><pre>approx_hsgp_hyperparams(<br>        full_index_scaled,<br>        0,<br>        lengthscale_range=[max(full_index_scaled), max(full_index_scaled)*2],<br>        cov_func=&quot;expquad&quot;)<br><br># (11, array([6.4])) -&gt; m=11 and c=6.4</pre><p>Great! Now, we have m and c parameters.</p><p>Let’s move on to the model setup:</p><pre>n_order = 2<br>dates = dataset.date.values[None:-test_size]<br>coords = {&quot;channel&quot;: channels, &quot;fourier_mode&quot;: np.arange(2 * n_order)}<br><br><br>with pm.Model(coords=coords) as tvp_model:<br>    # --- coords --- #<br>    tvp_model.add_coord(name=&quot;date&quot;, values=dates, mutable=True)<br><br>    # --- data containers --- #<br>    index_scaled_data = pm.Data(<br>        name=&quot;index_scaled_data&quot;,<br>        value=index_train_scaled,<br>    )<br><br>    data = pm.Data(<br>       &quot;data&quot;,<br>       z_scaled,<br>       dims=(&quot;date&quot;, &quot;channel&quot;),<br>    )<br><br>    fourier_feature_data = pm.Data(<br>        &quot;fourier_features&quot;,<br>        fourier_features[None:-test_size],<br>        dims=(&quot;date&quot;, &quot;fourier_mode&quot;)<br>    )<br><br>    t_data = pm.Data(<br>        &quot;t&quot;,<br>        t_train,<br>        dims=&quot;date&quot;<br>    )<br><br>    sales_data = pm.Data(<br>        &quot;sales&quot;,<br>        target_scaled,<br>        dims=&quot;date&quot;<br>    )<br><br>    # --- priors --- #<br>    ## intercept<br>    a = pm.HalfNormal(name=&quot;a&quot;, sigma=0.1)<br>    ## trend<br>    b_trend = pm.HalfNormal(name=&quot;b_trend&quot;, sigma=2)<br>    ## adstock effect<br>    alpha = pm.Beta(name=&quot;alpha&quot;, alpha=2, beta=2, dims=&quot;channel&quot;)<br>    ## saturation effect<br>    lam = pm.Gamma(name=&quot;lam&quot;, alpha=2, beta=1, dims=&quot;channel&quot;)<br>    ## seasonality<br>    b_fourier = pm.Laplace(name=&quot;b_fourier&quot;, mu=0, b=0.2, dims=&quot;fourier_mode&quot;)<br>    ## regressor<br>    b_z = pm.HalfNormal(name=&quot;b_z&quot;, sigma=np.array(channel_share_array).reshape(-1,1).flatten(), dims=&quot;channel&quot;)<br>    ## standard deviation of the normal likelihood<br>    sigma = pm.HalfNormal(name=&quot;sigma&quot;, sigma=0.5)<br>    ## amplitude of the gaussian process<br>    eta = pm.Exponential(name=&quot;Exponential&quot;, lam=1)<br>    # degrees of freedom of the t distribution<br>    nu = pm.Gamma(name=&quot;nu&quot;, alpha=25, beta=2)<br>    <br>    ## lengthscale<br>    ls_trend_params = pm.find_constrained_prior(<br>        distribution=pm.InverseGamma,<br>        lower=float(max(full_index_scaled)),<br>        upper=float(max(full_index_scaled)*2),<br>        init_guess={&quot;alpha&quot;: 1.690e+01, &quot;beta&quot;: 4.509e+01},<br>        mass=0.85<br><br>    )<br>    ls_trend = pm.InverseGamma(name=&quot;ls_trend&quot;, **ls_trend_params)<br><br>    # --- model parametrization --- #<br>    trend = pm.Deterministic(name=&quot;trend&quot;, var=a + b_trend * t_data, dims=&quot;date&quot;)<br>    seasonality = pm.Deterministic(<br>        name=&quot;seasonality&quot;, var=pm.math.dot(fourier_feature_data, b_fourier), dims=&quot;date&quot;<br>    )<br><br>    # Use ExpQuad for smoother decay transitions<br>    cov_trend = eta**2 * pm.gp.cov.ExpQuad(input_dim=1, ls=ls_trend)<br><br>    # Use m and c from Ruitort-Mayol&#39;s heuristics<br>    gp_trend = pm.gp.HSGP(m=[11], c=6.4, cov_func=cov_trend)<br><br>    # Use prior_linearized instead of prior<br>    phi_trend, sqrt_psd_trend = gp_trend.prior_linearized(index_scaled_data)<br>    trend_coeffs = pm.Normal(&quot;trend_coeffs&quot;, size=11)<br>    lattent_param = pm.Deterministic(&quot;lattent_param&quot;, phi_trend @ (trend_coeffs * sqrt_psd_trend))<br><br>    z_adstock = pm.Deterministic(<br>        name=&quot;z_adstock&quot;, var=geometric_adstock(x=data, alpha=alpha, l_max=8, normalize=True), dims=(&quot;date&quot;,&quot;channel&quot;)<br>    )<br><br>    z_adstock_saturated = pm.Deterministic(<br>        name=&quot;z_adstock_saturated&quot;,<br>        var=logistic_saturation(x=z_adstock, lam=lam),<br>        dims=(&quot;date&quot;,&quot;channel&quot;),<br>    )<br><br>    z_effect = pm.Deterministic(<br>        name=&quot;z_effect&quot;, var=b_z * z_adstock_saturated, dims=(&quot;date&quot;,&quot;channel&quot;)<br>    )<br><br>    z_effect_post_diminishing = pm.Deterministic(<br>        name=&quot;z_effect_post_diminishing&quot;, var=lattent_param[:, None] * z_effect, dims=(&quot;date&quot;, &quot;channel&quot;)<br>    )<br><br>    mu = pm.Deterministic(name=&quot;mu&quot;, var=trend + seasonality + z_effect_post_diminishing.sum(axis=1), dims=&quot;date&quot;)<br><br>    # --- likelihood ---<br>    y = pm.StudentT(name=&quot;likelihood&quot;, nu=nu, mu=mu, sigma=sigma, observed=sales_data, dims=&quot;date&quot;)<br><br><br>    # --- prior samples #<br>    adstock_saturation_diminshing_model_prior_predictive = pm.sample_prior_predictive()<br><br>pm.model_to_graphviz(model=tvp_model)</pre><p>The model setup is quite similar to what we saw previously. The main differences lies in:</p><ul><li>We used the training index by slicing the full scaled index on training index.</li><li>We built an <em>Exponential</em> prior for the amplitude of the covariance</li><li>We used an <em>InverseGamma</em> prior (as it is always positive and avoid dividing by 0) for the lengthscale. To find corresponding alpha and beta , we leveraged pm.find_constrained_prior</li><li>We had to use HSGP.prior_linearized which gives you access to pm.Data and pm.set_data to make predictions (more precisely, you get the spectral density expressions and the Laplacian eigenfunctions explicitly so you can use them in any subsequent models).</li></ul><p>Let’s see the results now 👇</p><p><strong><em>Posterior predictive samples</em></strong></p><p>(Beforehand, check your model doesn’t yield any divergences)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbsLGMmTKqrncBLF-e4pFw.png" /></figure><p>Looks good👌!</p><p><strong><em>Out-of-sample predictions</em></strong></p><p>We combine the adstock l_max last observation of the training set with the test set as we saw earlier. Also, we make sure to select lattent_param to study the time varying parameters applied to the saturated media.</p><pre>l_max = 8  # This should match your adstock&#39;s l_max parameter<br><br># Combine last l_max training observations with test data<br>z_combined = np.vstack([z_scaled[-l_max:], z_test_scaled])<br><br># Combine the dates as well<br>combined_dates = np.concatenate([dataset.date.values[-l_max-test_size:-test_size],<br>                               dataset.date.values[-test_size:]])<br><br>combined_index_scaled = np.concatenate([index_train_scaled[-l_max:None],<br>                              index_test_scaled])<br><br># Combined t values<br>t_combined = np.concatenate([t_train[-l_max:], t_test])<br><br># Combined fourier features<br>fourier_combined = np.vstack([fourier_features[-l_max-test_size:-test_size],<br>                            fourier_features[-test_size:]])<br><br>if target_test_scaled is not None:<br>    target_combined = np.concatenate([target_scaled[-l_max:], target_test_scaled])<br>else:<br>    target_combined = np.concatenate([target_scaled[-l_max:],<br>                                     np.full(test_size, np.nan)])<br><br># Update model with the combined data<br>with tvp_model:<br>    pm.set_data(<br>        new_data={<br>            &quot;data&quot;: z_combined,<br>            &quot;t&quot;: t_combined,<br>            &quot;index_scaled_data&quot;: combined_index_scaled ,<br>            &quot;fourier_features&quot;: fourier_combined<br>        },<br>        coords={&quot;date&quot;: combined_dates}<br>    )<br><br>    # Generate posterior predictive samples<br>    combined_posterior_predictive = pm.sample_posterior_predictive(<br>        trace=diminishing_model_trace,<br>        var_names=[&quot;likelihood&quot;,&quot;lattent_param&quot;],<br>        random_seed=rng,<br>        predictions=True,<br>        idata_kwargs={&quot;coords&quot;: {&quot;date&quot;: combined_dates}}<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RUyWL3bshNcpdIhLFQVHQ.png" /><figcaption>Image from the author</figcaption></figure><p><strong>Test Metrics: </strong>MAE: 6.05, RMSE: 7.55, MAPE: 7.35%</p><p>As a comparison, on the same dataset, our best GBM scored with a higher 8.91 RMSE score🚀</p><p><strong><em>Model parameter recovery</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcWGX9dY5ZZQb3NTJ9DrCw.png" /><figcaption>Image from the author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RzV0arxWdyyf3wQAqVrPA.png" /><figcaption>Image from the author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aZP-Eq4zaPaaYg-3MCcjA.png" /><figcaption>Image from the author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnJpF4_56_0_Jvam8qlyIQ.png" /><figcaption>Image from the author</figcaption></figure><p><strong><em>Channels contribution</em></strong></p><p>First let’s focus on the time varying parameters applied to the media effects. Once again, you can see how easy it is to play with the model output and parameters.</p><pre># Get the data from both curves<br>curve1 = diminishing_model_trace.posterior_predictive[&quot;lattent_param&quot;].mean(dim=[&quot;chain&quot;, &quot;draw&quot;])<br>curve2 = combined_posterior_predictive.predictions[&quot;lattent_param&quot;].mean(dim=[&quot;chain&quot;, &quot;draw&quot;]).isel(lattent_param_dim_2=slice(l_max, None))<br><br># Create a figure with appropriate size<br>plt.figure(figsize=(10, 6))<br><br># Plot the first curve<br>x1 = np.arange(len(curve1))<br>plt.plot(x1, curve1, &#39;b-&#39;, label=&#39;Training Period&#39;)<br><br># Plot the extension (second curve)<br># Make sure to offset the x values to continue from where curve1 ends<br>x2 = np.arange(len(curve1), len(curve1) + len(curve2))<br>plt.plot(x2, curve2, &#39;b-&#39;, linewidth=2, linestyle=&#39;--&#39;, label=&#39;Prediction Period&#39;)<br><br># Add a vertical line to show the boundary between training and prediction<br>plt.axvline(x=len(curve1)-1, color=&#39;gray&#39;, linestyle=&#39;:&#39;, alpha=0.7)<br><br># Add labels and title<br>plt.xlabel(&#39;Time Index&#39;)<br>plt.ylabel(&#39;Parameter Value&#39;)<br>plt.title(&#39;Latent Parameter Curves&#39;)<br>plt.legend()<br>plt.grid(True, alpha=0.3)<br><br># Show the plot<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkKvtAZeGj3KuaWOCqorAg.png" /></figure><p>The models successfully recovered the diminishing returns applied to the media effects 👌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXXt_MomY9APx9Hk7AVchQ.png" /><figcaption>Image from the author</figcaption></figure><p>We observe that the model does an excellent job at predicting the TV media contributions but struggles a bit more with the Digital Media. One reason could be the continuous activity of this media compared to the staggered activity of the former. Yet, in both cases, the diminishing effect is captured!</p><p><strong><em>ROAS estimates</em></strong></p><pre>roas_posterior_samples = {}<br><br># Loop through each channel<br>for channel in dataset.channel.values:<br>    # Get media effect samples for this channel<br>    channel_effect_samples = z_effect_posterior_samples.sel(channel=channel)<br><br>    # Get media spending for this channel (excluding test data)<br>    channel_spending = dataset.spends.sel(channel=channel)[0,:][:-test_size].sum().values<br><br>    # Sum across dates for each draw<br>    total_effect = channel_effect_samples.sum(dim=&quot;date&quot;)<br><br>    # ROAS = total effect / total spend<br>    roas_posterior_samples[channel] = total_effect / channel_spending<br><br><br># Plot the ROAS distributions<br>num_channels = len(dataset.channel)<br>fig, axes = plt.subplots(<br>    nrows=num_channels,<br>    ncols=1,<br>    figsize=(12, 5*num_channels),<br>    sharex=True,<br>    sharey=False,<br>    layout=&quot;constrained&quot;<br>)<br><br># Handle single channel case<br>if num_channels == 1:<br>    axes = [axes]<br><br># Plot ROAS for each channel<br>for i, (ax, channel) in enumerate(zip(axes, dataset.channel.values)):<br>    # Plot posterior distribution of ROAS<br>    az.plot_posterior(<br>        roas_posterior_samples[channel],<br>        # ref_val=ref_roas[channel],  # Uncomment if you have reference values<br>        ax=ax<br>    )<br><br>    # Set title for subplot<br>    ax.set(title=f&quot;{channel}&quot;)<br><br>    # Add mean ROAS value to title<br>    mean_roas = roas_posterior_samples[channel].mean().values<br>    ax.set_title(f&quot;{channel} (Mean ROAS: {mean_roas:.0f})&quot;)<br><br>    # For the last subplot, add x-label<br>    if i == num_channels - 1:<br>        ax.set(xlabel=&quot;ROAS&quot;)<br><br># Add overall title<br>fig.suptitle(&quot;Global ROAS by Channel&quot;, fontsize=18, fontweight=&quot;bold&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfBHPQb9RI_sKc6SLJQliw.png" /><figcaption>Image from the author</figcaption></figure><p>Given the previous conclusions, it’s not a surprise we get great results for TV and less accurate ones for Digital. However, the model still gives a higher ROAS for Digital than for TV which is the analysis the marketing team is expecting from us 😉</p><h3>Conclusion</h3><p>In this article, we saw how Bayesian methods — particularly Gaussian Processes combined with adstock and saturation — offer a flexible, robust way to model marketing channels. By capturing uncertainty in parameters and predictions, Bayesian approaches help us gauge confidence in budget allocation decisions.</p><p>Key takeaways include:</p><ul><li><strong>Uncertainty as a Feature:</strong> Rather than a single point estimate, Bayesian models deliver full posterior distributions, guiding more risk-aware decisions.</li><li><strong>Carryover Effects:</strong> Handling adstock or decay properly is crucial — especially at train/test boundaries — to avoid abrupt predictive “jumps.”</li><li><strong>Customization via Priors and Kernels:</strong> Priors let us inject domain knowledge based on discussions with domain experts.</li><li><strong>Fitting unobserved variables with HSGP:</strong> GPs and Hilbert Space approximations — that are more suitable when they apply to time series — are a must-have for real-world MMM challenges.</li></ul><p>Looking ahead, you can further refine these models by exploring hierarchical structures (e.g., partial pooling across multiple brands or regions), advanced priors informed by expert knowledge, or channel calibrations — which we will explore in upcoming articles. While Bayesian methods may have a steeper learning curve, the payoff in interpretability and flexible modelling of complex marketing phenomena is well worth the effort.</p><p>Github repository: <a href="https://github.com/querbesd/marketing-mix-modelling/tree/master">https://github.com/querbesd/marketing-mix-modelling/tree/master</a></p><p>If you have any questions or comments, please comment! Always happy to collect feedback!</p><p><em>My Linkedin</em>: <a href="https://www.linkedin.com/in/damien-querbes-9112491a/">https://www.linkedin.com/in/damien-querbes-9112491a/</a></p><p><strong>Some reference articles:</strong></p><ul><li><a href="https://juanitorduz.github.io/hsgp_intro/">A Conceptual and Practical Introduction to Hilbert Space GPs Approximation Methods</a> by Juan Camilo Orduz (all his notebooks are golden!)</li><li><a href="https://juanitorduz.github.io/pymc_mmm/">Media Effect Estimation with PyMC: Adstock, Saturation &amp; Diminishing Returns</a> by Juan Camilo Orduz</li><li><a href="https://www.pymc.io/projects/examples/en/latest/gaussian_processes/HSGP-Basic.html">Gaussian Processes: HSGP Reference &amp; First Steps</a> by Bill Engels , Alexandre Andorra</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b78f7efdde0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Traditional Machine Learning Models for Marketing Mix Modelling]]></title>
            <link>https://medium.com/@querbes.damien/traditional-machine-learning-models-for-marketing-mix-modelling-6bf820124e50?source=rss-8076ae32af66------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bf820124e50</guid>
            <dc:creator><![CDATA[Damien Querbes]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 10:41:50 GMT</pubDate>
            <atom:updated>2025-04-04T10:49:39.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qonsMTL2W0soUEZ4rViUZQ.jpeg" /></figure><p>Imagine you’re a CMO who just spent $10 million on an Out-of-Home marketing campaign. Now your CEO wants to know: “What was our return on investment? How did it perform? Should we reallocate our spending next quarter?” Unfortunately, traditional post-click attribution models fall short answering these questions and without proper marketing measurement, you’re left with gut feelings instead of concrete answers.</p><p>This article begins a series exploring Marketing Mix Modelling (MMM), a powerful analytical framework I implemented last year while helping a CMO quantify and optimise marketing impact across channels. MMM is built around linear regressions capable of capturing complex patterns, and in my experience, it combines a high level of interpretability for business stakeholders with great precision despite market noise. With several major players currently embracing MMM models — including Google with Meridian, Meta with Robyn, and the PYMC team with pymc-marketing — I strongly encourage any data scientist to explore this thriving field.</p><p>Throughout this article, we’ll explore:</p><ul><li>The fundamental components and challenges in marketing measurement</li><li>(Some of) the building blocks of Robyn and PYMC-marketing open-source project</li><li>Why traditional machine learning approaches tend to fall short for MMM and how we could overcome some limitations</li></ul><h3><strong>Article outline:</strong></h3><ol><li><strong>Quick intro about MMM components</strong></li><li><strong>Synthetic data generation (simple case)</strong></li><li><strong>Exploratory data analysis</strong></li><li><strong>Media data transformation (adstock and saturation)</strong></li><li><strong>Fitting data with traditional machine learning models</strong></li></ol><ul><li>Parameter recovery with Optuna</li><li>Parameter recovery with Shap</li></ul><p>6. <strong>New (and more complex) data challenge with an unobserved confounder</strong></p><h3>Quick Intro about MMM components</h3><p>One of the main strengths of Marketing mix modelling is its simple definition: it is a linear relationship of various components that any marketer is familiar with. Indeed, at its core, MMM decomposes sales (or conversions) into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrHQfO384HZO0Qi4uC5-ww.png" /></figure><p>Where:</p><ul><li>y(t) represents sales at time t</li><li>beta_0 is the intercept term</li><li>beta_trend captures the underlying trend coefficient</li><li>beta_seasonality measures seasonal effects</li><li>beta_i represents the effectiveness (multiplier) of marketing channel i</li><li>x_i^effect is the transformed marketing spend for channel i</li><li>epsilon is the error term (noise)</li></ul><p>Regarding the media transformation commonly applied, it corresponds to:</p><ul><li>first, an adstock transformation to each channel marketing spend. For a geometric adstock function, lambda and alpha parameters respectively define the length of the decay period and the steepness of the curve.</li><li>then, a saturation effect defined by the lambda parameter.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*3iHU7EQcjCYYnOsX6mUlJA.png" /></figure><p>You may also find MMM models where saturation is first applied (before the adstock effect). Here is the rule of thumbs according to <a href="https://research.google/pubs/pub46001/">Jin, Yuxue, et al. “Bayesian methods for media mix modeling with carryover and shape effects.” (2017)</a> , section 2.3:</p><blockquote><em>We could first apply the adstock transformation to the time series of media spend, and then apply the shape transformation. An alternative way would be to reverse the order. If media spend in each time period is relatively small compared to the cumulative spend across multiple time periods, the shape effect in each time period is less obvious compared to that of cumulative media spend. In this case, we would prefer to apply the shape transformation after the adstock transformation. However, if the media spend is heavily concentrated in some single time periods with an on-and-off pattern, the latter choice might be preferable.</em></blockquote><h3><strong>Synthetic data generation</strong></h3><p>To illustrate this relationship, I built a synthetic data class MMMDataGenerator which will allow to recover true parameters. My repository is available in open-source <a href="https://github.com/querbesd/marketing-mix-modelling/tree/master">here</a>.</p><p>For our first example, we use our MMMDataGenerator class with a simple case:</p><ul><li>1 country (US)</li><li>2 marketing channels (TV and a digital one)</li><li>4 years of weekly data</li></ul><pre>countries = [&#39;US&#39;] # We generate data for several countries with different sparcity patterns but let&#39;s keep it simple in this article<br>channels = [&#39;TV&#39;, &#39;Digital&#39;] # 2 channels with different patterns.<br>n_dates = 53*4 # About 4 year data<br><br># Generate data<br>generator = MMMDataGenerator(seed=42) # seed parameter to make data reproductible<br><br># Let run generate_dataset method!<br>dataset, global_params, country_params, _ = generator.generate_dataset_with_dynamics(n_dates=n_dates,<br>    countries=countries,<br>    channels=channels,<br>    apply_dynamic_effects=False # Variable that add time varying coefficients for media effects if True<br>    )</pre><p>Under the hood, the generate_data_with_dynamics() method does the following:</p><pre>t = np.arange(n_dates)<br>        trend_slope = 0.15<br>        seasonal_amplitude = 10<br>        amplitude = 10<br><br>        overall_trend = trend_slope * t<br>        overall_seasonal = seasonal_amplitude * np.sin(2 * np.pi * t / 52)<br><br>        for i, country in enumerate(countries):<br>            launch_date = country_params[country][&#39;launch_date&#39;]<br>            country_size = country_params[country][&#39;size&#39;]<br><br>            # Generate data only for post-launch period<br>            active_dates = n_dates - launch_date<br>            spends = self.generate_media_data(active_dates, channels, country_size)<br>            <br><br>            # Place data after launch date<br>            for j, channel in enumerate(channels):<br>                all_spends[i, launch_date:, j] = spends[channel]<br>            <br><br>            # Store base sales<br>            all_base_sales[i, launch_date:] = country_params[country][&#39;base_sales&#39;]<br><br>            # Store trend and seasonality<br>            all_trends[i, launch_date:] = overall_trend[launch_date:]/10<br>            all_seasonality[i, launch_date:] = overall_seasonal[launch_date:]/10<br><br>            # Calculate and store media response<br>            media_response = np.zeros(n_dates)<br>            for j, channel in enumerate(channels):<br>                if launch_date &lt; n_dates:<br>                    spend = all_spends[i, :, j]<br>                    adstocked = geometric_adstock(<br>                        spend,<br>                        country_params[country][&#39;alphas&#39;][channel],<br>                        l_max=8,<br>                        normalize=True<br>                    ).eval()<br><br>                    saturated = logistic_saturation(<br>                        adstocked,<br>                        country_params[country][&#39;lambdas&#39;][channel]<br>                    ).eval()<br><br>                    # Apply dynamic effectiveness if enabled<br>                    if apply_dynamic_effects:<br>                        # Apply the effectiveness pattern for this country and channel<br>                        effectiveness = dynamic_effectiveness[country]<br>                        # Store for analysis<br>                        all_dynamic_effects[i, :, j] = effectiveness<br>                        # Apply to the media response<br>                        media_effect = saturated * country_params[country][&#39;effects&#39;][channel] * effectiveness<br>                    else:<br>                        media_effect = saturated * country_params[country][&#39;effects&#39;][channel]<br><br>                    all_media_response[i, :, j] = media_effect<br><br>            # Store noise component<br>            noise_scale = 0.75<br>            epsilon = np.zeros(n_dates)<br>            epsilon[launch_date:] = self.rng.normal(0, noise_scale, size=active_dates)<br>            all_noise[i, launch_date:] = epsilon[launch_date:]<br><br>            # Calculate base response<br>            base_response = (<br>                all_base_sales[i, :] +<br>                all_trends[i, :] +<br>                all_seasonality[i, :] +<br>                np.sum(all_media_response[i, :, :], axis=1) +  # Sum across channels<br>                all_noise[i, :]<br>            )</pre><p>This process highlights both the linear relationship explained above as well as the digital transformations. The case is voluntarily simple as there is no unobserved confounders. I find it easier to grasp the main concepts. In the reality, situations are more complex.</p><h3>Exploratory Data Analysis</h3><h4>Overall target observation</h4><p>Here, the only information that can be observed (given we don’t have access to the underlying components) is the Base Response (green curve) which is the sum of the media effects, seasonality, trend and base sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nz9ccVenNbfWbso0zvR0dA.png" /><figcaption>Image from the author</figcaption></figure><p>Response (Raw) means the total response is displayed before being multiplied by the amplitude coefficient (10).</p><p>From this observation, we can note:</p><ul><li>a positive trend</li><li>some seasonality with spikes around Feb-May and low momentum between Aug-Nov</li></ul><p>Let’s keep this information in mind for later.</p><h4>Media Spend observation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAgXTe2O_luQdegORzodMA.png" /><figcaption>Image from the author</figcaption></figure><p>We can note:</p><ul><li>a continuous activity in digital channel with many spikes</li><li>a sparser activity in TV channel with a few momentum during 1 or 2 weeks.</li></ul><p>From the above plot, we can also see the correlation between channels is somehow low. This can be verified by the correlation matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eD6bS8BHEFRzZaZN1jZRBg.png" /><figcaption>Image from the author</figcaption></figure><h3><strong>Media data transformation</strong></h3><p>Now, let’s focus on how we our data synthetic class transforms media spend. This section’s purpose is to grasp the concepts of adstock (or carryover) and saturation effects and how they are combined.</p><h4>Adstock effect</h4><p>I will describe the geometric_adstock as this is the effect I used in my data synthetic class and it’s the main pattern that you should face in the reality and its concept is easily interpratable. But, there are numerous types of adstock effects. You can check all <a href="https://www.pymc-marketing.io/en/stable/api/generated/pymc_marketing.mmm.transformers.html">adstock and saturation priors in pymc-marketing</a> if you want to see more transformation functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*-n20ZiojF9JNzOS_rkQ55Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wkar2Pf5CRpurasyrA3fA.png" /></figure><p><strong>Alpha parameter effect </strong>(0 &lt; alpha &lt;1)<strong>: </strong>The bigger the alpha value, the bigger the carryover effect</p><ul><li>alpha = 0.01: Media effects disappear almost immediately after the first data point.</li><li>alpha = 0.5: Effects persist for a moderate amount of time. If you spend 1€ at t0, at t+1, your adstock effect will be 0.5. At t+2, it will be at 0.25…</li><li>alpha = 0.9: Effects persist for a long time</li></ul><p>From the channels we picked, we might assume that TV has a longer adstock effect than Digital. We’ll verify this later.</p><p><strong>Normalize parameter effect :</strong> When normalize is set to True</p><ul><li>The curves are scaled so the area under the curve equals 1</li><li>This creates a less dramatic initial descent compared to non-normalized curves</li></ul><p>Normalization makes it easier to compare relative shapes of different alpha values.</p><p>Finally, we see that there is no more effects after the l_maxparameter.</p><h4>Saturation effect</h4><p>Same as the adstock effect, below I will refer to the logistic saturation which one of existing saturation effects that may encounter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*JQfcAwZGqfZnUrBXteQDGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENsn6yycdGetSJ0eJ-pH7A.png" /><figcaption>Image from the author</figcaption></figure><p>The lambda value (above 0) controls the saturation rate:</p><ul><li>lambda = 0.5: Very gradual saturation (almost linear for small input values)</li><li>lambda = 2.0: Moderate saturation effect with diminishing returns beginning earlier</li><li>lambda = 4.0: Aggressive saturation with strong diminishing returns at lower spend levels</li></ul><p><strong>Key characteristics:</strong></p><ul><li>The function is monotonically increasing (more input always yields more output)</li><li>As input increases, the marginal effect decreases (diminishing returns)</li><li>Higher lambda values cause the curve to “bend” more quickly, indicating earlier diminishing returns</li><li>The function approaches an asymptotic maximum value as input increases</li></ul><p><strong>Marketing interpretation:</strong></p><ul><li>Captures the concept that there is a limit to advertising effectiveness</li><li>Reflects how additional media spending yields less incremental response after a certain point</li><li>Can be used to identify the “efficient frontier” of advertising spend. If we take the lambda 1 on the above chart, we see that the optimal spend is below 0.6–0.7 where the curve is almost linear.</li></ul><h4>Observation of media transformations on channel spends</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2HEsblXnWCM5EVzLiYCWw.png" /><figcaption>Image from the author</figcaption></figure><ul><li>Despite the spend sparcity of TV channel, TV effect is almost present.</li><li>We see a strong saturation of the Digital channel as it often reaches its maximum asymptot. This is a source of media optimization for the marketing team.</li></ul><p>Here are the saturation curves for both channels with axis 0 being the adstocked media spend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPurDWNsKcVzDDqubLiHvA.png" /><figcaption>Image from the author</figcaption></figure><p>This means:</p><ul><li>There is almost no diminishing effects for TV channels (in the range of historical spend). This should encourage the management to spend bigger budgets on this channel.</li><li>The diminishing effect starts being significant when the adstocked media spend is above 0.4. Below this threeshold, the spend is optimal.</li></ul><h3><strong>Fitting data with traditional machine learning models</strong></h3><p>Now, let’s start modelling!</p><h4>Features creation</h4><pre># Media features<br>media_columns = [&quot;TV_spend&quot;, &quot;Digital_spend&quot;]<br>spend_df = pd.DataFrame(dataset.sel(country=&quot;US&quot;).spends, columns=media_columns)<br><br># Trend features<br>trend = pd.DataFrame({&quot;trend&quot;: np.arange(len(dataset.date))})<br><br># Fourier features<br>n_order = 2<br>periods = dataset.date.dt.dayofyear / 365.25<br>fourier_features = pd.DataFrame(<br>    {<br>        f&quot;{func}_order_{order}&quot;: getattr(np, func)(2 * np.pi * periods * order)<br>        for order in range(1, n_order + 1)<br>        for func in (&quot;sin&quot;, &quot;cos&quot;)<br>    }<br>)<br><br># Combine features<br>X = pd.concat([trend, spend_df, fourier_features], axis=1)<br># Build y<br>y = pd.Series(dataset.target.values.reshape(-1,), index=X.index)</pre><p>For trend, we created a dummy linear trend. We’ll let the model find the real coefficient.</p><p>For seasonality, we computed the <a href="https://en.wikipedia.org/wiki/Fourier_series">Fourier series</a> based on sine and cosine functions, which naturally create wave patterns. By combining these functions at different frequencies (how quickly they complete a cycle), we can capture both simple and complex seasonal patterns.</p><p>In our code, we set n_order = 2 because we consider up to 2 cycles per year in our data. This creates 4 new features (sine and cosine for each of the 2 orders) that help our model recognize and predict these recurring patterns throughout the year.</p><p>This approach is much more flexible than simply using month or quarter as features, as it captures the continuous, smooth nature of seasonal changes rather than treating each month as completely separate from others.</p><h4>Modelling</h4><p>We tested 4 different models:</p><ul><li>A Linear Regression model with adstock transformation (geometric adstock)</li><li>A Linear Regression model with adstock + saturation transformations (geometric adstock and logistic saturation)</li><li>A Gradient Boosting Model with adstock transformation (geometric adstock)</li><li>An Ensemble Model with adstock transformation. The model first fits the data with a Linear Regression model and then fits the residuals with a GBM allowing to capture non linear patterns that the Linear Regression failed at capturing.</li></ul><p>notebooks/traditional_models.py shows how the different model classes are build.</p><h4>Model architecture</h4><p><strong><em>Hyperparameter Tuning with Optuna</em></strong></p><p>One of the most critical components of our MMM implementation is the use of <a href="https://optuna.org/">Optuna</a> for hyperparameter optimization. Unlike traditional GridSearch and RandomSearch, Optuna learns from its initial iterations and builds a surrogate model to predict how our loss is expected to evolve when we change our hyperparameters. Optuna also defines an acquisition function to help choose the next hyperparameters to be tried. This acquisition function balances exploitation (rely on the current best) and exploration (keep exploring better possibilities) of the search space. This makes it super efficient while maintaining scalability.</p><p>In our implementation, we use Optuna to efficiently search through both different adstock parameters for each media channel and model hyperparameters.</p><pre>def _objective(self, trial, X, y, media_cols, tscv, is_multiobjective=False):<br>        &quot;&quot;&quot;Optuna objective function for linear model&quot;&quot;&quot;<br>        # Suggest adstock parameters (as well as logistic saturation parameters if applicable)  <br>        alphas = {}<br>        lambdas = {}<br>        for col in media_cols:<br>            min_val, max_val = self.alpha_ranges.get(col, (0.1, 0.7))<br>            alphas[col] = trial.suggest_float(f&quot;alpha_{col}&quot;, min_val, max_val)<br>            if self.apply_saturation:<br>                # Get lambda range from self.lambda_ranges if available, otherwise use default<br>                lambda_min, lambda_max = self.lambda_ranges.get(col, (0, 12)) if self.lambda_ranges else (0, 12)<br>                lambdas[col] = trial.suggest_int(f&quot;lambda_{col}&quot;, lambda_min, lambda_max)<br><br>        # Apply transformation (adstock and optional saturation)<br>        X_transformed = self._apply_transformation(X, alphas, lambdas, media_cols)<br><br>        # Suggest model parameters<br>        linear_alpha = trial.suggest_float(&quot;linear_alpha&quot;, 0.01, 10.0, log=True)</pre><p>This approach allows us to efficiently search through a large parameter space with fewer trials than a classical Random or Grid Search.</p><p>Based on our domain knowledge, we added some constraints to the TV and Digital alpha parameters but remained very uninformative (wide space) for the lambdasaturation parameters (used by the Linear Regression including both adstock and saturation transformations).</p><pre>for col in media_columns:<br>  if &#39;TV&#39; in col.upper():<br>          alpha_ranges[col] = (0.3, 0.8)<br>          lambda_ranges[col] = (0,10)<br>  elif &#39;DIGITAL&#39; in col.upper() or &#39;SEARCH&#39; in col.upper():<br>          alpha_ranges[col] = (0.0, 0.5)<br>          lambda_ranges[col] = (0,10)</pre><p><strong><em>Adstock and Saturation transformation</em></strong></p><p>After suggesting the search space to each parameter, we transform the full data set based on the transformation function parameter.</p><p>Each class contains a transformation method to compute the adstocked media spend. As we also want one Linear Regression model including the saturation transformation, we added an apply_saturation parameter in the MMM_Linear class.</p><p><strong><em>Optuna’s trial evaluation</em></strong></p><p>To evaluate each trial, we performed a Cross-Validation with TimeSeriesSplit which is very similar to the KFold class but adapted to TimeSeries. For each trial, we splitted our training dataset in 5 folds keeping each time 20 data points for validation. Each fold contains a unique validation set. Below the case of a TimeSeriesSplit with 4 folds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtLWHm9nm686OopZeG4CFQ.png" /><figcaption>Image from the author</figcaption></figure><p>Finally, on each fold, we calculated the RMSE and took the mean. This gives us the trial’s score.</p><p><strong>PS:</strong> <a href="https://facebookexperimental.github.io/Robyn/docs/analysts-guide-to-MMM">Robyn package</a> (Meta) runs a similar modelling process to my 2nd model but it includes a multiobjective Optuna study by combining both the normalized RMSE and RSSD:</p><blockquote>When exploring the best hyperparameters to select, Robyn tasks Nevergrad with achieving two objectives:</blockquote><blockquote><em>Model fit</em>: Aim to minimize the model’s prediction error (NRMSE or normalized root-mean-square error)</blockquote><blockquote><em>Business fit</em>: Aim to minimize decomposition distance (DECOMP.RSSD, decomposition root-sum-square distance). The distance accounts for a relationship between spend share and a channel’s coefficient decomposition share. If the distance is too far, its result can be too unrealistic — e.g. media activity with the smallest spending gets the largest effect.</blockquote><p>Contrarily to what I read in some Medium articles, I didn’t find RSSD metric was a great fit with non Linear models. To assess the model contributions, some authors have used SHAP values. However, Shap values compute the marginal contributions which may differ from the absolute total media contribution. As my content is mainly educational and I wanted to compare different model families, I decided to run simple objective Optuna surveys here.</p><h4>Model comparison</h4><pre>run_mmm_analysis(<br>    X=X,<br>    y=y,<br>    media_columns=media_columns,<br>    alpha_ranges=alpha_ranges,<br>    lambda_ranges=lambda_ranges,<br>    is_multiobjective=False,<br>    test_size=50,<br>    n_trials=50  # Increase this for better results<br>)</pre><p>Running the above script basically does sequentially the following:</p><ul><li>Perform train test split keeping the last 50 observations for model performance metrics</li><li>Train the 4 defined models and optimize hyperparameters towards RMSE through Optuna for 50 trials</li><li>Plot predictions and performance metrics from the 4 models on test set</li><li>Plot SHAP values vs adstocked spend</li><li>Comparing best adstock parameters found from Optuna process</li><li>Computing and comparing incremental ROAS across models</li></ul><p>Now, let’s jump into the results!</p><p><strong><em>Models performance metrics</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAQGvItT3kSiFVu5pW3LRw.png" /></figure><pre>Evaluating models...<br>  Linear Regression Results:<br>    RMSE:  9.40<br>    R²:    0.8543<br>    MAPE:  0.0594<br>    NRMSE: 0.0921<br>  Linear Regression With Saturation Results:<br>    RMSE:  7.83<br>    R²:    0.8988<br>    MAPE:  0.0503<br>    NRMSE: 0.0768<br>  Gradient Boosting Results:<br>    RMSE:  11.27<br>    R²:    0.7905<br>    MAPE:  0.0696<br>    NRMSE: 0.1105<br>  Ensemble Results:<br>    RMSE:  7.56<br>    R²:    0.9057<br>    MAPE:  0.0504<br>    NRMSE: 0.0741</pre><p>From the above chart, we see best models are the Linear Regression model with saturation transformation and the Ensemble models as they show comparable and high R2 (0.9) and low RMSE on test set. Both models seem to be strong candidates to forecast future sales 💪</p><p><strong><em>SHAP Values vs transformed (adstock) spend</em></strong></p><p><a href="https://shap.readthedocs.io/en/latest/#">SHAP</a> (SHapley Additive exPlanations) values represent a powerful approach to model interpretation that originates from cooperative game theory. In the context of Marketing Mix Modelling, SHAP values provide a mathematically rigorous method for quantifying each marketing channel’s contribution to a predicted outcome. Unlike traditional coefficient-based interpretation used in linear models, SHAP values excel when working with complex non-linear models such as Random Forests, Gradient Boosting, or Neural Networks, where simple coefficients don’t exist or aren’t interpretable.</p><p>In our case, we used SHAP values to capture non-linear relationships like saturation effects without requiring pre-specified transformations. If you don’t have any idea of how the saturation effect looks like on your marketing channels, SHAP applied to a non linear model can be quite powerful!</p><p>Let’s illustrate this on our GBM and Ensemble Models:</p><ul><li>Shap values for GBM</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S73Nhj1ocuYUuldUmxgOqQ.png" /><figcaption>Image from the author</figcaption></figure><ul><li>Shap values for the Ensemble model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQKcwF325bvtxyFP5hp4Iw.png" /><figcaption>Image from the author</figcaption></figure><p>Do you still have in mind the saturation curves showed earlier related to the synthetic data? They look pretty similar to what we see above actually! Indeed, for TV channel, the Ensemble model effectively captures the very weak saturation effect as the response curve is almost linear. For Digital channel, the above plot shows the channel gets saturated when spending more than 0.5. This is valuable information for marketing teams.</p><p><strong><em>Adstock parameter recovery</em></strong></p><p>Now, let’s compare the adstock parameters from best models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yupkWvX1ADTuUe13ziRtw.png" /></figure><p>Except the low alpha value for the Linear Regression model, the Optuna process managed to find out alphas close to each channel’s true value.</p><p><strong><em>Incremental ROAS recovery</em></strong></p><p>Let’s take a quick break to precise how the incremental ROAS is computed.</p><blockquote>The incremental ROAS is the difference in sales if the channel is paused divided by the channel costs.</blockquote><p>Here is how the calculate_incremental_roas() function has been built:</p><pre>baseline_prediction = model.predict(test_indices=data_indices)<br>    <br># Initialize results<br>roas_results = {}<br><br># For each channel, zero it out and calculate ROAS<br>for channel in media_columns:<br>    if verbose:<br>        print(f&quot;  Processing channel: {channel}&quot;)<br><br>    # Store original spend data<br>    original_spend = X_data[channel].values<br>    total_spend = np.sum(original_spend)<br><br><br>    try:<br>        # Get prediction with channel zeroed out<br>        zeroed_prediction = model.predict(<br>            test_indices=data_indices,<br>            zero_media_columns=[channel]<br>        )<br><br>        # Calculate incremental contribution<br>        incremental_contribution = np.sum(baseline_prediction - zeroed_prediction)<br><br>        # Calculate ROAS<br>        if total_spend &gt; 0:<br>            roas = incremental_contribution / total_spend<br>        else:<br>            roas = np.nan</pre><p>The predict() method integrate a parameter zero_media_columns to pass a list of channels to “zero out” (setting spend to 0). Let’s execute our function on the training set (most of the times, we want to understand the past performance of our acquisition channels).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGC4A76OQKLULOhOMWwgTw.png" /></figure><p><em>True values on training set: TV ROAS=95 | Digital ROAS=155</em></p><p>The Linear Regression model including Saturation transformation is model closer to true values as it is the only one able to recover the true ROAS from Digital. The Ensemble model has limitations when performing zero-out analysis for channels with strong non-linear response curves, particularly when compared to models with explicit non-linear transformations targeted at those specific channels.</p><p>This analysis reveals an important methodological consideration: while multiple models may exhibit similar predictive accuracy metrics (R² and RMSE), for critical business applications like ROAS estimation, preference should be given to models that more accurately capture the underlying causal mechanisms. This ensures reliable decision support beyond mere statistical fit. While the Ensemble model (linear base with GBM-fitted residuals) achieved marginally superior overall fit statistics, the Linear Regression with Saturation model more accurately recovered the true ROAS values, particularly for Digital channels with pronounced non-linear response curves.</p><p>This finding aligns with the principle of parsimony in statistical modelling — not merely as a philosophical preference for simplicity, but as a practical advantage in analytical robustness. Models with explicit transformations that directly encode domain knowledge (such as media saturation effects) can outperform more complex architectures in downstream business applications, even when the latter show modest improvements in conventional evaluation metrics.</p><p>For Marketing Mix Modelling specifically, this underscores the importance of evaluating models not only on their ability to predict outcomes under observed conditions but also on their capacity to accurately estimate incremental effects under counterfactual scenarios. This distinction becomes particularly critical when models inform budget allocation decisions with significant financial implications.</p><h3>New Data Challenge: introducing diminishing returns over time</h3><p>So far, we have applied 2 non linear transformations with adstock and saturation effects. Testing different approaches including Non-Linear models and applying transformation functions on spend turned out to be quite efficient. Let’s see how our models perform after adding diminishing returns to our saturated response.</p><p>To generate this new pattern, we can reuse our MMMDataGenerator class. We just need to set apply_dynamic_effects to True:</p><pre>dataset, global_params, country_params, dynamics_dict = generator.generate_dataset_with_dynamics(n_dates=n_dates,<br>    countries=countries,<br>    channels=channels,<br>    apply_dynamic_effects=True<br>    )</pre><p>To display target and component contributions:</p><pre>components_basic = {<br>    &#39;base_sales&#39;: True,<br>    &#39;trend&#39;: True,<br>    &#39;seasonality&#39;: True,<br>    &#39;individual_channels&#39;: False,<br>    &#39;total_media&#39;: True,<br>    &#39;base_response&#39;: True,<br>    &#39;noise_line&#39;: False,<br>    &#39;noise_range&#39;: True,<br>    &#39;target&#39;: True,<br>    &#39;scaled_base&#39;: True,<br>    &#39;promo_effects&#39;: False<br>}<br>fig = visualizer.plot_contributions(dataset, country_params, countries, components_basic)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDmoqmfKU8T_DXK6n8op7w.png" /><figcaption>Image from the author</figcaption></figure><p>To understand the new transformation applied to the saturated spend:</p><pre>fig_2 = visualizer.plot_media_transformations(dataset, country_params, countries, dynamics_dict=dynamics_dict)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uyt4Qp-gWCi5xIeF61V6HQ.png" /></figure><p>The plots on the right both show the diminishing returns pattern over time. Let’s see if our models are able to capture this new pattern.</p><p><strong><em>Models performance metrics</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UVr5HaTF1G0HY9ILVxNZ3A.png" /><figcaption>Image from the author</figcaption></figure><pre>2. Evaluating models...<br>  Linear Regression Results:<br>    RMSE:  17.84<br>    R²:    -0.7592<br>    MAPE:  0.1867<br>    NRMSE: 0.2522<br>  Linear Regression With Saturation Results:<br>    RMSE:  19.39<br>    R²:    -1.0780<br>    MAPE:  0.2079<br>    NRMSE: 0.2741<br>  Gradient Boosting Results:<br>    RMSE:  9.44<br>    R²:    0.5073<br>    MAPE:  0.0942<br>    NRMSE: 0.1335<br>  Ensemble Results:<br>    RMSE:  13.17<br>    R²:    0.0414<br>    MAPE:  0.1277<br>    NRMSE: 0.1862</pre><p>The poor performance of linear models (evidenced by negative R² values) is expected given the violation of homoscedasticity assumptions. These models fundamentally cannot capture the temporal dynamics of diminishing returns present in the underlying data. Only the Gradient Boosting model seems to show some decent performance with a R2 of 0.5. Let’s focus on this model and see if it is able to capture the diminishing returns trend.</p><p><strong><em>SHAP Values vs transformed (adstock) spend and over time</em></strong></p><ul><li>Gradient Boosting model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7sau7JNDdbQFtBTI4jkzQ.png" /><figcaption>Image from the author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6zN9riVpAiOcRGOenfhVw.png" /><figcaption>Image from the author</figcaption></figure><p>From the above plots, there is no signs of diminishing returns applied to the adstocked channel spend.</p><p>When plotting SHAP values against Adstocked spend, we still a linear relationship for TV conveying the weak saturation effect on this channel. Regarding the Digital channel, we can’t conclude a linear relationship here as the residuals are not equally distributed around around the line. More likely, the previous saturation effect is reflected here with a digital spend effect starting decreasing after the adstocked spend is above 0.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBRExuvZdxfb6-ESv39cAw.png" /><figcaption>Image from the author</figcaption></figure><p><strong><em>Adstock parameter recovery</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZg5PnsaC1esW4FzTAuVNA.png" /><figcaption>Image from the author</figcaption></figure><p>The Optuna process managed to recover the true values for the adstock parameter. Especially for the GBM 💪</p><p><strong><em>Incremental ROAS recovery (on training set)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dk4id0YULKRrNRaPWgb6w.png" /><figcaption>Image from the author</figcaption></figure><p><em>True values: TV ROAS=70 | Digital ROAS=85</em></p><p>All models predict a higher ROAS for TV than Digital. However, they are all wrong showing that even our best model fails at being explainable enough to make appropriate business decisions 😞</p><h3>Conclusion</h3><p>Our exploration of Marketing Mix Modelling approaches reveals valuable practical insights. Traditional linear regression models, when properly transformed, perform remarkably well at capturing seasonality, adstock effects, and saturation curves. Their interpretability makes them powerful tools for stakeholders requiring clear justification for marketing investments.</p><p>However, when faced with complex patterns like diminishing returns over time or other types of unobserved confounders, linear approaches break down significantly. Our gradient boosting model, optimized through Optuna, demonstrated superior adaptability in these scenarios. SHAP values in that case becomes handy to uncover non linear trends (even though that it failed at capturing the diminishing returns for us).</p><p>Despite these advantages, all models struggled with accurate ROAS estimation when confronted with complex patterns. This suggests that for marketing environments with evolving effectiveness and potential confounders, more sophisticated approaches may be necessary. Bayesian methods offers better alternatives by incorporating domain knowledge through priors, some of them being used to capture complex patterns, and providing a principled approach to causal inference which makes them perfectly explainable.</p><p>The choice of modelling technique should be guided by your specific marketing ecosystem’s complexity. In simpler environments, transformed linear models offer an excellent balance of interpretability and accuracy. For more dynamic situations, consider gradient boosting with SHAP or exploring Bayesian models, which we’ll cover in the <a href="https://medium.com/@querbes.damien/the-benefits-of-bayesian-models-compared-to-traditional-ones-0b78f7efdde0">next article</a>.</p><p>Github repository: <a href="https://github.com/querbesd/marketing-mix-modelling/tree/master">https://github.com/querbesd/marketing-mix-modelling/tree/master</a></p><p>If you have any questions or comments, please comment! Always happy to collect feedback!</p><p><em>My Linkedin</em>: <a href="https://www.linkedin.com/in/damien-querbes-9112491a/">https://www.linkedin.com/in/damien-querbes-9112491a/</a></p><p><strong>Some reference articles:</strong></p><ul><li><a href="https://www.topbots.com/explainable-ai-marketing-analytics/">Explainable AI: Application of Shapely Values in Marketing Analytics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf820124e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Customer Insights with an automated Chat Topic Detection pipeline]]></title>
            <link>https://medium.com/@querbes.damien/unlocking-customer-insights-with-an-automated-chat-topic-detection-pipeline-b18ad4e419a7?source=rss-8076ae32af66------2</link>
            <guid isPermaLink="false">https://medium.com/p/b18ad4e419a7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[topic-clusters]]></category>
            <category><![CDATA[customer-feedback]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Damien Querbes]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 16:41:20 GMT</pubDate>
            <atom:updated>2024-09-27T16:42:44.078Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s business landscape, analyzing customer interactions at scale is crucial for decision-making. Chat conversations, in particular, are full of valuable data that can provide real-time insights into what customers want, how they feel, and the challenges they face. Manual conversation tagging was once the standard approach for customer support teams, but it was time-consuming and error-prone. Luckily, the advent of large language models (LLMs) has made this process much easier now 🚀, making chat topic detection a powerful tool for product and marketing teams alike.</p><p>In this article, I describe how I implemented a chat topic detection pipeline for <a href="https://dogchef.com/">Dog Chef </a>— one of the leading players in Europe for pet fresh meals.</p><h3>Why Chat Topic Detection Matters for Businesses</h3><h4>1. Improve Your Marketing Communication</h4><p>By analyzing customer chats, businesses can gain a deeper understanding of which product features confuse customers or require more explanation. With this information, you can enhance FAQs or improve communication on product pages, ensuring potential customers are well-informed and reducing friction in the buying journey.</p><h4>2. Evaluate Your Operations</h4><p>Customer chats often reveal operational inefficiencies. For example, if a large portion of chats is focused on shipping delays or product issues, these operational challenges can be quantified and tracked over time. Monitoring chat volumes related to such complaints gives businesses a real-time gauge on how well their operations are functioning and highlights areas for immediate improvement.</p><h4>3. Improved Team Efficiency</h4><p>Manually analyzing thousands of chat interactions can be overwhelming. Automating chat topic detection allows support teams to focus on more complex, high-value interactions while leaving the bulk of chat categorization to machine learning models. This approach reduces operational costs and enhances efficiency, empowering teams to be more productive.</p><h4>4. Add the Prediction Output Into Your Churn Prediction Models</h4><p>One of the most critical business metrics for any company is customer churn. By incorporating the output of chat topic detection into existing churn prediction models, businesses can gain a more comprehensive understanding of customer dissatisfaction. Topics related to service issues or unmet expectations can serve as early indicators of potential churn. This integration helps businesses act before it’s too late, either through customer outreach or by addressing the root cause of dissatisfaction.</p><h4>5. Data-Driven Insights for Product Management</h4><p>Understanding the topics customers are talking about in their chats provides invaluable insights for product development. By visualizing the main themes of customer conversations, product teams can prioritize features or improvements based on real customer feedback. This reduces the risk of product misalignment and ensures your roadmap is driven by actual customer needs.</p><h3>How to implement a chat topic detection pipeline?</h3><p>I open-sourced the code in my <a href="https://github.com/querbesd/chat-topic-detection">github repository</a>. Hope you will find it useful 😉</p><h4>Stack I used</h4><ul><li>Airbyte for ETL</li><li>OpenAI API. In my case, I fine-tuned a gpt 3.5 model to improve model performance. I really recommend it if you have a long list of topics and nuances are sometimes small.</li><li>DBT for data processing and job scheduler</li><li>Bigquery for the data warehouse</li><li>GCS to store the prediction outputs</li><li>Google Cloud Function to execute the code</li><li>Pub/Sub topic to execute the Cloud Function</li></ul><h4>Steps to follow</h4><p>1. Extract conversations from your chat solution to your data warehouse. You can explore some freemium ETL that you can explore such as <a href="https://fivetran.com/">Fivetran</a> or <a href="http://airbyte.com/">airbyte</a>.</p><p>2. Preprocess the conversations in an acceptable format (see the repo). <a href="http://dbt.com/">DBT</a> can be very handy in this context.</p><p>3. Clone the repository locally</p><pre>git clone https://github.com/querbesd/chat-topic-detection.git</pre><p>4. Update your variable environments and params</p><p>Refer to the repo for more information.</p><p>Basically, the code does:</p><ul><li>Fetch conversation data from the input table and create the input requests file to be ingested by the LLM. The file is stored in a temporary file.</li><li>Performs batch predictions asynchroneously. batch_predict.py parallelizes requests to the OpenAI API while throttling to stay under rate limits. The script for the batch predicting was inspired from the openai-cookbook (see code <a href="https://github.com/openai/openai-cookbook/blob/main/examples/api_request_parallel_processor.py">here</a>)</li><li>Save the output file locally or in a GCS bucket.</li></ul><p>5. Deploy the project to a <a href="https://cloud.google.com/functions/docs/deploy#console_1">Cloud Function</a></p><p>6. Create a <a href="https://cloud.google.com/pubsub/docs/create-topic">Pub/Sub topic</a> to trigger your Cloud Function</p><p>7. Create another Cloud Function to pull data from your GCS bucket to Bigquery. Set your bucket as a trigger of your function. This means anytime a file is created, it will trigger the function.</p><p>I put the code below if this may interest you:</p><pre>from google.cloud import bigquery<br>from google.cloud import storage<br>import os<br>import json<br><br>def import_to_big_query(data, context, project_id=&quot;your_project_id&quot;, dataset=&#39;your_target_dataset&#39;, table_id=&#39;your_target_table&#39;, verbose=True):<br>    def vprint(s):<br>        if verbose:<br>            print(s)<br><br>    vprint(f&quot;Event ID: {context.event_id}&quot;)<br>    vprint(f&quot;Event type: {context.event_type}&quot;)<br>    vprint(&quot;Importing required modules.&quot;)<br><br>    <br><br>    vprint(f&quot;This is the data: {data}&quot;)<br><br>    input_bucket_name = data[&#39;bucket&#39;]<br>    source_file_name = data[&#39;name&#39;]<br>    uri = f&quot;gs://{input_bucket_name}/{source_file_name}&quot;<br><br>    vprint(f&quot;Getting the data from bucket: {uri}&quot;)<br>    vprint(f&quot;Project ID: {project_id}&quot;)<br><br>    # Process only JSONL files<br>    if source_file_name.lower().endswith(&#39;.jsonl&#39;):<br>        storage_client = storage.Client()<br>        bucket = storage_client.bucket(input_bucket_name)<br>        blob = bucket.blob(source_file_name)<br>        content = blob.download_as_text()<br><br>        # Transform and write JSONL data to a temporary file<br>        temp_file_path = transform_jsonl_and_write(content)<br><br>        load_data_to_bigquery(temp_file_path, dataset, table_id)<br><br>def load_data_to_bigquery(temp_file_path, dataset, table_id):<br>    client = bigquery.Client()<br>    table_ref = f&quot;{client.project}.{dataset}.{table_id}&quot;<br><br>    job_config = bigquery.LoadJobConfig(<br>        source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,<br>        autodetect=True,<br>        write_disposition=bigquery.WriteDisposition.WRITE_APPEND,<br>    )<br><br>    with open(temp_file_path, &quot;rb&quot;) as source_file:<br>        load_job = client.load_table_from_file(<br>            source_file,<br>            table_ref,<br>            job_config=job_config,<br>        )<br><br>    load_job.result()  # Wait for the job to complete<br>    print(f&quot;Job finished. Loaded {load_job.output_rows} rows.&quot;)<br><br>def transform_jsonl_and_write(content):<br>    <br>    temp_file_path = &#39;/tmp/transformed_data.jsonl&#39;<br>    <br>    rows = []<br>    for index, line in enumerate(content.splitlines()):<br>        parsed_line = json.loads(line)<br>        # Assuming the &#39;prediction&#39; data is located at parsed_line[1] and needs to be checked for errors<br>        # Skip rows where &#39;prediction&#39; contains error messages<br>        if any(&quot;{&#39;error&#39;:&quot; in str(prediction) for prediction in parsed_line[1]):<br>            print(f&quot;Skipping row n°{index} due to error in &#39;prediction&#39;.&quot;)<br>            continue  # Move to the next iteration without adding the current row to rows<br><br>        row = {<br>            &#39;conversation_id&#39;: parsed_line[2][&#39;conversation_id&#39;],<br>            &#39;conversation&#39;: parsed_line[2][&#39;conversation&#39;],<br>            &#39;prediction&#39;: parsed_line[1]<br>        }<br>        rows.append(row)<br>    <br>    # Convert the list of dictionaries to a JSONL string<br>    jsonl_string = &#39;\n&#39;.join(json.dumps(row) for row in rows)<br>    with open(temp_file_path, &#39;w&#39;, encoding=&#39;utf-8&#39;) as file:<br>        file.write(jsonl_string)<br>    return temp_file_path</pre><p>And voilà! You should now have your conversations and their associated topics in the desired Bigquery table 💪 And analyzing topic breakdown and trends becomes super easy 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*KigMXFq4vEyq6zWv9iWt6w.png" /></figure><p>If you have any questions or comments, please comment! Always happy to collect feedback!</p><p><em>My Linkedin</em>: <a href="https://www.linkedin.com/in/damien-querbes-9112491a/">https://www.linkedin.com/in/damien-querbes-9112491a/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b18ad4e419a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>