<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://lmc2179.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://lmc2179.github.io/" rel="alternate" type="text/html" /><updated>2026-02-22T20:44:33+00:00</updated><id>https://lmc2179.github.io/feed.xml</id><title type="html">Casual Inference</title><subtitle>Data analysis and other apocrypha</subtitle><author><name>Louis Cialdella</name></author><entry><title type="html">Don’t stop as soon as you hit stat sig! How to safely stop an experiment early with alpha spending in Python</title><link href="https://lmc2179.github.io/posts/alpha_spending.html" rel="alternate" type="text/html" title="Don’t stop as soon as you hit stat sig! How to safely stop an experiment early with alpha spending in Python" /><published>2024-07-10T00:00:00+00:00</published><updated>2024-07-10T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/alpha_spending</id><content type="html" xml:base="https://lmc2179.github.io/posts/alpha_spending.html"><![CDATA[<h1 id="where-it-begins-the-understandable-urge-to-stop-early">Where it begins: The (understandable) urge to stop early</h1>

<p>Let me tell you a story - perhaps a familiar one.</p>

<blockquote>
  <p><strong>Product Manager</strong>: Hey <code class="language-plaintext highlighter-rouge">{data_analyst}</code>, I looked at your dashboard! We only kicked off <code class="language-plaintext highlighter-rouge">{AB_test_name}</code> a few days ago, but the results look amazing! It looks like the result is already statistically significant, even though we were going to run it for another week.</p>

  <p><strong>Data Analyst</strong>: Absolutely, it’s very promising!</p>

  <p><strong>Product Manager</strong>: Well, that settles it, we can turn off the test, it looks like a winner.</p>

  <p><strong>Data Analyst</strong>: Woah, hold on now - we can’t do that!</p>

  <p><strong>Product Manager</strong>: But…why not? Your own dashboard says it’s statistically significant! Isn’t that what it’s for? Aren’t we like…95% sure, or something?</p>

  <p><strong>Data Analyst</strong>: Yes, but we said we would collect two weeks of data when we designed the experiment, and the analysis is only valid if we do that. I have to respect the arcane mystic powers of ✨<code class="language-plaintext highlighter-rouge">S T A T I S T I C S</code>✨!!!</p>
</blockquote>

<h3 id="has-this-ever-happened-to-you"><em><strong>Has this ever happened to you?</strong></em></h3>

<p>If you’re a working data scientist (or PM), it probably has. This is an example of <strong>early stopping</strong>, or <strong>optional stopping</strong>, or <strong>data peeking</strong> - and we are often cautioned to avoid it. The most frustrating part about this conversation is that it happens even when both parties are trying to be collaborative and play by the rules.</p>

<p><strong>From the data scientist’s point of view</strong>, they did a power analysis and figured out how to make sure the experiment is as informative as possible. Can’t we just stick to the plan?</p>

<p><strong>From the PM’s point of view</strong>, the dashboard is telling them that statistical analysis sanctions the result they see. We gave each experiment arm a chance, and one of them was the winner using their usual statistical process. Why should we wait for the full sample if an easy win is right in front of us?</p>

<p>The PM’s argument, frankly, makes a lot of sense. A couple more detailed arguments in favor of stopping early might look like this:</p>

<ul>
  <li><strong>If we think that one of the treatment groups really is better, then collecting more data is an unnecessary waste</strong>. Collecting data isn’t usually free - so it’s best to stop as soon as you can.</li>
  <li><strong>If we think that one of the treatment groups really is better, than we should make it available to a larger population as soon as we can</strong>. This is not always just a question of a small gain, or a few more dollars. In clinical trials, the stakes can be very literally life or death - the trials of the HIV drug AZT were stopped short for this reason, as the results were so overwhelmingly positive that it seemed unethical to continue depriving the control group and other patients of the chance at an effective therapy. The trial was ended early and the FDA voted to approve its use shortly after (there are also more complicated factors involved in that RCT, but that’s another conversation).</li>
</ul>

<p>The core issue here comes from the fact that good experimentation needs to balance <strong>speed vs risk</strong>. On the one hand, we want to learn and act as quick as we can. On the other, we want to avoid unnecessary risk - every experiment includes the possibility of a downside, but we want to be careful and not take on more risk than we need to.</p>

<p>All the possible experimentation procedures sit somewhere on this high speed-low risk tradeoff spectrum. The “highest speed” solution would be to avoid experimentation at all - just act as quick as you can. The “lowest risk” solution would be to run the experiment as planned, and always run it by the book, no matter what happens.</p>

<p>As is so often the case, there is a chance to get the both of worlds by picking a solution between the extremes. <strong>There are good reasons to stop a test early, but in order to do so safely, we need to be more careful about our process.</strong> Let’s start by looking at the risks of stopping early without changing our process, and then we’ll talk about how to mitigate those risks.</p>

<h1 id="what-risk-do-we-take-by-stopping-as-soon-as-the-result-is-significant">What risk do we take by stopping as soon as the result is significant?</h1>

<p>Let’s remind ourselves why we do statistical significance calculations in the first place. We use P-values, confidence intervals, and all of those kinds of other frequentist devices is because they control uncertainty. The result of designing an experiment, picking a sample size based on 80% power and doing your calculations with $\alpha = 5\%$ is that the arcane mystic powers of statistics will prevent you from making a Type I error 95% of the time and a Type II error 80% of the time.</p>

<p>Talking about the benefits in terms of “Type I” and “Type II”  errors is a little opaque. What does this do for us here in real life? <strong>We can make it concrete by talking about a more specific analysis</strong>. Let’s talk about an analysis which is very common in practice - comparing the means of two samples experimentally with a T-test. A T-test based experiment usually looks something like this:</p>

<ul>
  <li>Pick your desired power and significant levels, usually denoted by the magic symbols $\beta$ and $\alpha$. We often use $\beta = 80\%$ and $\alpha = 5\%$, though you may pick other values based on the context.</li>
  <li>Use your favorite power calculator to pick a sample size, which we’ll call $n$.</li>
  <li>Collect $n$ samples from the control and treatment arms, and compute the difference in means $\hat{\Delta} = \overline{y^T} - \overline{y^C}$. That’s just the mean of the treated units, minus the mean of the control units.</li>
  <li>Use your favorite implementation of the T-test (like the one in <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html">scipy</a>) to compute a P-value. If $p \leq \alpha$, then you can conclude that $\Delta \neq 0$, and so the treatment and control groups have different population means. Assuming the differences goes in the direction of better outcomes, you officially pop the champage and conclude that your treatment had some non-zero effect compared to control. Nice!</li>
</ul>

<p>This procedure is a test run “by the book”, in which we collected all our data and ran a single T-test to see what happened. It guarantees that we get the usual magic protections of P-value testing, namely that:</p>

<ul>
  <li>We’ll only come to a false conclusion $\alpha\%$ of the time. That is, it will only rarely happen that the above procedure will cause us to pop the champagne when in fact $\Delta = 0$. This is protection from Type I errors, or “false detection” errors.</li>
  <li>We’ll detect effects that actually exist (and are larger than the MDE) about $\beta \%$ of the time. That is, if $\Delta$ is large enough, we’ll pop the champage most of the time. This is protection from Type II errors, or “failure to detect” errors.</li>
</ul>

<p>What happens to these guarantees if we introduce the possibility of early stopping? <strong>The short version is that the more often we check to see if the result is significant, the more chances we are giving ourselves to detect a false positive, or commit a Type I error. As a result, just checking more often can cause our actual Type I error rate to be much higher than $\alpha$</strong>.</p>

<p>Let’s look at the actual size of the impact of early stopping. Let’s augment our T-test based experiment by not just calculating the p-value on the last day, of the experiments but on the 29 days before. We’re going to <strong>simulate</strong> this example in a world where the null hypothesis really is true, and there is no treatment effect.</p>

<p>So at each step of a simulation run (where one step is one day, and one simulation run is one experiment), we’ll:</p>
<ul>
  <li>Simulate 100 samples from the $Exponential(5)$ distribution and append them to the control data set. Do the same for treatment. Since we’re drawing treated and control samples from the same distribution, the null hypothesis that they have the same population mean is literally true.</li>
  <li>Run a T-test on the accumulated treatment/control data so far. If $p &lt; .05$, then we would have stopped early using the “end the experiment when it’s significant” stopping rule.</li>
</ul>

<p>If we do this many times, this will tell us whether stopping as soon as we see a significant result would have caused us to commit a Type I error. If we run this many times, and track the P-value of each run, we see that the trajectory of many P-values crosses the <code class="language-plaintext highlighter-rouge">.05</code> threshold at some point early on  in the test, but as time goes on most of the P-values “settle down” to the expected range:</p>

<p><img src="https://lmc2179.github.io/drafts/image.png" alt="alt text" /></p>

<p>In this picture, each simulation run is a path which runs from zero samples to the total sample size. Paths which cross the $\alpha = .05$ line at any time would have been false positives under early stopping, and are colored blue. Paths which are never significant are shown in grey. You’ll notice that while few paths end below the dotted line, many of them cross the line of significance at some point as they bob up and down.</p>

<p>During these simulations, the T-test conducted at the very end had a false positive rate of 5%, as expected. <strong>But the procedure which allowed stopping every day (ie, every 100 samples) had a false positive rate of 27%, more than 5x worse!</strong> (I ran 1000 simulations, though I’m only showing 40 of them so the graph isn’t so busy - you can find the code in the appendix, if you’re curious.)</p>

<p>We talked about the speed-risk tradeoff before - adding more checks without changing anything else will expose us to more risks, and make our test results much less safe. <strong>How should we insulate ourselves from the risk of a false positive if we want to stop early?</strong></p>

<p>On first glance, this looks similar to the problem of multiple testing that might be addressed by methods like the <a href="https://lmc2179.github.io/posts/fwer.html">Bonferroni correction</a> or an <a href="https://lmc2179.github.io/posts/fdr.html">FDR correcting method</a>. Those methods also help us out in situations where more checks inflate the false positive rate. Those methods would cause us to set our $\alpha$ lower based on the number of checks we’re planning to run. By lowering $\alpha$ we are “raising the bar” and demanding more evidence before we accept a result. This is a good start, but it has a serious flaw - it will meaningfully decrease the power ($\beta$) of our experiment, and we’ll need to run it longer than expected. Can we do better?</p>

<p>We can try and compromise by saying that we should be skeptical of apparent  effects early in the experiment, but that effects that are really large should still prompt us to stop early. That leaves us a little wiggle room - we should not stop early most of the time, unless the effect looks like it is <em>really</em> strong. What if we set $\alpha$ lower at the beginning of the experiment, but used the original value of $\alpha$ (5%, or whatever) after all the data is collected? That sort of “early skepticism” approach might get us a procedure that works.</p>

<p>Of course, the devil is in the details, and so this opens us up to the next question. <strong>How strong does the effect need to be early on in the experiment for us to be willing to stop early? How should we change our testing procedure to accommodate early stopping?</strong></p>

<h1 id="the-alpha-spending-function-approach-set-the-standard-evidence-higher-early-on-in-the-experiment">The $\alpha$ spending function approach: set the standard evidence higher early on in the experiment</h1>

<p>The idea we’ve come across here is called the <strong>alpha spending function approach</strong>. It works by turning our fixed significance level $\alpha$ into a function $adjust(p, \alpha)$, which takes in the proportion of the sample we’ve collected so far and tells us how to adjust the significance level based on how far along we are. The proportion $p$ is given by $p = \frac{n}{N}$, the fraction of the total sample collected.</p>

<p>The idea here is that when $p$ is small, $\alpha$ will be small, and we’ll be very skeptical of observed effects. When we’ve collected the entire sample then $p = 1$ and we’ll apply no adjustment, meaning $adjust(p, \alpha) = \alpha$. A detailed reference here is <a href="https://eclass.uoa.gr/modules/document/file.php/MATH301/PracticalSession3/LanDeMets.pdf">Lan and DeMets 1994</a>, which focuses on the clinical trial setting.</p>

<p>What form might $adjust(p, \alpha)$ have? Since we want it to scale between 0 and $\alpha$ as $p$ increases, a reasonable starting point is something like:</p>

\[adjust_{linear}(p, \alpha) = p \alpha\]

<p>We might called this a <strong>linear alpha spending function</strong>. Lan and Demets above mention an alternative called the <strong>O’Brien-Fleming (OBF) alpha spending function</strong>, which is:</p>

\[adjust_{OBF}(p, \alpha) = 2 - 2 \Phi (\frac{Z_{\alpha / 2}}{\sqrt{p}})\]

<p>Where $\Phi$ is the CDF of a standard normal distribution, $Z_{\alpha/2}$ is the Z-value associated with $\alpha/2$, and $p$ is the fraction of the sample we’ve collected so far.</p>

<p>In Python, a little bit of assembly is required to calculate this function. It looks something like this:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">obf_alpha_spending</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="n">proportion_sample_collected</span><span class="p">):</span>
    <span class="n">z_alpha_over_2</span> <span class="o">=</span> <span class="n">norm</span><span class="p">.</span><span class="n">ppf</span><span class="p">(</span><span class="mi">1</span><span class="o">-</span><span class="n">desired_final_alpha</span><span class="o">/</span><span class="mi">2</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">2</span> <span class="o">-</span> <span class="mi">2</span><span class="o">*</span><span class="p">(</span><span class="n">norm</span><span class="p">.</span><span class="n">cdf</span><span class="p">(</span><span class="n">z_alpha_over_2</span><span class="o">/</span><span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">proportion_sample_collected</span><span class="p">)))</span>
</code></pre></div></div>

<p>Unless you spend a lot of time thinking about the normal CDF, it’s probably not obvious what this function looks like. Lets see how going from $p=0$ (none of the sample collected) to $p=1$ (full sample collected) looks:</p>

<p><img src="https://lmc2179.github.io/drafts/image-1.png" alt="alt text" /></p>

<p>We see that the OBF function is more conservative everywhere than the linear function, but that it is extra conservative at the beginning. Why might this be? Some intuition (I think) has to do with the fact that the relationship between sample size and precision is non-linear (the formula for the standard error of the mean, for example, includes a $\sqrt{n}$).</p>

<p>Okay, so we have a way of adjusting $\alpha$ dependign on how much data has arrived. Lets put it to the test. We’ll rerun the simulation above, with the following conditions. This time, we’ll compare the false positive rates from the different strategies we’ve discussed: constant alpha (same as above), the linear spending function, and the O’Brien Fleming spending function. The results of 10,000 simulated experiments look like this:</p>

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Number of False positives (of 10k simulations)</th>
      <th>False positive rate (Type I error rate)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Constant $\alpha = .05$</td>
      <td>$2776$</td>
      <td>$27.76\%$</td>
    </tr>
    <tr>
      <td>Linear</td>
      <td>$1285$</td>
      <td>$12.85\%$</td>
    </tr>
    <tr>
      <td>OBF</td>
      <td>$799$</td>
      <td>$7.99\%$</td>
    </tr>
  </tbody>
</table>

<p>In the first row, we see what we already know - early stopping without using an alpha spending rule has a False positive rate much larger than the expected 5%. Linear alpha spending is an improvement (about 2.6x more errors than desired), but OBF is the winner, with a Type I error rate closest to 5% (1.6x more errors than desired). OBF will have less power, but power analysis subject to early stopping rules is a subject for another time.</p>

<p>The alpha spending approach is an easy thing to add to your next test, and it’s worth doing - it lets you have the best of both worlds, letting you stop early if the result is large at only a small cost to your false positive rate. And given that you can write it as a 2-line Python function, it’s not too hard to add to your A/B test analysis tool. And best of all, having a strategy for early stopping means no more awkward conversations about the <em>arcane mystic powers of</em> ✨<code class="language-plaintext highlighter-rouge">S T A T I S T I C S</code>✨ with your cross-functional partners!</p>

<h1 id="appendix-code-for-the-simulations">Appendix: Code for the simulations</h1>

<h3 id="p-value-paths">P-value paths</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">ttest_ind</span><span class="p">,</span> <span class="n">norm</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>

<span class="n">days_in_test</span> <span class="o">=</span> <span class="mi">30</span>
<span class="n">samples_per_day</span> <span class="o">=</span> <span class="mi">100</span>


<span class="k">def</span> <span class="nf">simulate_one_experiment</span><span class="p">():</span>
    <span class="n">treated_samples</span><span class="p">,</span> <span class="n">control_samples</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([]),</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([])</span>
    
    <span class="n">simulation_results</span> <span class="o">=</span> <span class="p">[]</span>
    
    <span class="k">for</span> <span class="n">day</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">days_in_test</span><span class="p">):</span>
        <span class="n">treated_samples</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">treated_samples</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">exponential</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">samples_per_day</span><span class="p">))</span>
        <span class="n">control_samples</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">control_samples</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">normal</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">samples_per_day</span><span class="p">))</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">ttest_ind</span><span class="p">(</span><span class="n">treated_samples</span><span class="p">,</span> <span class="n">control_samples</span><span class="p">)</span>
        <span class="n">simulation_results</span><span class="p">.</span><span class="n">append</span><span class="p">([</span><span class="n">day</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">treated_samples</span><span class="p">),</span> <span class="n">result</span><span class="p">.</span><span class="n">statistic</span><span class="p">,</span> <span class="n">result</span><span class="p">.</span><span class="n">pvalue</span><span class="p">])</span>
        
    <span class="n">simulation_results</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">simulation_results</span><span class="p">,</span> <span class="n">columns</span><span class="o">=</span><span class="p">[</span><span class="s">'day'</span><span class="p">,</span> <span class="s">'n'</span><span class="p">,</span> <span class="s">'t'</span><span class="p">,</span> <span class="s">'p'</span><span class="p">])</span>
    <span class="k">return</span> <span class="n">simulation_results</span>

<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="n">sns</span>

<span class="n">n_simulations</span> <span class="o">=</span> <span class="mi">40</span>
<span class="n">false_positives</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">early_stop_false_positives</span> <span class="o">=</span> <span class="mi">0</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_simulations</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">simulate_one_experiment</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">np</span><span class="p">.</span><span class="nb">any</span><span class="p">(</span><span class="n">result</span><span class="p">[</span><span class="s">'p'</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="p">.</span><span class="mi">05</span><span class="p">):</span>
        <span class="n">early_stop_false_positives</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="n">color</span> <span class="o">=</span> <span class="s">'blue'</span>
        <span class="n">alpha</span> <span class="o">=</span> <span class="mf">0.5</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">color</span> <span class="o">=</span> <span class="s">'grey'</span>
        <span class="n">alpha</span> <span class="o">=</span> <span class="p">.</span><span class="mi">3</span>
    <span class="k">if</span> <span class="n">result</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="s">'p'</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="p">.</span><span class="mi">05</span><span class="p">:</span>
        <span class="n">false_positives</span> <span class="o">+=</span> <span class="mi">1</span>
    <span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">result</span><span class="p">[</span><span class="s">'n'</span><span class="p">],</span> <span class="n">result</span><span class="p">[</span><span class="s">'p'</span><span class="p">],</span> <span class="n">color</span><span class="o">=</span><span class="n">color</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="n">alpha</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">axhline</span><span class="p">(.</span><span class="mi">05</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'black'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Number of samples'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'P-value'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Many experiments will cross p &lt; 0.05 even when H0 is true'</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s">'False positives with full sample:'</span><span class="p">,</span> <span class="n">false_positives</span> <span class="o">/</span> <span class="n">n_simulations</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s">'False positives if early stopping is allowed:'</span><span class="p">,</span> <span class="n">early_stop_false_positives</span> <span class="o">/</span> <span class="n">n_simulations</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="plotting-the-obf-function">Plotting the OBF function</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">norm</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>

<span class="k">def</span> <span class="nf">constant_alpha</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="n">proportion_sample_collected</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">desired_final_alpha</span>

<span class="k">def</span> <span class="nf">linear_alpha_spending</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="n">proportion_sample_collected</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">proportion_sample_collected</span> <span class="o">*</span> <span class="n">desired_final_alpha</span>

<span class="k">def</span> <span class="nf">obf_alpha_spending</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="n">proportion_sample_collected</span><span class="p">):</span>
    <span class="n">z_alpha_over_2</span> <span class="o">=</span> <span class="n">norm</span><span class="p">.</span><span class="n">ppf</span><span class="p">(</span><span class="mi">1</span><span class="o">-</span><span class="n">desired_final_alpha</span><span class="o">/</span><span class="mi">2</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">2</span> <span class="o">-</span> <span class="mi">2</span><span class="o">*</span><span class="p">(</span><span class="n">norm</span><span class="p">.</span><span class="n">cdf</span><span class="p">(</span><span class="n">z_alpha_over_2</span><span class="o">/</span><span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">proportion_sample_collected</span><span class="p">)))</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">linspace</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
<span class="n">alpha</span> <span class="o">=</span> <span class="p">.</span><span class="mi">05</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="p">[</span><span class="n">constant_alpha</span><span class="p">(</span><span class="n">alpha</span><span class="p">,</span> <span class="n">pi</span><span class="p">)</span> <span class="k">for</span> <span class="n">pi</span> <span class="ow">in</span> <span class="n">p</span><span class="p">],</span> <span class="n">label</span><span class="o">=</span><span class="s">'Constant'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="p">[</span><span class="n">linear_alpha_spending</span><span class="p">(</span><span class="n">alpha</span><span class="p">,</span> <span class="n">pi</span><span class="p">)</span> <span class="k">for</span> <span class="n">pi</span> <span class="ow">in</span> <span class="n">p</span><span class="p">],</span> <span class="n">label</span><span class="o">=</span><span class="s">'Linear'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="p">[</span><span class="n">obf_alpha_spending</span><span class="p">(</span><span class="n">alpha</span><span class="p">,</span> <span class="n">pi</span><span class="p">)</span> <span class="k">for</span> <span class="n">pi</span> <span class="ow">in</span> <span class="n">p</span><span class="p">],</span> <span class="n">label</span><span class="o">=</span><span class="s">'OBF'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Proportion of sample collected'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Adjusted alpha value'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Comparison of alpha spending strategies'</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="type-i-error-comparison-of-different-alpha-spending-functions">Type I error comparison of different alpha spending functions</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">ttest_ind</span><span class="p">,</span> <span class="n">norm</span>
<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tqdm</span>

<span class="k">def</span> <span class="nf">constant_alpha</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="n">proportion_sample_collected</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">desired_final_alpha</span>

<span class="k">def</span> <span class="nf">linear_alpha_spending</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="n">proportion_sample_collected</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">proportion_sample_collected</span> <span class="o">*</span> <span class="n">desired_final_alpha</span>

<span class="k">def</span> <span class="nf">obf_alpha_spending</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="n">proportion_sample_collected</span><span class="p">):</span>
    <span class="n">z_alpha_over_2</span> <span class="o">=</span> <span class="n">norm</span><span class="p">.</span><span class="n">ppf</span><span class="p">(</span><span class="mi">1</span><span class="o">-</span><span class="n">desired_final_alpha</span><span class="o">/</span><span class="mi">2</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">2</span> <span class="o">-</span> <span class="mi">2</span><span class="o">*</span><span class="p">(</span><span class="n">norm</span><span class="p">.</span><span class="n">cdf</span><span class="p">(</span><span class="n">z_alpha_over_2</span><span class="o">/</span><span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">proportion_sample_collected</span><span class="p">)))</span>

<span class="k">def</span> <span class="nf">simulate_one</span><span class="p">(</span><span class="n">control_average</span><span class="p">,</span> <span class="n">alpha_strategies</span><span class="p">,</span> <span class="n">samples_per_day</span><span class="p">,</span> <span class="n">number_of_days</span><span class="p">,</span> <span class="n">desired_final_alpha</span><span class="p">):</span>
    <span class="n">total_sample_size</span> <span class="o">=</span> <span class="n">samples_per_day</span> <span class="o">*</span> <span class="n">number_of_days</span>
    <span class="n">results</span> <span class="o">=</span> <span class="p">{</span><span class="n">f</span><span class="p">.</span><span class="n">__name__</span><span class="p">:</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">alpha_strategies</span><span class="p">}</span>
    <span class="n">control_samples</span><span class="p">,</span> <span class="n">treatment_samples</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([]),</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([])</span>
    <span class="k">for</span> <span class="n">day</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">number_of_days</span><span class="p">):</span>
        <span class="n">control_samples</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">concatenate</span><span class="p">([</span><span class="n">control_samples</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">exponential</span><span class="p">(</span><span class="n">scale</span><span class="o">=</span><span class="n">control_average</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">samples_per_day</span><span class="p">)])</span>
        <span class="n">treatment_samples</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">concatenate</span><span class="p">([</span><span class="n">treatment_samples</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">exponential</span><span class="p">(</span><span class="n">scale</span><span class="o">=</span><span class="n">control_average</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">samples_per_day</span><span class="p">)])</span>
        <span class="k">for</span> <span class="n">alpha_strategy</span> <span class="ow">in</span> <span class="n">alpha_strategies</span><span class="p">:</span>
            <span class="n">alpha</span> <span class="o">=</span> <span class="n">alpha_strategy</span><span class="p">(</span><span class="n">desired_final_alpha</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">control_samples</span><span class="p">)</span> <span class="o">/</span> <span class="n">total_sample_size</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">ttest_ind</span><span class="p">(</span><span class="n">control_samples</span><span class="p">,</span> <span class="n">treatment_samples</span><span class="p">).</span><span class="n">pvalue</span> <span class="o">&lt;=</span> <span class="n">alpha</span><span class="p">:</span>
                <span class="n">results</span><span class="p">[</span><span class="n">alpha_strategy</span><span class="p">.</span><span class="n">__name__</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="k">return</span> <span class="n">results</span>

<span class="n">simulation_results</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">([</span><span class="n">simulate_one</span><span class="p">(</span><span class="n">control_average</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> 
                                                <span class="n">alpha_strategies</span><span class="o">=</span><span class="p">[</span><span class="n">constant_alpha</span><span class="p">,</span> <span class="n">linear_alpha_spending</span><span class="p">,</span> <span class="n">obf_alpha_spending</span><span class="p">],</span> 
                                                <span class="n">samples_per_day</span><span class="o">=</span><span class="mi">100</span><span class="p">,</span> 
                                                <span class="n">number_of_days</span><span class="o">=</span><span class="mi">30</span><span class="p">,</span> 
                                                <span class="n">desired_final_alpha</span><span class="o">=</span><span class="p">.</span><span class="mi">05</span><span class="p">)</span> <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="n">tqdm</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10000</span><span class="p">))])</span>

<span class="k">print</span><span class="p">(</span><span class="n">simulation_results</span><span class="p">.</span><span class="n">mean</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="n">simulation_results</span><span class="p">.</span><span class="nb">sum</span><span class="p">())</span>
</code></pre></div></div>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[Where it begins: The (understandable) urge to stop early]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/statsig.png" /><media:content medium="image" url="https://lmc2179.github.io/statsig.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Building your own sklearn transformer is easy and very useful</title><link href="https://lmc2179.github.io/posts/sklearn-preprocessors.html" rel="alternate" type="text/html" title="Building your own sklearn transformer is easy and very useful" /><published>2024-01-02T00:00:00+00:00</published><updated>2024-01-02T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/sklearn-preprocessors</id><content type="html" xml:base="https://lmc2179.github.io/posts/sklearn-preprocessors.html"><![CDATA[<p><em>Scikit-learn pipelines let you snap together transformations like Legos to make a Machine Learning model. The transformers included in the box with Sklearn are handy for anyone doing ML in Python, and practicing data scientists use them all the time. Even better, it’s very easy to build your own transformer, and doing so unlocks a zillion opportunities to shape your data.</em></p>

<h1 id="pipelines-make-model-specification-easy">Pipelines make model specification easy</h1>

<p>Most of the time, ML models can’t just suck in data from the world and spit predictions back out, whaterver overzealous marketers of the latest AI fad might tell you. Usually, you need a bit of careful sculpting of the input matrix in order to make sure it is usable by your favorite model. For example, you might do things like:</p>

<ul>
  <li>Scale variables by <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler">setting them from 0 to 1</a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer">normalizing them</a></li>
  <li>Encoding non-numeric values as <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html">one-hot vectors</a></li>
  <li>Generating <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.SplineTransformer.html#sklearn.preprocessing.SplineTransformer">spline features</a> for continues numeric values</li>
  <li>Running <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html">some function</a> on the inputs values, like <code class="language-plaintext highlighter-rouge">sqrt(x)</code></li>
</ul>

<p>In Python, this process is eased quite a bit by the usage of <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">Scikit-learn Pipelines</a>, which let you chain together as many preprocessing steps as you like and then treat them like one big model. The idea here is that stateful transformations are basically part of your model, so you should fit/transform them the same way you do your model. The <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html">FunctionTransformer</a> allows you to perform stateless transformations. In order to create a stateful transformations, you’ll need to write your own Transformer class - but luckily, it’s pretty easy once you have an idea of how to structure it.</p>

<h1 id="anatomy-of-an-sklearn-transformer">Anatomy of an Sklearn Transformer</h1>

<p>Creating a subclass is as easy as inheriting from <code class="language-plaintext highlighter-rouge">BaseEstimator</code> and <code class="language-plaintext highlighter-rouge">TransformerMixin</code> and writing a couple of methods which might be familiar if you’ve been using scikit-learn already:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">fit(X, y)</code>: This method takes care of any state you need to track. In the scaling example, this means computing the observed min and max of each feature, so we can scale inputs later.</li>
  <li><code class="language-plaintext highlighter-rouge">transform(X)</code>: This method applies the change. In the scaling example, this means subtracting the min value and dividing by the max, both of which were stored previously.</li>
</ul>

<p>For example, if you wanted to write a transformer that centered data by subtracting its mean (de-meaning it? that feels too mean), its <code class="language-plaintext highlighter-rouge">fit</code> and <code class="language-plaintext highlighter-rouge">transform</code> would do the following:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">fit(X, y)</code>: Calculate the average of each column (ie, take the vector average of <code class="language-plaintext highlighter-rouge">X</code>).</li>
  <li><code class="language-plaintext highlighter-rouge">transform(X)</code>: Subtract the stored average from the input vectors in <code class="language-plaintext highlighter-rouge">X</code>.</li>
</ul>

<p>Lets take a look at a couple of examples that I’ve found useful in my work.</p>

<h1 id="an-example-replace-a-rare-token-in-a-column-with-some-value">An example: Replace a rare token in a column with some value</h1>

<p>A common trick in dealing with categorical columns in ML models is to replace rare categories with a unique value that indicates “Other” or “This is a rare value”. This kind of prepreocessing would be handy to have available as a transformer, so let’s build one.</p>

<p>At init time, we’ll take in parameters from the user:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">target_column</code> - The column to scan</li>
  <li><code class="language-plaintext highlighter-rouge">min_pct</code> - Values which appear in a smaller percentage of rows than this will be considered rare</li>
  <li><code class="language-plaintext highlighter-rouge">min_count</code> - Values which appear in fewer rows than this will be considered rare. Mutually exclusive with the previous</li>
  <li><code class="language-plaintext highlighter-rouge">replacement_token</code> - The token to convert rare values to.</li>
</ul>

<p>We can sketch out the <code class="language-plaintext highlighter-rouge">fit</code> and <code class="language-plaintext highlighter-rouge">transform</code> methods:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">fit(X, y)</code>: Look at examples of <code class="language-plaintext highlighter-rouge">target_column</code> and find examples of tokens with less than <code class="language-plaintext highlighter-rouge">min_pct</code> or <code class="language-plaintext highlighter-rouge">min_count</code>. Store them in the object’s state.</li>
  <li><code class="language-plaintext highlighter-rouge">transform(X)</code>: Look at the <code class="language-plaintext highlighter-rouge">target_column</code>, and replace all the known rare tokens with the replacement token.</li>
</ul>

<p>Here’s what that looks like in code as a transformer subclass:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">RareTokenTransformer</span><span class="p">(</span><span class="n">BaseEstimator</span><span class="p">,</span> <span class="n">TransformerMixin</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">target_column</span><span class="p">,</span> <span class="n">min_pct</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">min_count</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">replacement_token</span><span class="o">=</span><span class="s">'__RARE__'</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">target_column</span> <span class="o">=</span> <span class="n">target_column</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">min_pct</span> <span class="ow">and</span> <span class="n">min_count</span><span class="p">)</span> <span class="ow">or</span> <span class="p">(</span><span class="ow">not</span> <span class="n">min_pct</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">min_count</span><span class="p">):</span>
            <span class="k">raise</span> <span class="nb">Exception</span><span class="p">(</span><span class="s">"Please provide either min_pct or min_count, not both"</span><span class="p">)</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">min_pct</span> <span class="o">=</span> <span class="n">min_pct</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">min_count</span> <span class="o">=</span> <span class="n">min_count</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">replacement_token</span> <span class="o">=</span> <span class="n">replacement_token</span>
    
    <span class="k">def</span> <span class="nf">fit</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="n">counts</span> <span class="o">=</span> <span class="n">X</span><span class="p">[</span><span class="bp">self</span><span class="p">.</span><span class="n">target_column</span><span class="p">].</span><span class="n">value_counts</span><span class="p">()</span>
        <span class="k">if</span> <span class="bp">self</span><span class="p">.</span><span class="n">min_count</span><span class="p">:</span>
            <span class="n">rare_tokens</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">counts</span><span class="p">.</span><span class="n">index</span><span class="p">[</span><span class="n">counts</span> <span class="o">&lt;=</span> <span class="bp">self</span><span class="p">.</span><span class="n">min_count</span><span class="p">])</span>
        <span class="k">if</span> <span class="bp">self</span><span class="p">.</span><span class="n">min_pct</span><span class="p">:</span>
            <span class="n">pcts</span> <span class="o">=</span> <span class="n">X</span><span class="p">[</span><span class="bp">self</span><span class="p">.</span><span class="n">target_column</span><span class="p">].</span><span class="n">value_counts</span><span class="p">()</span> <span class="o">/</span> <span class="n">counts</span><span class="p">.</span><span class="nb">sum</span><span class="p">()</span>
            <span class="n">rare_tokens</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">pcts</span><span class="p">.</span><span class="n">index</span><span class="p">[</span><span class="n">pcts</span> <span class="o">&lt;=</span> <span class="bp">self</span><span class="p">.</span><span class="n">min_pct</span><span class="p">])</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">rare_tokens</span> <span class="o">=</span> <span class="n">rare_tokens</span>
        <span class="k">return</span> <span class="bp">self</span>
    
    <span class="k">def</span> <span class="nf">transform</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">X</span><span class="p">):</span>
        <span class="n">X_copy</span> <span class="o">=</span> <span class="n">X</span><span class="p">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="n">X_copy</span><span class="p">[</span><span class="bp">self</span><span class="p">.</span><span class="n">target_column</span><span class="p">]</span> <span class="o">=</span> <span class="n">X_copy</span><span class="p">[</span><span class="bp">self</span><span class="p">.</span><span class="n">target_column</span><span class="p">].</span><span class="n">replace</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">rare_tokens</span><span class="p">,</span> <span class="bp">self</span><span class="p">.</span><span class="n">replacement_token</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">X_copy</span>
</code></pre></div></div>

<p>Let’s try it on a real dataframe.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">X1</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'numeric_col'</span><span class="p">:</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span> <span class="s">'categorical_col'</span><span class="p">:</span> <span class="p">[</span><span class="s">'A'</span><span class="p">,</span> <span class="s">'A'</span><span class="p">,</span> <span class="s">'A'</span><span class="p">,</span> <span class="s">'B'</span><span class="p">,</span> <span class="s">'C'</span><span class="p">]})</span>
<span class="n">X2</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'numeric_col'</span><span class="p">:</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span> <span class="s">'categorical_col'</span><span class="p">:</span> <span class="p">[</span><span class="s">'C'</span><span class="p">,</span> <span class="s">'A'</span><span class="p">,</span> <span class="s">'B'</span><span class="p">,</span> <span class="s">'A'</span><span class="p">,</span> <span class="s">'A'</span><span class="p">]})</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">RareTokenTransformer</span><span class="p">(</span><span class="s">'categorical_col'</span><span class="p">,</span> <span class="n">min_pct</span><span class="o">=</span><span class="mf">0.2</span><span class="p">)</span>
<span class="n">t</span><span class="p">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X1</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">t</span><span class="p">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X1</span><span class="p">).</span><span class="n">to_markdown</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="n">t</span><span class="p">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X2</span><span class="p">).</span><span class="n">to_markdown</span><span class="p">())</span>
</code></pre></div></div>

<p>This gives us the expected <code class="language-plaintext highlighter-rouge">X1</code>:</p>

<table>
  <thead>
    <tr>
      <th style="text-align: right"> </th>
      <th style="text-align: right">numeric_col</th>
      <th style="text-align: left">categorical_col</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
      <td style="text-align: left">A</td>
    </tr>
    <tr>
      <td style="text-align: right">1</td>
      <td style="text-align: right">1</td>
      <td style="text-align: left">A</td>
    </tr>
    <tr>
      <td style="text-align: right">2</td>
      <td style="text-align: right">2</td>
      <td style="text-align: left">A</td>
    </tr>
    <tr>
      <td style="text-align: right">3</td>
      <td style="text-align: right">3</td>
      <td style="text-align: left"><strong>RARE</strong></td>
    </tr>
    <tr>
      <td style="text-align: right">4</td>
      <td style="text-align: right">4</td>
      <td style="text-align: left"><strong>RARE</strong></td>
    </tr>
  </tbody>
</table>

<p>And <code class="language-plaintext highlighter-rouge">X2</code>:</p>

<table>
  <thead>
    <tr>
      <th style="text-align: right"> </th>
      <th style="text-align: right">numeric_col</th>
      <th style="text-align: left">categorical_col</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
      <td style="text-align: left"><strong>RARE</strong></td>
    </tr>
    <tr>
      <td style="text-align: right">1</td>
      <td style="text-align: right">1</td>
      <td style="text-align: left">A</td>
    </tr>
    <tr>
      <td style="text-align: right">2</td>
      <td style="text-align: right">2</td>
      <td style="text-align: left"><strong>RARE</strong></td>
    </tr>
    <tr>
      <td style="text-align: right">3</td>
      <td style="text-align: right">3</td>
      <td style="text-align: left">A</td>
    </tr>
    <tr>
      <td style="text-align: right">4</td>
      <td style="text-align: right">4</td>
      <td style="text-align: left">A</td>
    </tr>
  </tbody>
</table>

<h1 id="a-borrowed-example-combining-patsy-and-sklearn">A borrowed example: Combining patsy and sklearn</h1>

<p>One of the few flaws of Scikit-learn is that it doesn’t include out-of-the-box support for <a href="https://patsy.readthedocs.io/en/latest/">Patsy</a>. Patsy is a library that lets you easily specify design matrices with a single string. <a href="https://www.statsmodels.org/dev/example_formulas.html">Statsmodels</a> allows you to fit models specified using Patsy strings, but Statsmodels only really covers generalized linear models.</p>

<p>It would be really handy to be able to use scikit-learn models with Patsy. A <a href="https://juanitorduz.github.io/formula_transformer/"><code class="language-plaintext highlighter-rouge">FormulaTransformer</code> is implemented by Dr. Juan Camilo Orduz on his blog</a> that does just that - I’ve borrowed his idea here and modified it to make it stateful.</p>

<p>This transformer will include the following <code class="language-plaintext highlighter-rouge">fit</code> and <code class="language-plaintext highlighter-rouge">transform</code> steps:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">fit(X, y)</code>: Compute the <code class="language-plaintext highlighter-rouge">design_info</code> based on the specified formula and <code class="language-plaintext highlighter-rouge">X</code>. For example, Patsy needs to keep track of which columns are categorical and which are numeric.</li>
  <li><code class="language-plaintext highlighter-rouge">transform(X)</code>: Run <code class="language-plaintext highlighter-rouge">patsy.dmatrix</code> using the <code class="language-plaintext highlighter-rouge">design_info</code> to generate the transformed version of <code class="language-plaintext highlighter-rouge">X</code>.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">patsy</span>
<span class="kn">from</span> <span class="nn">sklearn.base</span> <span class="kn">import</span> <span class="n">BaseEstimator</span><span class="p">,</span> <span class="n">TransformerMixin</span>

<span class="k">class</span> <span class="nc">FormulaTransformer</span><span class="p">(</span><span class="n">BaseEstimator</span><span class="p">,</span> <span class="n">TransformerMixin</span><span class="p">):</span>
    <span class="c1"># Adapted from https://juanitorduz.github.io/formula_transformer/
</span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">formula</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">formula</span> <span class="o">=</span> <span class="n">formula</span>
    
    <span class="k">def</span> <span class="nf">fit</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="n">dm</span> <span class="o">=</span> <span class="n">patsy</span><span class="p">.</span><span class="n">dmatrix</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">formula</span><span class="p">,</span> <span class="n">X</span><span class="p">)</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">design_info</span> <span class="o">=</span> <span class="n">dm</span><span class="p">.</span><span class="n">design_info</span>
        <span class="k">return</span> <span class="bp">self</span>
    
    <span class="k">def</span> <span class="nf">transform</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">X</span><span class="p">):</span>
        <span class="n">X_formula</span> <span class="o">=</span> <span class="n">patsy</span><span class="p">.</span><span class="n">dmatrix</span><span class="p">(</span><span class="n">formula_like</span><span class="o">=</span><span class="bp">self</span><span class="p">.</span><span class="n">formula</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">X</span><span class="p">)</span>
        <span class="n">columns</span> <span class="o">=</span> <span class="n">X_formula</span><span class="p">.</span><span class="n">design_info</span><span class="p">.</span><span class="n">column_names</span>
        <span class="n">X_formula</span> <span class="o">=</span> <span class="n">patsy</span><span class="p">.</span><span class="n">build_design_matrices</span><span class="p">([</span><span class="bp">self</span><span class="p">.</span><span class="n">design_info</span><span class="p">],</span> <span class="n">X</span><span class="p">,</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dataframe'</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">X_formula</span>
</code></pre></div></div>

<p>Lets take a look at how this transforms an actual dataframe. We’ll use input matrices with one numeric and one categorical column. We’ll square the numeric column, and one-hot encode the categorical one.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="n">pd</span><span class="p">.</span><span class="n">set_option</span><span class="p">(</span><span class="s">'display.max_columns'</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>

<span class="n">X1</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'numeric_col'</span><span class="p">:</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="s">'categorical_col'</span><span class="p">:</span> <span class="p">[</span><span class="s">'A'</span><span class="p">,</span> <span class="s">'B'</span><span class="p">,</span> <span class="s">'C'</span><span class="p">]})</span>
<span class="n">X2</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'numeric_col'</span><span class="p">:</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="s">'categorical_col'</span><span class="p">:</span> <span class="p">[</span><span class="s">'C'</span><span class="p">,</span> <span class="s">'A'</span><span class="p">,</span> <span class="s">'B'</span><span class="p">]})</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">FormulaTransformer</span><span class="p">(</span><span class="s">'np.power(numeric_col, 2) + categorical_col - 1'</span><span class="p">)</span>
<span class="n">t</span><span class="p">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X1</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">t</span><span class="p">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X1</span><span class="p">).</span><span class="n">to_markdown</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="n">t</span><span class="p">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X2</span><span class="p">).</span><span class="n">to_markdown</span><span class="p">())</span>
</code></pre></div></div>
<p>This shows us what we expect, namely that <code class="language-plaintext highlighter-rouge">X1</code> is:</p>

<table>
  <thead>
    <tr>
      <th style="text-align: right"> </th>
      <th style="text-align: right">categorical_col[A]</th>
      <th style="text-align: right">categorical_col[B]</th>
      <th style="text-align: right">categorical_col[C]</th>
      <th style="text-align: right">np.power(numeric_col, 2)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: right">0</td>
      <td style="text-align: right">1</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
    </tr>
    <tr>
      <td style="text-align: right">1</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">1</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">1</td>
    </tr>
    <tr>
      <td style="text-align: right">2</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">1</td>
      <td style="text-align: right">4</td>
    </tr>
  </tbody>
</table>

<p>And that <code class="language-plaintext highlighter-rouge">X2</code> is:</p>

<table>
  <thead>
    <tr>
      <th style="text-align: right"> </th>
      <th style="text-align: right">categorical_col[A]</th>
      <th style="text-align: right">categorical_col[B]</th>
      <th style="text-align: right">categorical_col[C]</th>
      <th style="text-align: right">np.power(numeric_col, 2)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">1</td>
      <td style="text-align: right">0</td>
    </tr>
    <tr>
      <td style="text-align: right">1</td>
      <td style="text-align: right">1</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">1</td>
    </tr>
    <tr>
      <td style="text-align: right">2</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">1</td>
      <td style="text-align: right">0</td>
      <td style="text-align: right">4</td>
    </tr>
  </tbody>
</table>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[Scikit-learn pipelines let you snap together transformations like Legos to make a Machine Learning model. The transformers included in the box with Sklearn are handy for anyone doing ML in Python, and practicing data scientists use them all the time. Even better, it’s very easy to build your own transformer, and doing so unlocks a zillion opportunities to shape your data.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/transformer.png" /><media:content medium="image" url="https://lmc2179.github.io/transformer.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Elasticity and log-log models for practicing data scientists</title><link href="https://lmc2179.github.io/posts/isoelastic.html" rel="alternate" type="text/html" title="Elasticity and log-log models for practicing data scientists" /><published>2023-12-12T00:00:00+00:00</published><updated>2023-12-12T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/isoelastic</id><content type="html" xml:base="https://lmc2179.github.io/posts/isoelastic.html"><![CDATA[<p><em>Models of <a href="https://en.wikipedia.org/wiki/Elasticity_(economics)">elasticity</a> and log-log relationships seem to show up over and over in my work. Since I have only a fuzzy, gin-soaked memory of Econ 101, I always have to remind myself of the properties of these models. The commonly used  $y = \alpha x ^\beta$  version of this model ends up being pretty easy to interpret, and has wide applicabilty across many domains that actual data scientists work.</em></p>

<h1 id="its-everywhere">It’s everywhere!</h1>

<p>I have spent a shocking percentage of my career drawing some version of this diagram on a whiteboard:</p>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/important_relationship.png" alt="image" /></p>

<p>This relationship has a few key aspects that I notice over and over again:</p>
<ul>
  <li>The output increases when more input is added; the line slopes up.</li>
  <li>Each input added is less efficient than the last; the slope is decreasing.</li>
  <li>Inputs and outputs are both positive</li>
</ul>

<p>There’s also a downward-sloping variant, and a lot of the same analysis goes into that as well.</p>

<p>If you’re an economist, or even if you just took econ 101, you likely recognize this. It’s common to model this kind of relationship as $y = ax^b$, a function which has “<a href="https://en.wikipedia.org/wiki/Isoelastic_function">constant elasticity</a>”, meaning an percent change in input produces the same percent change in output regardless of where you are in the input space. A common example is the <a href="https://en.wikipedia.org/wiki/Cobb%E2%80%93Douglas_production_function">Cobb-Douglas production function</a>. The most common examples all seem to be related to price, such as how changes in price affect the amount demanded or supplied.</p>

<p>Lots and lots and <em>lots</em> of measured variables seem to have this relationship. In my own career I’ve seen this shape of input-output relationship show up over and over, even outside the price examples:</p>
<ul>
  <li>Marketing spend and impressions</li>
  <li>Number of users who see something vs the number who engage with it</li>
  <li>Number of samples vs model quality</li>
  <li>Time spent on a project and quality of result</li>
  <li>Size of an investment vs revenue generated (this one was popularized and explored by <a href="https://en.wikipedia.org/wiki/Tendency_of_the_rate_of_profit_to_fall">a well known early data scientist</a>)</li>
</ul>

<p>To get some intuition, lets look at some examples of how different values of $\alpha$ and $\beta$ affect the shape of this function:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">linspace</span><span class="p">(.</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
  <span class="k">return</span> <span class="n">a</span><span class="o">*</span><span class="n">x</span><span class="o">**</span><span class="n">b</span>

<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Examples of ax^b'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'a=1,b=0.5'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">1.5</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'a=1,b=1.5'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'a=1,b=1.0'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'a=2,b=0.5'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mf">1.5</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'a=2,b=1.5'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'a=2,b=1.0'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://github.com/lmc2179/lmc2179.github.io/assets/1301965/03d1c910-9806-4f9f-b9fe-0d8da56161e9" alt="image" /></p>

<p>By and large, we see that $\alpha$ and $\beta$ are the analogues of the intercept and slope, that is</p>
<ul>
  <li>$\alpha$ affects the vertical scale, or where the curve is anchored when $x=0$</li>
  <li>$\beta$ affects the curvature (when $\beta &lt; 1$,  there are diminishing returns; when $\beta &gt; 1$ increasing returns, when $\beta = 0$ then it’s linear). When it’s negative, the slope is downward.</li>
</ul>

<p>Nonetheless, I am not an economist (though I’ve had the pleasure of working with plenty of brilliant people with economics training). If you’re like me, then you might not have these details close to hand. This post is meant to be a small primer for anyone who needs to build models with these kinds of functions.</p>

<p>We usually want to know this relationship so we can answer some practical questions such as:</p>
<ul>
  <li>How much input will we need to add in order to reach our desired level of output?</li>
  <li>If we have some free capital, material, or time to spend, what will we get for it? Should we use it here or somewhere else?</li>
  <li>When will it become inefficient to add more input, ie when will the value of the marginal input be less than the marginal output?</li>
</ul>

<p>Let’s look at the $ \alpha x ^\beta$  model in detail.</p>

<h1 id="some-useful-facts-about-the-y--alpha-x-beta-model">Some useful facts about the $y = \alpha x ^\beta$ model</h1>

<h2 id="it-makes-it-easy-to-talk-about--change-in-input-vs--change-in-output">It makes it easy to talk about % change in input vs % change in output</h2>

<p>One of the many reasons that the common OLS model $y = \alpha + \beta x$ is so popular is that it lets us make a very succinct statement about the relationship between $x$ and $y$: “A one-unit increase in $x$ is associated with an increase of $\beta$ units of $y$.” What’s the equivalent to this for our model $y = \alpha x ^ \beta$?</p>

<p>The interpretation of this model is a little different than the usual OLS model. Instead, we’ll ask: how does <strong>multiplying</strong> the input <strong>multiply</strong> the output? That is, how do percent changes in $x$ produce percent changes in $y$? For example, we might wonder what happens when we increase the input by 10%, ie multiplying it by 1.1. Lets see how multiplying the input by $m$ creates a multiplier on the output:</p>

<p>$\frac{f(xm)}{f(x)} = \frac{\alpha (xm)^\beta}{\alpha x ^ \beta} = m^\beta$</p>

<p>That means for this model, we can summarize changes between variables as:</p>

<blockquote>
  <p>Under this model, multiplying the input by <em>m</em> multiplies the output by $m^\beta$.</p>
</blockquote>

<p>Or, if you are percentage afficionado:</p>

<blockquote>
  <p>Under this model, changing the input by $p\%$ changes the output output by $(1+p\%)^\beta$.</p>
</blockquote>

<h2 id="its-easy-to-fit-with-ols">It’s easy to fit with OLS</h2>

<p>Another reason that the OLS model is so popular is because it is easy to estimate in practice. The OLS model may not always be true, but it is often easy to estimate it, and it might tell us something interesting even if it isn’t correct. Some basic algebra lets us turn our model into one we can fit with OLS. Starting with our model:</p>

<p>$y = \alpha x^\beta$</p>

<p>Taking the logarithm of both sides:</p>

<p>$log \ y = log \ \alpha + \beta \  log \ x$</p>

<p>This model is linear in $log \ x$, so we can now use OLS to calculate the coefficients! Just don’t forget to $exp$ the intercept to get $\alpha$ on the right scale.</p>

<h2 id="we-can-use-it-to-solve-for-input-if-we-know-the-desired-level-of-output">We can use it to solve for input if we know the desired level of output</h2>

<p>In practical settings, we often start with the desired quantity of output, and then try to understand if the required input is available or feasible. It’s handy to have a closed form which inverts our model:</p>

<p>$f^{-1}(y) = (y/\alpha)^{\frac{1}{\beta}}$</p>

<p>If we want to know how a <strong>change</strong> in the output will require <strong>change</strong> in the input, we look at how multiplying the output by $m$ changes the required value of $x$:</p>

<p>$\frac{f^{-1}(ym)}{f^{-1}(y)} = m^{\frac{1}{\beta}}$</p>

<p>That means if our goal is to multiply the output by $m$ we need to multiply the input by $m^{\frac{1}{\beta}}$.</p>

<h1 id="an-example-lotsize-vs-house-price">An example: Lotsize vs house price</h1>

<p>Let’s look at how this relationship might be estimated on a real data set. Here, we’ll use a data set of house prices along with the size of the lot they sit on. The question of how lot size relates to house price has a bunch of the features we expect, namely:</p>
<ul>
  <li>The slope is positive - all other things equal, we’d expect bigger lots to sell for more.</li>
  <li>Each input added is less efficient than the last; adding more to an already large lot probably doesn’t change the price much.</li>
  <li>Lot-size and price are both positive.</li>
</ul>

<p>Lets grab the data:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="n">sns</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span> 
<span class="kn">from</span> <span class="nn">statsmodels.api</span> <span class="kn">import</span> <span class="n">formula</span> <span class="k">as</span> <span class="n">smf</span>

<span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s">'https://vincentarelbundock.github.io/Rdatasets/csv/AER/HousePrices.csv'</span><span class="p">)</span>
<span class="n">df</span> <span class="o">=</span> <span class="n">df</span><span class="p">.</span><span class="n">sort_values</span><span class="p">(</span><span class="s">'lotsize'</span><span class="p">)</span>
</code></pre></div></div>

<p>We’ll fit our log-log model and plot it:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">model</span> <span class="o">=</span> <span class="n">smf</span><span class="p">.</span><span class="n">ols</span><span class="p">(</span><span class="s">'np.log(price) ~ np.log(lotsize)'</span><span class="p">,</span> <span class="n">df</span><span class="p">).</span><span class="n">fit</span><span class="p">()</span>

<span class="n">plt</span><span class="p">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'lotsize'</span><span class="p">],</span> <span class="n">df</span><span class="p">[</span><span class="s">'price'</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'lotsize'</span><span class="p">],</span> <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">model</span><span class="p">.</span><span class="n">fittedvalues</span><span class="p">),</span> <span class="n">color</span><span class="o">=</span><span class="s">'orange'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Log-log model'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Lot Size vs House Price'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Lot Size'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'House Price'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">tight_layout</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://github.com/lmc2179/lmc2179.github.io/assets/1301965/9e1e7e67-7f07-41c6-ad4e-8b0389a84539" alt="image" /></p>

<p>Okay, looks good so far. This seems like a plausible model for this case. Let’s double check it by looking at it on the log scale:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'lotsize'</span><span class="p">],</span> <span class="n">df</span><span class="p">[</span><span class="s">'price'</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'lotsize'</span><span class="p">],</span> <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">model</span><span class="p">.</span><span class="n">fittedvalues</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'Log-log model'</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'orange'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xscale</span><span class="p">(</span><span class="s">'log'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">yscale</span><span class="p">(</span><span class="s">'log'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'LogLot Size vs Log House Price'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Log Lot Size'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Log House Price'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">tight_layout</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://github.com/lmc2179/lmc2179.github.io/assets/1301965/fa83fa55-dd2a-4ecd-a9de-a08b0ea815f4" alt="image" /></p>

<p>Nice. When we log-ify everything, it looks like a textbook regression example.</p>

<p>Okay, let’s interpret this model. Lets convert the point estimate of $\beta$ into an estimate of percent change:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">b</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="n">params</span><span class="p">[</span><span class="s">'np.log(lotsize)'</span><span class="p">]</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">model</span><span class="p">.</span><span class="n">params</span><span class="p">[</span><span class="s">'Intercept'</span><span class="p">])</span>
<span class="k">print</span><span class="p">(</span><span class="s">'1% increase in lotsize --&gt;'</span><span class="p">,</span> <span class="nb">round</span><span class="p">(</span><span class="mi">100</span><span class="o">*</span><span class="p">(</span><span class="mf">1.01</span><span class="o">**</span><span class="n">b</span><span class="o">-</span><span class="mi">1</span><span class="p">),</span> <span class="mi">2</span><span class="p">),</span> <span class="s">'% increase in price'</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s">'2% increase in lotsize --&gt;'</span><span class="p">,</span> <span class="nb">round</span><span class="p">(</span><span class="mi">100</span><span class="o">*</span><span class="p">(</span><span class="mf">1.02</span><span class="o">**</span><span class="n">b</span><span class="o">-</span><span class="mi">1</span><span class="p">),</span> <span class="mi">2</span><span class="p">),</span> <span class="s">'% increase in price'</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s">'10% increase in lotsize --&gt;'</span><span class="p">,</span> <span class="nb">round</span><span class="p">(</span><span class="mi">100</span><span class="o">*</span><span class="p">(</span><span class="mf">1.10</span><span class="o">**</span><span class="n">b</span><span class="o">-</span><span class="mi">1</span><span class="p">),</span> <span class="mi">2</span><span class="p">),</span> <span class="s">'% increase in price'</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1% increase in lotsize --&gt; 0.54 % increase in price
2% increase in lotsize --&gt; 1.08 % increase in price
10% increase in lotsize --&gt; 5.3 % increase in price
</code></pre></div></div>

<p>We see that relatively, price increases more slowly than lotsize.</p>

<h1 id="does-this-model-really-describe-reality-a-reminder-that-a-convenient-model-need-not-be-the-correct-model">Does this model really describe reality? A reminder that a convenient model need not be the correct model</h1>

<p>The above set of tips and tricks is, when you get down to it, mostly algebra. It’s useful algebra to be sure, but it is really just repeated manipulation of the functional form $\alpha x ^ \beta$. It turns out that that functional form is both a priori plausible for lots of relationships, and is easy to work with.</p>

<p>However, we should not mistake analytical convenience for truth. We should recognize that assuming a particular functional form comes with risks, so we should spend some time:</p>
<ul>
  <li>Demonstrating that this functional form is a good fit for the data at hand by doing regression diagnostics like residual plots</li>
  <li>Understanding how far off our model’s predictions and prediction intervals are from the truth by doing cross-validation</li>
  <li>Making sure we’re clear on what causal assumptions we’re making, if we’re going to consider counterfactuals</li>
</ul>

<p>This is always good practice, of course - but it’s easy to forget about it once you have a particular model that is convenient to work with.</p>

<h1 id="some-alternatives-to-the-model-weve-been-using">Some alternatives to the model we’ve been using</h1>

<p>As I mentioned above, the log-log model isn’t the only game in town.</p>

<p>For one, we’ve assumed that the “true” function should have constant elasticity. But that need not be true; we could imagine taking some other function and computing its <a href="https://en.wikipedia.org/wiki/Elasticity_of_a_function">point elasticity</a> in one spot, or its <a href="https://en.wikipedia.org/wiki/Arc_elasticity">arc elasticity</a> between two points.</p>

<p>What about alternatives to $y = \alpha x^\beta$ and the log-log model?</p>
<ul>
  <li>If you just want a model that is non-decreasing or non-increasing, you could try <a href="https://scikit-learn.org/stable/modules/generated/sklearn.isotonic.IsotonicRegression.html">non-parametric isotonic regression</a>.</li>
  <li>You could pick a different transformation other than log, like a square root. This also works when there are zeros, whereas $log(0)$ is undefined.</li>
  <li>Another possible transformation is <a href="https://worthwhile.typepad.com/worthwhile_canadian_initi/2011/07/a-rant-on-inverse-hyperbolic-sine-transformations.html">Inverse Hyperbolic Sine</a>, which also has an <a href="https://marcfbellemare.com/wordpress/wp-content/uploads/2019/02/BellemareWichmanIHSFebruary2019.pdf">elasticity interpreation</a>.</li>
</ul>

<h1 id="appendix-estimating-when-you-have-only-two-data-points">Appendix: Estimating when you have only two data points</h1>

<p>Occasionally I’ve gone and computed an observed elasticity by fitting the model from a single pair of observations. This isn’t often all that useful, but I’ve included it here in case you find it helpful.</p>

<p>Lets imagine we have only two data points, which we’ll call $x_1, y_1, x_2, y_2$. Then, we have two equations and two unknowns, that is:</p>

\[y_1 = \alpha x_1^\beta\]

\[y_2 = \alpha x_2^\beta\]

<p>If we do some algebra, we can come up with estimates for each variable:</p>

\[\beta = \frac{log \ y_1 - log \ y_2}{log \ x_1 - log \ x_2}\]

\[\alpha = exp(log \ y_1 + \beta \ log \ x_1)\]

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="k">def</span> <span class="nf">solve</span><span class="p">(</span><span class="n">x1</span><span class="p">,</span> <span class="n">x2</span><span class="p">,</span> <span class="n">y1</span><span class="p">,</span> <span class="n">y2</span><span class="p">):</span>
    <span class="c1"># y1 = a*x1**b
</span>    <span class="c1"># y2 = a*x2**b
</span>    <span class="n">log_x1</span><span class="p">,</span> <span class="n">log_x2</span><span class="p">,</span> <span class="n">log_y1</span><span class="p">,</span> <span class="n">log_y2</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">x1</span><span class="p">),</span> <span class="n">np</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">x2</span><span class="p">),</span> <span class="n">np</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">y1</span><span class="p">),</span> <span class="n">np</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">y2</span><span class="p">)</span>
    <span class="n">b</span> <span class="o">=</span> <span class="p">(</span><span class="n">log_y1</span> <span class="o">-</span> <span class="n">log_y2</span><span class="p">)</span> <span class="o">/</span> <span class="p">(</span><span class="n">log_x1</span> <span class="o">-</span> <span class="n">log_x2</span><span class="p">)</span>
    <span class="n">log_a</span> <span class="o">=</span> <span class="n">log_y1</span> <span class="o">+</span> <span class="n">b</span><span class="o">*</span><span class="n">log_x1</span>
    <span class="k">return</span> <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">log_a</span><span class="p">),</span> <span class="n">b</span>
</code></pre></div></div>

<p>Then, we can run an example like this one in which a 1% increase in $x$ leads to a 50% increase in $y$:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">solve</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mf">1.01</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">1.5</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="mf">1.01</span><span class="o">**</span><span class="n">b</span><span class="p">)</span>
</code></pre></div></div>

<p>Which shows us <code class="language-plaintext highlighter-rouge">a=1.0, b=40.74890715609402, 1.01^b=1.5</code>.</p>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[Models of elasticity and log-log relationships seem to show up over and over in my work. Since I have only a fuzzy, gin-soaked memory of Econ 101, I always have to remind myself of the properties of these models. The commonly used $y = \alpha x ^\beta$ version of this model ends up being pretty easy to interpret, and has wide applicabilty across many domains that actual data scientists work.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/important_relationship.png" /><media:content medium="image" url="https://lmc2179.github.io/important_relationship.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Is my regression model good enough to make decisions? Evaluating actual vs predicted plots and relative error of regression models</title><link href="https://lmc2179.github.io/posts/seychelles.html" rel="alternate" type="text/html" title="Is my regression model good enough to make decisions? Evaluating actual vs predicted plots and relative error of regression models" /><published>2023-09-24T00:00:00+00:00</published><updated>2023-09-24T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/seychelles</id><content type="html" xml:base="https://lmc2179.github.io/posts/seychelles.html"><![CDATA[<p>We use predictive models as our advisors, helping us make better decisions using their output. A reasonable question, then, is “is my model accurate enough to be useful”? An already-present part of the process for most ML practitioners is Cross Validation, that beloved Swiss Army Knife of model validation. Anyone doing their due diligence when training a predictive model will try a few out, and select the one with the minimum Mean Squared Error, or perhaps use the <a href="https://lmc2179.github.io/posts/cvci.html">one standard error rule</a>. Either way, you’ll look at some out-of-sample errors for different models.</p>

<p>This doesn’t usually answer our question, though. Model selection tells us which choice is the best among the available options, but it’s unclear whether even the best one is actually good enough to be useful. I myself have had the frustrating experience of performing an in-depth model selection process, only to realize at the end that all my careful optimizing has given me a model which is better than the baseline, but still so bad at predicting that it is unusable for any practical purpose.</p>

<p>So, back to our question. What does “accurate enough to be useful” mean, exactly? How do we know if we’re there?</p>

<p>We could try imposing a rule of thumb like “your MSE must be this small”, but this seems to require context. After all, different tasks require different levels of precision in the real world - this is why dentists do not (except in extreme situations) use jackhammers, preferring tools with a diameter measured in millimeters.</p>

<p>Statistical measures of model or coefficient significance don’t seem to help either; knowing that a given coefficient (or all of them) are statistically significantly different from zero is handy, but does not tell us that the model is ready for prime time. Even the legendary $R^2$ doesn’t really have a clear a priori “threshold of good enough” (though surprisingly, I see to frequently run into people who are willing to do so, often claiming 80% or 90% as if their model is trying to make the Honor Roll this semester). If you’re used to using $R^2$, a perspective I found really helpful is Ch. 10 of Cosma Shalizi’s <a href="https://www.stat.cmu.edu/~cshalizi/TALR/TALR.pdf">The Truth About Linear Regression</a>.</p>

<p>An actual viable method is to look at whether your prediction intervals are both practically precise enough for the task and also cover the data, an approach detailed <a href="https://statisticsbyjim.com/regression/how-high-r-squared/">here</a>. This is a perfectly sensible choice if your model provides you with an easy way to compute prediction intervals. However, if you’re using something like scikit-learn you’ll usually be creating just a single point estimate (ie, a single fitted model of $\mathbb{E}[y \mid X]$ which you can deploy), and it may not be easy to generate prediction intervals for your model.</p>

<p>The method that I’ve found most effective is to work with my stakeholders and try to determine <strong>what size of relative (percent) error would be good enough for decision making</strong>, and then see how often the model predictions meet that requirement. Usually, I ask a series of questions like:</p>
<ul>
  <li>Imagine the model was totally accurate and precise, ie it hit the real value 100% of the time. What would that let us do? What value would that success bring us in terms of outcomes? Presumably, there is a clear answer here, and this would let us increase output, sell more products, or something else we want.</li>
  <li>Now imagine that the model’s accuracy was off by a little bit, say 5%. Would you still be able to achieve the desired outcome?</li>
  <li>If so, what if it was 10%? 20%? How large could the error be and still allow you to achieve your desired outcome?</li>
  <li>Take this threshold, and consider every prediction within it to be a “hit”, and everything else is a “miss”. In that case, we can evaluate the model’s practical usefulness by seeing how often it produces a hit.</li>
</ul>

<p>This allows us to take our error measure, which is a continuous number, and discretize it. We could add more categories by defining what it means to have a “direct hit”, a “near miss”, a “bad miss” etc. You could then attach a predicted outcome to each of those discrete categories, and you’ve learned something not just about how the model makes <strong>predictions</strong>, but how it lets you make <strong>decisions</strong>. In this sense, it’s the regression-oriented sequel to our previous discussion about <a href="https://lmc2179.github.io/posts/decisions.html">analyzing the confusion matrix</a> for classifiers - we go from pure regression analysis to decision analysis using a diagnostic. The “direct hits” for a regression model are like landing in the main diagonal of the confusion matrix.</p>

<p>In a sense, this is a check of the model’s “calibration quality”. While I usually hear that term referring to <a href="https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html">probability calibration</a>, I think it’s relevant here too. In the regression setting, a model is “well calibrated” when its prediction are at or near the actual value. We’ll plot the regression equivalent of the calibration curve, and highlight the region that counts as a good enough fit.</p>

<p>Let’s do a quick example using this <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_california_housing.html">dataset of California House Prices along with their attributes</a>. Imagine that you’re planning on using this to figure out what the potential price of your house might be when you sell it; you want to know how much you might get for it so you can figure out how to budget for your other purchases. We’ll use a Gradient Boosting model, but that’s not especially important - whatever black-box method you’re using should work.</p>

<p>First, lets get all our favorite toys out of the closet, grabbing our data and desired model:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">cross_val_predict</span>
<span class="kn">from</span> <span class="nn">sklearn.ensemble</span> <span class="kn">import</span> <span class="n">HistGradientBoostingRegressor</span>
<span class="kn">from</span> <span class="nn">sklearn.datasets</span> <span class="kn">import</span> <span class="n">fetch_california_housing</span>

<span class="n">california_housing</span> <span class="o">=</span> <span class="n">fetch_california_housing</span><span class="p">(</span><span class="n">as_frame</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">california_housing</span><span class="p">.</span><span class="n">frame</span>

<span class="n">input_features</span> <span class="o">=</span> <span class="p">[</span><span class="s">'MedInc'</span><span class="p">,</span> <span class="s">'HouseAge'</span><span class="p">,</span> <span class="s">'AveRooms'</span><span class="p">,</span> <span class="s">'AveBedrms'</span><span class="p">,</span> <span class="s">'Population'</span><span class="p">,</span> <span class="s">'AveOccup'</span><span class="p">,</span> <span class="s">'Latitude'</span><span class="p">,</span> <span class="s">'Longitude'</span><span class="p">]</span>
<span class="n">target_variable</span> <span class="o">=</span> <span class="s">'MedHouseVal'</span>

<span class="n">X</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">input_features</span><span class="p">]</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">target_variable</span><span class="p">]</span>

<span class="n">model</span> <span class="o">=</span> <span class="n">HistGradientBoostingRegressor</span><span class="p">()</span>
</code></pre></div></div>

<p>In this context, the acceptable amount of error is probably dictated by how much money you have in the bank as a backup in case you get less for the house than you expected. For your purposes, you decide that a difference of 35% compared to the actual value would be too much additional cost for you to bear.</p>

<p>We’ll first come up with out-of-sample predictions using the cross validation function, and then we’ll plot the actual vs predicted values along with the “good enough” region we want to hit.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">predictions</span> <span class="o">=</span> <span class="n">cross_val_predict</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">cv</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>  <span class="c1"># cv=5 for 5-fold cross-validation
</span>
<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="n">sns</span>

<span class="n">x_y_line</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([</span><span class="nb">min</span><span class="p">(</span><span class="n">predictions</span><span class="p">),</span> <span class="nb">max</span><span class="p">(</span><span class="n">predictions</span><span class="p">)])</span>
<span class="n">p</span> <span class="o">=</span> <span class="mf">0.35</span> <span class="c1"># Size of threshold, 35%
</span>
<span class="n">sns</span><span class="p">.</span><span class="n">histplot</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="n">predictions</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="n">y</span><span class="p">)</span> <span class="c1"># Plot the predicted vs actual values
</span><span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x_y_line</span><span class="p">,</span> <span class="n">x_y_line</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Perfect accuracy'</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'orange'</span><span class="p">)</span> <span class="c1"># Plot the "perfect calibration" line
</span><span class="n">plt</span><span class="p">.</span><span class="n">fill_between</span><span class="p">(</span><span class="n">x_y_line</span><span class="p">,</span> <span class="n">x_y_line</span><span class="o">*</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="n">p</span><span class="p">),</span> <span class="n">x_y_line</span><span class="o">*</span><span class="p">(</span><span class="mi">1</span><span class="o">-</span><span class="n">p</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'Acceptable error region'</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'orange'</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="p">.</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># Plot the "good enough" region
</span><span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Predicted'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Actual'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://github.com/lmc2179/lmc2179.github.io/assets/1301965/be70f215-01ab-438e-8afe-da66f01eb958" alt="image" /></p>

<p>For reasons I can’t really explain, I find it very amusing that this diagram looks like the <a href="https://en.wikipedia.org/wiki/Flag_of_Seychelles">flag of Seychelles</a>, and would look even more so if we added finer gradations of hit vs missed targets.</p>

<p>In addition to a chart like this, it’s also handy to define a numeric score - we could even use this for model selection, if we wanted to. One that seems like it would be an easy step to me is the percentage of time our model makes predictions that land in the bound of acceptable error. Hopefully, that number is high, indicating that we can usually expect this model to produce outputs of good enough quality to use for decision-making.</p>

<p>If we define $p$ as the acceptable percent change, we can compute the estimated <em>percent of predictions within acceptable error as</em>:</p>

\[\text{Estimated probability of acceptable error} \\
= \frac{\text{Count of predictions within band}}{\text{Count of all predictions}}
= \frac{\sum_i I[y_i \times (1-p) \leq \hat{y}_i \leq y_i \times (1+p)]}{n}\]

<p>To think about this from an engineering perspective, our use case defines the “tolerance”, similar to the tolerance which is set in machining parts. This quantity tells us how often the product which our model produces (ie its output) is within the tolerance for error that we can handle.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Within target region calculation
</span>
<span class="n">within_triangle</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">((</span><span class="n">y</span><span class="o">*</span><span class="p">(</span><span class="mi">1</span><span class="o">-</span><span class="n">p</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">predictions</span><span class="p">)</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">predictions</span> <span class="o">&lt;</span> <span class="n">y</span><span class="o">*</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="n">p</span><span class="p">)))</span>

<span class="k">print</span><span class="p">(</span><span class="nb">round</span><span class="p">(</span><span class="mi">100</span> <span class="o">*</span> <span class="p">(</span><span class="n">within_triangle</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">))),</span> <span class="mi">2</span><span class="p">)</span>
</code></pre></div></div>

<p>That gives us 66% for this model on this data set - a strong start, though there’s probably room for improvement. It seems unlikely that we’d be willing to deploy this model as-is, and we’d want to improve performance by adding more features, more data, or improving the model design. However, even though this model is not usable currently, it’s useful to now have a way of measuring how well the model fits the task at hand.</p>

<p>This is just one example of doing decision-oriented model validation, but the method could be expanded or taken in different directions. If we wanted to get a finer idea of how our decisions might play out, we could break the plot into more segments, like introducing regions for “near misses” or “catastrophic misses”. You could also probably analyze the relationship between predicted and actual with quantile regression, learning what the “usual” lower bound on actual value given the predicted value is.</p>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[We use predictive models as our advisors, helping us make better decisions using their output. A reasonable question, then, is “is my model accurate enough to be useful”? An already-present part of the process for most ML practitioners is Cross Validation, that beloved Swiss Army Knife of model validation. Anyone doing their due diligence when training a predictive model will try a few out, and select the one with the minimum Mean Squared Error, or perhaps use the one standard error rule. Either way, you’ll look at some out-of-sample errors for different models.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/Flag_of_Seychelles.svg.png" /><media:content medium="image" url="https://lmc2179.github.io/Flag_of_Seychelles.svg.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Flexible prediction intervals: Quantile Regression in Python</title><link href="https://lmc2179.github.io/posts/quantreg_pi.html" rel="alternate" type="text/html" title="Flexible prediction intervals: Quantile Regression in Python" /><published>2023-04-28T00:00:00+00:00</published><updated>2023-04-28T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/quantreg_pi</id><content type="html" xml:base="https://lmc2179.github.io/posts/quantreg_pi.html"><![CDATA[<h2 id="most-useful-forecasts-include-a-range-of-likely-outcomes">Most useful forecasts include a range of likely outcomes</h2>

<p>It’s generally good to try and guess what the future will look like, so we can plan accordingly. How much will our new inventory cost? How many users will show up tomorrow? How much raw material will I need to buy? The first instinct we have is usual to look at historical averages; we know the average price of widgets, the average number of users, etc. If we’re feeling extra fancy, we might build a model, like a linear regression, but this is also an average; a conditional average based on some covariates. Most out-of-the-box machine learning models are the same, giving us a prediction that is correct on average.</p>

<p>However, answering these questions with a single number, like an average, is a little dangerous. The actual cost will usually not be exactly the average; it will be somewhat higher or lower. How much higher? How much lower? If we could answer this question with a range of values, we could prepare appropriately for the worst and best case scenarios. It’s good to know our resource requirements for the average case; it’s better to also know the worst case (even if we don’t expect the worst to actually happen, if total catastrophe is plausible it will change our plans).</p>

<p>As is so often the case, it’s useful to consider a specific example. Let’s imagine a seasonal product; to pick one totally at random, imagine the inventory planning of a luxury sunglasses brand for cats. Purrberry needs to make summer sales projections for inventory allocation across its various brick-and-mortar locations where it’s sales happen.</p>

<p>You go to your data warehouse, and pull last year’s data on each location’s pre-summer sales (X-axis) and summer sales (Y-axis):</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="n">sns</span>

<span class="n">plt</span><span class="p">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">df</span><span class="p">[</span><span class="s">'on_season_revenue'</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Off season revenue at location'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'On season revenue at location'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Comparison between on and off season revenue at store locations'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>
<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/quantreg_pi/Figure_1.png" alt="Scatterplot" /></p>

<p>We can read off a few things here straight away:</p>
<ul>
  <li>A location with high off-season sales will also have high summer sales; X and Y are positively correlated.</li>
  <li>The outcomes are more uncertain for the stores with the highest off-season sales; the variance of Y increases with X.</li>
  <li>On the high end, outlier results are more likely to be extra high sales numbers instead of extra low; the noise is asymmetric, and positively skewed.</li>
</ul>

<p>After this first peek at the data, you might reach for that old standby, Linear Regression.</p>

<h2 id="our-usual-tool-ols-doesnt-always-handle-this-well">Our usual tool, OLS, doesn’t always handle this well</h2>

<p>Regression afficionados will recall that our <a href="https://lmc2179.github.io/posts/confidence_prediction.html">trusty OLS model allows us to compute prediction intervals</a>, so we’ll try that first.</p>

<p>Recall that the OLS model is</p>

<p>$y ~ \alpha + \beta x + N(0, \sigma)$</p>

<p>Where $\alpha$ is the intercept, $\beta$ is the slope, and $\sigma$ is the standard deviation of the residual distribution. Under this model, we expect that observations of $y$ are normally distributed around $\alpha + \beta x$, with a standard deviation of $\sigma$. We estimate $\alpha$ and $\beta$ the usual way, and look at the observed residual variance to estimate $\sigma$, and we can use the <a href="https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule">familiar properties of the normal distribution</a> to create prediction intervals.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">statsmodels.api</span> <span class="kn">import</span> <span class="n">formula</span> <span class="k">as</span> <span class="n">smf</span>

<span class="n">ols_model</span> <span class="o">=</span> <span class="n">smf</span><span class="p">.</span><span class="n">ols</span><span class="p">(</span><span class="s">'on_season_revenue ~ off_season_revenue'</span><span class="p">,</span> <span class="n">df</span><span class="p">).</span><span class="n">fit</span><span class="p">()</span>
<span class="n">predictions</span> <span class="o">=</span> <span class="n">ols_model</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">df</span><span class="p">)</span>
<span class="n">resid_sd</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">std</span><span class="p">(</span><span class="n">ols_model</span><span class="p">.</span><span class="n">resid</span><span class="p">)</span>

<span class="n">high</span><span class="p">,</span> <span class="n">low</span> <span class="o">=</span> <span class="n">predictions</span> <span class="o">+</span> <span class="mf">1.645</span> <span class="o">*</span> <span class="n">resid_sd</span><span class="p">,</span> <span class="n">predictions</span> <span class="o">-</span> <span class="mf">1.645</span> <span class="o">*</span> <span class="n">resid_sd</span>

<span class="n">plt</span><span class="p">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">df</span><span class="p">[</span><span class="s">'on_season_revenue'</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">high</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'OLS 90% high PI'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">predictions</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'OLS prediction'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">low</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'OLS 90% low PI'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Off season revenue at location'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'On season revenue at location'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'OLS prediction intervals'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/quantreg_pi/Figure_2.png" alt="OLS plot" /></p>

<p>Hm. Well, this isn’t terrible - it looks like the 90% prediction intervals do contain the majority of observations. However, it also looks pretty suspect; on the left side of the plot the PIs seem too broad, and on the right side they seem a little too narrow.</p>

<p>This is because the PIs are the same width everywhere, since we assumed that the variance of the residuals is the same everywhere. But from this plot, we can see that’s not true; the variance increases as we increase X. These two situations (constant vs non-constant variance) have the totally outrageous names <a href="https://en.wikipedia.org/wiki/Homoscedasticity_and_heteroscedasticity">homoskedasticity and heteroskedasticity</a>. OLS assumes homoskedasticity, but we actually have heteroskedasticity. If we want to make predictions that match the data we see, and OLS model won’t quite cut it.</p>

<p>NB: A choice sometimes recommended in a situation like this is to perform a log transformation, but <a href="https://lmc2179.github.io/posts/multiplicative.html">we’ve seen before</a> that logarithms aren’t a panacea when it comes to heteroskedasticity, so we’ll skip that one.</p>

<h2 id="the-idea-create-prediction-intervals-based-on-the-conditional-quantiles">The idea: create prediction intervals based on the conditional quantiles</h2>

<p>We really want to answer a question like: “For all stores with $x$ in pre-summer sales, where will (say) 90% of the summer sales per store be?”. <strong>We want to know how the bounds of the distribution, the highest and lowest plausible observations, change with the pre-summer sales numbers</strong>. If we weren’t considering an input like the off-season sales, we might look at the 5% and 95% <a href="https://en.wikipedia.org/wiki/Quantile">quantiles</a> of the data to answer that question.</p>

<p>We want to know what the quantiles of the distribution will be if we condition on $x$, so our model will produce the <em>conditional quantiles</em> given the off-season sales. This is analogous to the conditional mean, which is what OLS (and many machine learning models) give us. The conditional mean is $\mathbb{E}[y \mid x]$, or the expected value of $y$ given $x$. We’ll represent the conditional median, or conditional 50th quantile, as $Q_{50}[y \mid x]$. Similarly, we’ll call the conditional 5th percentile $Q_{5}[y \mid x]$, and the conditional 95th percentile will be $Q_{95}[y \mid x]$.</p>

<p>OLS works by finding the coefficients that minimize the sum of the squared loss function. Quantile regression can be framed in a similar way, where the loss function is changed to something else. For the median model, the minimization happening is <a href="https://en.wikipedia.org/wiki/Least_absolute_deviations">LAD</a>, a relative of OLS. For a model which computes arbitrary quantiles, we mininimize the whimsically named <a href="https://www.lokad.com/pinball-loss-function-definition">pinball loss function</a>. You can look at <a href="https://en.wikipedia.org/wiki/Quantile_regression#Conditional_quantile_and_quantile_regression">this section of the Wikipedia page</a> to learn about the minimization problem happening under the hood.</p>

<h1 id="quantile-regression-in-action">Quantile regression in action</h1>

<h2 id="fitting-the-model">Fitting the model</h2>

<p>As usual, we’ll let our favorite Python library do the hard work. We’ll build our quantile regression models using <a href="https://www.statsmodels.org/dev/generated/statsmodels.regression.quantile_regression.QuantReg.html">the statsmodels implementation</a>. The interface is similar to the OLS model in statsmodels, or to the R linear model notation. We’ll fit three models: one for the 95th quantile, one for the median, and one for the 5th quantile.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">high_model</span> <span class="o">=</span> <span class="n">smf</span><span class="p">.</span><span class="n">quantreg</span><span class="p">(</span><span class="s">'on_season_revenue ~ off_season_revenue'</span><span class="p">,</span> <span class="n">df</span><span class="p">).</span><span class="n">fit</span><span class="p">(</span><span class="n">q</span><span class="o">=</span><span class="p">.</span><span class="mi">95</span><span class="p">)</span>
<span class="n">mid_model</span> <span class="o">=</span> <span class="n">smf</span><span class="p">.</span><span class="n">quantreg</span><span class="p">(</span><span class="s">'on_season_revenue ~ off_season_revenue'</span><span class="p">,</span> <span class="n">df</span><span class="p">).</span><span class="n">fit</span><span class="p">(</span><span class="n">q</span><span class="o">=</span><span class="p">.</span><span class="mi">5</span><span class="p">)</span>
<span class="n">low_model</span> <span class="o">=</span> <span class="n">smf</span><span class="p">.</span><span class="n">quantreg</span><span class="p">(</span><span class="s">'on_season_revenue ~ off_season_revenue'</span><span class="p">,</span> <span class="n">df</span><span class="p">).</span><span class="n">fit</span><span class="p">(</span><span class="n">q</span><span class="o">=</span><span class="p">.</span><span class="mi">05</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">df</span><span class="p">[</span><span class="s">'on_season_revenue'</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">high_model</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">df</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'95% Quantile'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">mid_model</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">df</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'50% Quantile (Median)'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">low_model</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">df</span><span class="p">),</span> <span class="n">label</span><span class="o">=</span><span class="s">'5% Quantile'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Off season revenue at location'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'On season revenue at location'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Quantile Regression prediction intervals'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/quantreg_pi/Figure_3.png" alt="Quantreg scatterplot" /></p>

<p>The 90% prediction intervals given by these models (the range between the green and blue lines) look like a much better fit than those given by the OLS model. On the left side of the X-axis, the interval is appropriately narrow, and then widens as the X-axis increases. This change in width indicates that our model is heteroskedastic.</p>

<p>It also looks like noise around the median is asymmetric; the distance from the upper bound to the median looks larger than the distance from the lower bound to the median. We could see this in the model directly by looking at the slopes of each line, and seeing that $\mid \beta_{95} - \beta_{50} \mid \geq \mid \beta_{50} - \beta_{5} \mid$.</p>

<h2 id="checking-the-model">Checking the model</h2>

<p>Being careful consumers of models, we are sure to check the model’s performance to see if there are any surprises.</p>

<p>First, we can look at the prediction quality in-sample. We’ll compute the <strong>coverage</strong> of the model’s predictions. Coverage is the percentage of data points which fall into the predicted range. Our model was supposed to have 90% coverage - did it actually?</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">sem</span>
<span class="n">covered</span> <span class="o">=</span> <span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'on_season_revenue'</span><span class="p">]</span> <span class="o">&gt;=</span> <span class="n">low_model</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">df</span><span class="p">))</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'on_season_revenue'</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="n">high_model</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">df</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s">'In-sample coverage rate: '</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">average</span><span class="p">(</span><span class="n">covered</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Coverage SE: '</span><span class="p">,</span> <span class="n">sem</span><span class="p">(</span><span class="n">covered</span><span class="p">))</span>
</code></pre></div></div>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>In-sample coverage rate:  0.896
Coverage SE:  0.019345100974843932
</code></pre></div></div>

<p>The coverage is within one standard error of 90%. Nice!</p>

<p>There’s no need to limit ourselves to looking in-sample and we probably shouldn’t. We could use the coverage metric during cross-validation, ensuring that the out-of-sample coverage was similarly good.</p>

<p>When we do OLS regression, we often plot the predictor against the error to understand whether the linear specification was reasonable. We can do the same here by plotting our predictor against the coverage. This plot shows the coverage and a CI for each quartile.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">sns</span><span class="p">.</span><span class="n">regplot</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'off_season_revenue'</span><span class="p">],</span> <span class="n">covered</span><span class="p">,</span> <span class="n">x_bins</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">axhline</span><span class="p">(.</span><span class="mi">9</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dotted'</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'black'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Coverage by revenue group'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Off season revenue at location'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Coverage'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/quantreg_pi/Figure_4.png" alt="Coverage plot" /></p>

<p>All the CIs contain 90% with no clear trend, so the linear specification seems reasonable. We could make the same plot by decile, or even percentile as well to get a more careful read.</p>

<p>What if that last plot had looked different? If the coverage veers off the the target value, we could have considered introducing nonlinearities to the model, such as adding splines.</p>

<h1 id="some-other-perspectives-on-quantile-regression-and-prediction-intervals">Some other perspectives on quantile regression and prediction intervals</h1>

<p>This is just one usage of quantile regression. QR models can also be used for multivariable analysis of <a href="https://lmc2179.github.io/posts/distributional-effects.html">distributional impact</a>, providing very rich summaries of how our covariates are correlated with change in the shape of the output distribution.</p>

<p>We also could have thought about prediction intervals differently. If we believed that the noise was heteroskedastic but still symmetric (or perhaps even normally distributed), we could have used an OLS-based procedure model how the residual variance changed with the covariate. For a great summary of this, see <a href="https://www.stat.cmu.edu/~cshalizi/ADAfaEPoV/ADAfaEPoV.pdf">section 10.3 of Shalizi’s data analysis book</a>.</p>

<h1 id="appendix-how-the-data-was-generated">Appendix: How the data was generated</h1>

<p>The feline fashion visionaries at Purrberry are, regrettably, entirely fictional for the time being. The data from this example was generated using the below code, which creates skew normal distributed noise:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">skewnorm</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>

<span class="n">n</span> <span class="o">=</span> <span class="mi">250</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">linspace</span><span class="p">(.</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span>
<span class="n">gen</span> <span class="o">=</span> <span class="n">skewnorm</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">arange</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">))</span><span class="o">+</span><span class="p">.</span><span class="mi">01</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="n">x</span><span class="p">)</span>
<span class="n">gen</span><span class="p">.</span><span class="n">random_state</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">Generator</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">PCG64</span><span class="p">(</span><span class="nb">abs</span><span class="p">(</span><span class="nb">hash</span><span class="p">(</span><span class="s">'predictions'</span><span class="p">))))</span>
<span class="n">y</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">+</span> <span class="n">x</span> <span class="o">+</span> <span class="n">gen</span><span class="p">.</span><span class="n">rvs</span><span class="p">()</span>

<span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'off_season_revenue'</span><span class="p">:</span> <span class="n">x</span><span class="p">,</span> <span class="s">'on_season_revenue'</span><span class="p">:</span> <span class="n">y</span><span class="p">})</span>
</code></pre></div></div>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[Most useful forecasts include a range of likely outcomes]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/quantile_friend.png" /><media:content medium="image" url="https://lmc2179.github.io/quantile_friend.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">How did my treatment affect the distribution of my outcomes? A/B testing with quantiles and their confidence intervals in Python</title><link href="https://lmc2179.github.io/posts/distributional-effects.html" rel="alternate" type="text/html" title="How did my treatment affect the distribution of my outcomes? A/B testing with quantiles and their confidence intervals in Python" /><published>2022-06-11T00:00:00+00:00</published><updated>2022-06-11T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/distributional-effects</id><content type="html" xml:base="https://lmc2179.github.io/posts/distributional-effects.html"><![CDATA[<p><em>We’re familiar with A/B tests that tell us how our metric (usually an average of some kind) changed due to the treatment. But if we want to get a better than average insight into the treatment effect, we should look beyond the mean. This post demonstrates why and how we might look at the way the quantiles of the distribution changed as a result of the treatment, complete with neat visualizations you can show in your next A/B test report built in Python.</em></p>

<h1 id="distributional-effects-of-ab-tests-are-often-overlooked-but-provide-a-deeper-understanding">Distributional effects of A/B tests are often overlooked but provide a deeper understanding</h1>

<h2 id="the-group-averages-and-average-treatment-effect-hide-a-lot-of-information">The group averages and average treatment effect hide a lot of information</h2>

<p>Most companies I know of that include A/B testing in their product development process usually do something like the following for most of their tests:</p>
<ul>
  <li>Pick your favorite metric which you want to increase, and perhaps some other metrics that will act as guard rails. Often, this is some variant of “revenue per user”, “engagment per user”, ROI or the efficiency of the process.</li>
  <li>Design and launch an experiment which compares the existing product’s performance to that of some variant products.</li>
  <li>At some point, decide to stop collecting data.</li>
  <li>Compute the average treatment effect for the control version vs the test variant(s) on each metric. Calculate some measure of uncertainty (like a P-value or confidence/credible interval). Make a decision about whether to replace the existing production product with one of the test variants.</li>
</ul>

<p>This process is so common because, well, it works - if followed, it will usually result in the introduction of product features which increase our favorite metric. It creates a series of discrete steps in the product space which attempt to optimize the favorite metric without incurring unacceptable losses on the other metrics.</p>

<p>In this process, the average treatment effect is the star of the show. But as we learn in Stats 101, two distributions can look drastically different while still having the same average. For example, here are four remarkably different distributions with the same average:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="n">sns</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">poisson</span><span class="p">,</span> <span class="n">skellam</span><span class="p">,</span> <span class="n">nbinom</span><span class="p">,</span> <span class="n">randint</span><span class="p">,</span> <span class="n">geom</span>

<span class="k">for</span> <span class="n">dist</span> <span class="ow">in</span> <span class="p">[</span><span class="n">poisson</span><span class="p">(</span><span class="mi">100</span><span class="p">),</span> <span class="n">skellam</span><span class="p">(</span><span class="mi">1101</span><span class="p">,</span> <span class="mi">1000</span><span class="p">),</span> <span class="n">randint</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">200</span><span class="p">),</span> <span class="n">geom</span><span class="p">(</span><span class="mf">1.</span><span class="o">/</span><span class="mi">100</span><span class="p">)]:</span>
  <span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">400</span><span class="p">),</span> <span class="n">dist</span><span class="p">.</span><span class="n">pmf</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">400</span><span class="p">)))</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlim</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">400</span><span class="p">)</span>  
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'PMF'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Four distributions with a mean of 100'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/distributional_effects/Figure_0.png" alt="Four distributions with different shapes but the same mean" /></p>

<p>Similarly, the average treatment effect does not tell us much about how our treatment changed the shape of the distribution of outcomes. But we can expand our thinking not just to consider how the treatment changed the average, but the effect on the shape of the distribution; the <a href="https://en.wikipedia.org/wiki/Distributional_effects">distributional effect</a> of the treatment. Expanding our thought to think about distributional effects might give us insights that we can’t get from averages alone, and help us see more clearly what our treatment did. For example:</p>

<ul>
  <li>If we have a positive treatment effect, we can see whether one tail of the distribution was disproportionately affected. Did our gains come from lifting everyone? From squeezing more revenue out of the high-revenue users? From “lifting the floor” on the users who aren’t producing much in control?</li>
  <li>If an experiment negatively affected one tail of the distribution, we can consider mitigation. If our treatment provided a negative experience for users on the low end of the distribution, is there anything we can do to make their experience better?</li>
  <li>Are we meeting our goals for the shape of the distribution? For example, if we want to maintain a minimum service level, are we doing so in the treatment group?</li>
  <li>Do we want to move up market? If so, is our treatment increasing the output for the high end of the outcome distribution?</li>
  <li>Do we want to diversify our customer base? If so, is our treatment increasing our concentration among already high-value users?</li>
</ul>

<p>The usual average treatment effect cannot answer these questions. We could compare single digit summaries of shape (variance, skewness, kurtosis) between treatment and control. However, even these are only simplified summaries; they describe a single attribute of the shape like the dispersion, symmetry, or heavy tailedness.</p>

<p>Instead, we’ll look at the empirical <a href="https://en.wikipedia.org/wiki/Quantile_function">quantile function</a> of control and treatment, and the difference between them. We’ll lay out some basic definitions here:</p>
<ul>
  <li>The quantile function is the smooth version of the more familiar percentile distribution. For example, the 0.5 quantile is the median, the value that’s larger than 50% of the mass in the distribution, and the 50th percentile (those are all the same thing).</li>
  <li>The empirical quantile function is the set of quantile values in the treatment/control results which we actually observe.</li>
  <li>The inverse of the quantile function is the CDF , and its empirical counterpart is the <a href="https://www.statsmodels.org/devel/generated/statsmodels.distributions.empirical_distribution.ECDF.html">empirical CDF</a>. We won’t talk much about the CDF here, but it’s useful to link the two because the CDF is such a common description of a distribution.</li>
</ul>

<p>Let’s take a look at an example of how we might use these in practice to learn about the distributional effects of a test.</p>

<h1 id="an-example-how-did-my-ab-test-affect-the-distribution-of-revenue">An example: How did my A/B test affect the distribution of revenue?</h1>

<p>Let’s once more put ourselves in the shoes of that most beloved of Capitalist Heroes, the <a href="https://lmc2179.github.io/posts/confidence_prediction.html">purveyor of little tiny cat sunglasses</a>. Having harnessed the illuminating insights of your business’ data, you’ve consistently been improving your key metric of Revenue per Cat. You currently send out a weekly email about the current purrmotional sales, a newsletter beloved by dashing calicos and tabbies the world over. As you are the sort of practical, industrious person who is willing to spend their valuable time reading a blog about statistics, you originally gave this email the very efficient subject line of “Weekly Newsletter” and move on to other things.</p>

<p>However, you’re realizing it’s time to revisit that decision - your previous analysis demonstrated that warm eather is correlated with stronger sales, as cats everywhere flock to sunny patches of light on the rug in the living room. Perhaps, if you could write a suitably eye-catching subject line, you could make the most of this seasonal oppourtunity. Cats are notoriously aloof, so you settle on the overstuffed subject line “<strong>W</strong>ow so chic ✨ shades 🕶 for cats 😻 summer SALE ☀ <em>buy now</em>” in a desperate bid for their attention. As you are (likely) a person and not a cat, you decide to run an A/B test on this subject line to see if your audience likes the new subject line.</p>

<p>You fire up your A/B testing platform, and get 1000 lucky cats to try the new subject line, and 1000 to try the old one. You measure the revenue purr customer in the period after the test, and you’re ready to analyze the test results.</p>

<p>Lets import some things from the usual suspects:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">norm</span><span class="p">,</span> <span class="n">sem</span> <span class="c1"># Normal distribution, Standard error of the mean
</span><span class="kn">from</span> <span class="nn">copy</span> <span class="kn">import</span> <span class="n">deepcopy</span> 
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tqdm</span> <span class="c1"># A nice little progress bar
</span><span class="kn">from</span> <span class="nn">scipy.stats.mstats</span> <span class="kn">import</span> <span class="n">mjci</span> <span class="c1"># Calculates the standard error of the quantiles: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mstats.mquantiles_cimj.html
</span><span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span> <span class="c1"># Pretty pictures
</span><span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="n">sns</span> <span class="c1"># Matplotlib's best friend
</span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span> 
</code></pre></div></div>

<p>In order to get a feel for how revenue differed between treatment and control, let’s start with our usual first tool for understanding distribution shape, the trusty histogram:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Distribution of revenue per customer'</span><span class="p">)</span>
<span class="n">sns</span><span class="p">.</span><span class="n">distplot</span><span class="p">(</span><span class="n">data_control</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Control'</span><span class="p">)</span>
<span class="n">sns</span><span class="p">.</span><span class="n">distplot</span><span class="p">(</span><span class="n">data_treatment</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Treatment'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Density'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Revenue ($)'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/distributional_effects/Figure_1.png" alt="Histogram" /></p>

<p>Hm. That’s a little tough to read. Just eyeballing it, the tail on the Treatment group seems a little thicker, but it’s hard to say much more than that.</p>

<p>Let’s see what we can learn about how treatment differs from control. We’ll compute the usual estimate of the average treatment effect on revenue per customer, along with its standard error.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">z_a_over_2</span><span class="p">(</span><span class="n">alpha</span><span class="p">):</span>
  <span class="k">return</span> <span class="n">norm</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">).</span><span class="n">ppf</span><span class="p">(</span><span class="mf">1.</span><span class="o">-</span><span class="n">alpha</span><span class="o">/</span><span class="mf">2.</span><span class="p">)</span>

<span class="n">te</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">data_treatment</span><span class="p">)</span> <span class="o">-</span> <span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">data_control</span><span class="p">)</span> <span class="c1"># Point estimate of the treatment effect
</span><span class="n">ci_radius</span> <span class="o">=</span> <span class="n">z_a_over_2</span><span class="p">(.</span><span class="mi">05</span><span class="p">)</span> <span class="o">*</span> <span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">sem</span><span class="p">(</span><span class="n">data_treatment</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="n">sem</span><span class="p">(</span><span class="n">data_control</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># Propagate the standard errors of each mean, and compute a CI
</span><span class="k">print</span><span class="p">(</span><span class="s">'Average treatment effect: '</span><span class="p">,</span> <span class="n">te</span><span class="p">,</span> <span class="s">'+-'</span><span class="p">,</span> <span class="n">ci_radius</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Average treatment effect:  1.1241231969779277 +- 0.29768161367254564
</code></pre></div></div>

<p>Okay, so it looks like our treatment moved the average revenue per user! That’s good news - it means your carefully chosen subject line will actually translate into better outcomes, all for the low price of a changed subject line.</p>

<p>(An aside: in a test like this, you might pause here to consider other factors. For example: is there evidence that this is a novelty effect, rather than a durable change in the metric? Did I wait long enough to collect my data, to capture downstream events after the email was opened? These are good questions, but we will table them for now.)</p>

<p>It’s certainly good news that the average revenue moved. But, wise statistics sage that you are, you know the average isn’t the whole story. Now, lets think distributionally - let’s consider questions like:</p>
<ul>
  <li>Is the gain coming from squeezing more out of the big spenders, or increasing engagement with those who spend least?</li>
  <li>Was any part of the distribution negatively affected, even if the gain was positive on average?</li>
</ul>

<p>We answer these questions by looking at how the distribution shifted.</p>

<p>(Another aside: For this particular problem related to the effects of an email change, we might also look at whether the treatment increased the open rate, or the average order value, or if they went in different directions. This is a useful way to decompose the revenue per customer, but we’ll avoid it in this discussion since it’s pretty email-specific.)</p>

<p>Before we talk about the quantile function, we can also consider another commonly used tool for inspecting distribution shape, which goes by the thematically-appropriate name of <a href="https://en.wikipedia.org/wiki/Box_plot">box-and-whisker plot</a>.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Q</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">linspace</span><span class="p">(</span><span class="mf">0.05</span><span class="p">,</span> <span class="p">.</span><span class="mi">95</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">boxplot</span><span class="p">(</span><span class="n">data_control</span><span class="p">,</span> <span class="n">positions</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">whis</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">boxplot</span><span class="p">(</span><span class="n">data_treatment</span><span class="p">,</span> <span class="n">positions</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">whis</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xticks</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span> <span class="p">[</span><span class="s">'Control'</span><span class="p">,</span> <span class="s">'Treatment'</span><span class="p">])</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Revenue ($)'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Box and Whisker - Revenue per customer by Treatment status'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/distributional_effects/Figure_2.png" alt="Box and Whisker plot" /></p>

<p>This isn’t especially easy to read either. We can get a couple of things from it: it looks like the max revenue per user in the treatment group was much higher, and the median was lower. (I also tried this one on a log axis, and didn’t find it much easier, but you may find that a more intuitive plot than I did.)</p>

<p>Let’s try a different approach to understanding the distribution shape - we’ll plot the empirical quantile function. We can get this using the <code class="language-plaintext highlighter-rouge">np.quantile</code> function, and telling it which quantiles of the data we want to calculate.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Quantiles of revenue per customer'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Quantile'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Revenue ($)'</span><span class="p">)</span>
<span class="n">control_quantiles</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">quantile</span><span class="p">(</span><span class="n">data_control</span><span class="p">,</span> <span class="n">Q</span><span class="p">)</span>
<span class="n">treatment_quantiles</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">quantile</span><span class="p">(</span><span class="n">data_treatment</span><span class="p">,</span> <span class="n">Q</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">Q</span><span class="p">,</span> <span class="n">control_quantiles</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Control'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">Q</span><span class="p">,</span> <span class="n">treatment_quantiles</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Treatment'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/distributional_effects/Figure_3.png" alt="Quantile plots" /></p>

<p>I find this a little easier to understand. Here are some things we can read off from it:</p>
<ul>
  <li>The 0.5 quantile (the median) of revenue was higher in control than treatment - even though the average treatment user produced more revenue than control!</li>
  <li>Below the 0.75 quantile, it looks like control produced more revenue than treatment. That is, the treatment looks like it may have <em>decreased</em> revenue per customer in about 75% of users (we can’t tell for sure, because there are no confidence intervals on the curves).</li>
  <li>The 0.75 quantile of the two are the same. So 75% of the users in <em>both</em> treatment and control produced less than about $1.</li>
  <li>The big spenders, the top 25% of the distribution produced <em>much</em> more revenue in treatment than control. It appears that the treatment primarily creates an increase in revenue per user by increasing revenue among these highly engaged users.</li>
</ul>

<p>This is a much more detailed survey of the how the treatment affected our outcome than the average treatment effect can provide. At this point, we might decide to dive a little deeper into what happened with that 75% of users. If we can understand why they were affected negatively by the treatment, perhaps there is something we can do in the next iteration of the test to improve their experience.</p>

<p>Let’s look at this one more way - we’ll look at the treatment effect on the whole quantile curve. That is, we’ll subtract the control curve from the treatment curve, showing us how the treatment changed the shape of the distribution.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Quantile difference (Treatment - Control)'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Quantile'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Treatment - Control'</span><span class="p">)</span>
<span class="n">quantile_diff</span> <span class="o">=</span> <span class="n">treatment_quantiles</span> <span class="o">-</span> <span class="n">control_quantiles</span>
<span class="n">control_se</span> <span class="o">=</span> <span class="n">mjci</span><span class="p">(</span><span class="n">data_control</span><span class="p">,</span> <span class="n">Q</span><span class="p">)</span>
<span class="n">treatment_se</span> <span class="o">=</span> <span class="n">mjci</span><span class="p">(</span><span class="n">data_treatment</span><span class="p">,</span> <span class="n">Q</span><span class="p">)</span>
<span class="n">diff_se</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">control_se</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="n">treatment_se</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="n">diff_lower</span> <span class="o">=</span> <span class="n">quantile_diff</span> <span class="o">-</span> <span class="n">z_a_over_2</span><span class="p">(.</span><span class="mi">05</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">Q</span><span class="p">))</span> <span class="o">*</span> <span class="n">diff_se</span>
<span class="n">diff_upper</span> <span class="o">=</span> <span class="n">quantile_diff</span> <span class="o">+</span> <span class="n">z_a_over_2</span><span class="p">(.</span><span class="mi">05</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">Q</span><span class="p">))</span> <span class="o">*</span> <span class="n">diff_se</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">Q</span><span class="p">,</span> <span class="n">quantile_diff</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'orange'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">fill_between</span><span class="p">(</span><span class="n">Q</span><span class="p">,</span> <span class="n">diff_lower</span><span class="p">,</span> <span class="n">diff_upper</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="p">.</span><span class="mi">5</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">axhline</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'grey'</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="p">.</span><span class="mi">5</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/distributional_effects/Figure_4.png" alt="Quantile difference" /></p>

<p>This one includes confidence intervals computed using the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mstats.mjci.html">Maritz-Jarrett estimator of the quantile standard error</a>. We’ve applied a <a href="https://en.wikipedia.org/wiki/Bonferroni_correction">Bonferroni correction</a> to the estimates as well, so no one accuse us of a poor Familywise Error Rate.</p>

<p>We can read off from this chart where the statistically significant treatment effects on the quantile function are. Namely, the treatment lifted the top 25% of the revenue distribution, and depressed roughly the middle 50%. The mid-revenue users were less interested in the new subject line, but the fat cats in the top 25% of the distribution got even fatter; the entire treatment effect came from high-revenue feline fashionistas buying up all the inventory, so much so that it overshadowed the decrease in the middle.</p>

<h1 id="some-other-ways-to-explore-beyond-the-average-treatment-effect">Some other ways to explore beyond the average treatment effect</h1>

<p>The above analysis tells us more than the usual “average” analysis does; it lets us answer questions about how the treatment affects properties of the revenue distribution other than the mean. In a sense, we decomposed the average treatment effect by user quantile. But it’s not the only tool that lets us see how aspects of the distribution changed. There are some other methods we might consider as well:</p>
<ul>
  <li><strong>Hetereogeneous effect analysis/subgroup analysis</strong>: Instead of thinking about how the treatment effect varied by quantile, we can relate it to some set of pre-treatment covariates of interest. By doing so, we can learn how our favorite customer was affected, which might tell us more about the mechanism that makes the treatment work or let us introduce mitigation. This might involve computing interactions between the treatment and subgroups, creating PDPs of the covariates plus treatment indicator, using <a href="https://arxiv.org/abs/1706.03461">X-learning</a> or <a href="https://arxiv.org/abs/1902.07409">causal forests</a>, to name a few approaches.</li>
  <li><strong>Conditional variance modeling</strong>: Instead of looking at the conditional mean, we could instead look at the conditional variance and see whether the variance was increased by the treatment. We could even include other covariates if we desire, letting us build a regression model that predicts the variance rather than the average. An overview of this that I’ve found useful is §10.3 of <a href="https://www.stat.cmu.edu/~cshalizi/ADAfaEPoV/ADAfaEPoV.pdf">Cosma Shalizi’s <em>Advanced Data Analysis from an Elementary Point of View</em></a>.</li>
  <li><strong>Measures of distribution “flatness”</strong>: A number of measures tell us something about how evenly distributed a distribution is over its support. We could look at how the treatment affected the <a href="https://en.wikipedia.org/wiki/Gini_coefficient">Gini coefficent</a>, the <a href="https://en.wikipedia.org/wiki/Entropy_(information_theory)">entropy</a>, or the <a href="https://en.wikipedia.org/wiki/Kurtosis">kurtosis</a> were affected by the treatment, bootstrapping the standard errors.</li>
  <li><strong>Relating the change in the distribution shape to many variables</strong>: Our analysis here related the outcome distribution to one variable: the treatment status. We don’t need to limit ourselves to just just one, though. Similar to the way that regression lets us add more covariates to our “difference of means” analysis, <a href="https://en.wikipedia.org/wiki/Quantile_regression">Quantile Regression</a> lets us do this for the quantiles of the distribution. Statsmodels <a href="https://www.statsmodels.org/dev/generated/statsmodels.regression.quantile_regression.QuantReg.html">QuantReg</a> is an easy-to-use implementation of this.</li>
</ul>

<h1 id="appendix-where-the-data-in-the-example-came-from">Appendix: Where the data in the example came from</h1>

<p>Embarassingly, I have not yet achieved the level of free-market enlightment required to run a company that makes money by selling sunglasses to cats. Because of this fact, the data from this example was not actually collected by me, but generated by the following process:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">sample_size</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="n">data_control</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">normal</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">sample_size</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span>
<span class="n">data_treatment</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">concatenate</span><span class="p">([</span><span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">normal</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mf">0.01</span><span class="p">,</span> <span class="nb">round</span><span class="p">(</span><span class="n">sample_size</span><span class="o">/</span><span class="mi">2</span><span class="p">)),</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">normal</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="nb">round</span><span class="p">(</span><span class="n">sample_size</span><span class="o">/</span><span class="mi">2</span><span class="p">))])</span><span class="o">**</span><span class="mi">2</span>
</code></pre></div></div>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[We’re familiar with A/B tests that tell us how our metric (usually an average of some kind) changed due to the treatment. But if we want to get a better than average insight into the treatment effect, we should look beyond the mean. This post demonstrates why and how we might look at the way the quantiles of the distribution changed as a result of the treatment, complete with neat visualizations you can show in your next A/B test report built in Python.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/juniper_sunglasses.jpeg" /><media:content medium="image" url="https://lmc2179.github.io/juniper_sunglasses.jpeg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Symbolic Calculus in Python: Simple Samples of Sympy</title><link href="https://lmc2179.github.io/posts/sympy.html" rel="alternate" type="text/html" title="Symbolic Calculus in Python: Simple Samples of Sympy" /><published>2021-08-04T00:00:00+00:00</published><updated>2021-08-04T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/sympy</id><content type="html" xml:base="https://lmc2179.github.io/posts/sympy.html"><![CDATA[<p><em>My job seems to involve just enough calculus that I can’t afford to forget it, but little enough that I always feel rusty when I need to do it. In those cases, I’m thankful to be able to check my work and make it reproducible with <a href="https://www.sympy.org/en/index.html">Sympy</a>, a symbolic mathematics library in Python. Here are two examples of recent places I’ve used Sympy to do calculus. We’ll start by computing the expected value of a distribution by doing a symbolic definite integral. Then, we’ll find the maximum of a model by finding its partial derivatives symbolically, and setting it to zero.</em></p>

<h1 id="symbolic-integration-finding-the-moments-of-a-probability-distribution">Symbolic Integration: Finding the moments of a probability distribution</h1>

<p>A simple model for a continuous, non-negative random variable is a <a href="https://en.wikipedia.org/wiki/Half-normal_distribution">half-normal distribution</a>. This is implemented in scipy as <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.halfnorm.html">halfnorm</a>. The <code class="language-plaintext highlighter-rouge">scipy</code> version is implemented in terms of a <code class="language-plaintext highlighter-rouge">scale</code> parameter which we’ll call $s$. If we’re going to use this distribution, there are a few questions we’d like to answer about it:</p>
<ul>
  <li>What are the moments of this distribution? How do the mean and variance of the distribution depend on $s$?</li>
  <li>How might we estimate $s$ from some data? If we knew the relationship between the first moment and $s$, we could use the <a href="https://en.wikipedia.org/wiki/Method_of_moments_(statistics)">Method of Moments</a> for this univariate distribution.</li>
</ul>

<p>Scipy lets us do all of these numerically (using functions like <code class="language-plaintext highlighter-rouge">mean()</code>, <code class="language-plaintext highlighter-rouge">var()</code>, and <code class="language-plaintext highlighter-rouge">fit(data)</code>). However, computing closed-form expressions for the above gives us some intuition about how the distribution behaves more generally, and could be the starting point for further analysis like computing the standard errors of $s$.</p>

<p>The scipy docs tell us that the PDF is:</p>

<p>$f(x) = \frac{1}{s} \sqrt{\frac{2}{\pi}} exp(\frac{-\frac{x}{s}^2}{2})$</p>

<p>Computing the <a href="https://en.wikipedia.org/wiki/Expected_value#Absolutely_continuous_case">mean</a> of the distribution requires solving an improper integral:</p>

<p>$\mu = \int_{0}^{\infty} x f(x) dx$</p>

<p>Similarly, finding the <a href="https://en.wikipedia.org/wiki/Variance#Definition">variance</a> requires doing some integration:</p>

<p>$\sigma^2 = \int_{0}^{\infty} (x - \mu)^2 f(x) dx$</p>

<p>We’ll perform these integrals symbolically to learn how $s$ relates to the mean and variance. We’ll then rearrange $s$ in terms of $\mu$ to get an estimating equation for $s$.</p>

<p>We’ll import everything we need:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">sympy</span> <span class="k">as</span> <span class="n">sm</span>
<span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">halfnorm</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
</code></pre></div></div>

<p>Variables which we can manipulate algebraically in Sympy are called “symbols”. We can instantiate one at a time using <code class="language-plaintext highlighter-rouge">Symbol</code>, or a few at a time using <code class="language-plaintext highlighter-rouge">symbols</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">x</span> <span class="o">=</span> <span class="n">sm</span><span class="p">.</span><span class="n">Symbol</span><span class="p">(</span><span class="s">'x'</span><span class="p">,</span> <span class="n">positive</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">sm</span><span class="p">.</span><span class="n">Symbol</span><span class="p">(</span><span class="s">'s'</span><span class="p">,</span> <span class="n">positive</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

<span class="c1"># x, s = sm.symbols('x s') # This works too
</span></code></pre></div></div>

<p>We’ll specify the PDF of <code class="language-plaintext highlighter-rouge">scipy.halfnorm</code> as a function of $x$ and $s$:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">f</span> <span class="o">=</span> <span class="p">(</span><span class="n">sm</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mi">2</span><span class="o">/</span><span class="n">sm</span><span class="p">.</span><span class="n">pi</span><span class="p">)</span> <span class="o">*</span> <span class="n">sm</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="p">(</span><span class="n">x</span><span class="o">/</span><span class="n">s</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="o">/</span><span class="mi">2</span><span class="p">))</span><span class="o">/</span><span class="n">s</span>
</code></pre></div></div>

<p>It’s now a simple task to symbolically compute the definite integrals defining the first and second moments. The first argument to <code class="language-plaintext highlighter-rouge">integrate</code> is the function to integrate, and the second is a tuple <code class="language-plaintext highlighter-rouge">(x, start, end)</code> defining the variable and range of integration. For an indefinite integral, the second argument is just the target variable. Note that <code class="language-plaintext highlighter-rouge">oo</code> is the cute sympy way of writing $\infty$.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">mean</span> <span class="o">=</span> <span class="n">sm</span><span class="p">.</span><span class="n">integrate</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">f</span><span class="p">,</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">sm</span><span class="p">.</span><span class="n">oo</span><span class="p">))</span>

<span class="n">var</span> <span class="o">=</span> <span class="n">sm</span><span class="p">.</span><span class="n">integrate</span><span class="p">(((</span><span class="n">x</span><span class="o">-</span><span class="n">mean</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span><span class="o">*</span><span class="n">f</span><span class="p">,</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">sm</span><span class="p">.</span><span class="n">oo</span><span class="p">))</span>
</code></pre></div></div>

<p>And just like that, we have computed closed-form expressions for the mean and variance in terms of $s$. You could use the <a href="https://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician">LOTUS</a> to calculate the EV of any function of a random variable this way, if you wanted to.</p>

<p>Printing <code class="language-plaintext highlighter-rouge">sm.latex(mean)</code> and <code class="language-plaintext highlighter-rouge">sm.latex(var)</code>, we see that:</p>

<p>$\mu = \frac{\sqrt{2} s}{\sqrt{\pi}}$</p>

<p>$\sigma^2 = - \frac{2 s^{2}}{\pi} + s^{2}$</p>

<p>Let’s make sure our calculation is right by running a quick test. We’ll select a random value for $s$, then compute its mean/variance symbolically as well as using Scipy:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">random_s</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">random</span><span class="p">.</span><span class="n">uniform</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>

<span class="k">print</span><span class="p">(</span><span class="s">'Testing for s = '</span><span class="p">,</span> <span class="n">random_s</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s">'The mean computed symbolically'</span><span class="p">,</span> <span class="n">mean</span><span class="p">.</span><span class="n">subs</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">random_s</span><span class="p">).</span><span class="n">subs</span><span class="p">(</span><span class="n">sm</span><span class="p">.</span><span class="n">pi</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">pi</span><span class="p">).</span><span class="n">evalf</span><span class="p">(),</span> <span class="s">'</span><span class="se">\n</span><span class="s">'</span><span class="p">,</span>
      <span class="s">'The mean from Scipy is:'</span><span class="p">,</span> <span class="n">halfnorm</span><span class="p">(</span><span class="n">scale</span><span class="o">=</span><span class="n">random_s</span><span class="p">).</span><span class="n">mean</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="s">'The variance computed symbolically'</span><span class="p">,</span> <span class="n">var</span><span class="p">.</span><span class="n">subs</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">random_s</span><span class="p">).</span><span class="n">subs</span><span class="p">(</span><span class="n">sm</span><span class="p">.</span><span class="n">pi</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">pi</span><span class="p">).</span><span class="n">evalf</span><span class="p">(),</span> <span class="s">'</span><span class="se">\n</span><span class="s">'</span><span class="p">,</span>
      <span class="s">'The variance from Scipy is:'</span><span class="p">,</span> <span class="n">halfnorm</span><span class="p">(</span><span class="n">scale</span><span class="o">=</span><span class="n">random_s</span><span class="p">).</span><span class="n">var</span><span class="p">())</span>
</code></pre></div></div>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Testing for s =  3.2530297154660213
The mean computed symbolically 2.59554218580328
 The mean from Scipy is: 2.595542185803277
The variance computed symbolically 3.84536309142049
 The variance from Scipy is: 3.8453630914204933
</code></pre></div></div>

<p>It looks like our expressions for the mean and variance are correct, at least for this randomly chosen value of $s$. Running it a few more times, it looks like it works more generally.</p>

<h1 id="symbolic-differentiation-finding-the-maximum-of-a-response-surface-model">Symbolic Differentiation: Finding the maximum of a response surface model</h1>

<p>Sympy also lets us perform symbolic differentiation. Unlike <a href="https://en.wikipedia.org/wiki/Numerical_differentiation">numerical differentiation</a> and <a href="https://en.wikipedia.org/wiki/Automatic_differentiation">automatic differentiation</a>, symbolic differentiation lets us compute the closed form of the derivative when it is available.</p>

<p>Imagine you are the editor of an email newsletter for an ecommerce company. You currently send out newsletters with two types of content, in the hopes of convinncing customers to spend more with your business. You’ve just run an experiment where you change the frequency at which newsletters of each type are sent out. This experiment includes two variables:</p>
<ul>
  <li>$x$, the change from the current frequency in percent terms for email type 1. In the experiment this varied in the range $[-10\%, 10\%]$, as you considered an increase in the frequency as large as 10% and a decrease of the same magnitude.</li>
  <li>$y$, the change from the current frequency in percent terms for email type 2. This also was varied in the range $[-10\%, 10\%]$.</li>
</ul>

<p>In your experiment, you tried a large number of combinations of $x$ and $y$ in the range $[-10\%, 10\%]$. You’d like to know: <strong>based on your experiment data, what frequency of email sends will maximize revenue?</strong> In order to learn this, you fit a quadratic model to your experimental data, estimating the revenue function $r$:</p>

<p>$r(x, y) = \alpha + \beta_x x + \beta_y y + \beta_{x2} x^2 + \beta_{y2} y^2 + \beta_{xy} xy$</p>

<p>We can now learn where the maxima of the function are, doing some basic calculus.</p>

<p>Again, we start with our imports:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">sympy</span> <span class="k">as</span> <span class="n">sm</span>
<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">from</span> <span class="nn">sklearn.utils.extmath</span> <span class="kn">import</span> <span class="n">cartesian</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.ticker</span> <span class="k">as</span> <span class="n">mtick</span>
</code></pre></div></div>

<p>Next, we define symbols for the model. We have the experiment variables $x$ and $y$, plus all the free parameters of our model, and the revenue function.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">alpha</span><span class="p">,</span> <span class="n">beta_x</span><span class="p">,</span> <span class="n">beta_y</span><span class="p">,</span> <span class="n">beta_xy</span><span class="p">,</span> <span class="n">beta_x2</span><span class="p">,</span> <span class="n">beta_y2</span> <span class="o">=</span> <span class="n">sm</span><span class="p">.</span><span class="n">symbols</span><span class="p">(</span><span class="s">'x y alpha beta_x beta_y beta_xy beta_x2 beta_y2'</span><span class="p">)</span>

<span class="n">rev</span> <span class="o">=</span> <span class="n">alpha</span> <span class="o">+</span> <span class="n">beta_x</span><span class="o">*</span><span class="n">x</span> <span class="o">+</span> <span class="n">beta_y</span><span class="o">*</span><span class="n">y</span> <span class="o">+</span> <span class="n">beta_xy</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="o">+</span> <span class="n">beta_x2</span><span class="o">*</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="n">beta_y2</span><span class="o">*</span><span class="n">y</span><span class="o">**</span><span class="mi">2</span> 
</code></pre></div></div>

<p>We’ll find the critical points by using the <a href="https://en.wikipedia.org/wiki/Second_partial_derivative_test">usual method from calculus</a>, that is by finding the points where $\frac{dr}{dx} = 0$ and $\frac{dr}{dy} = 0$.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">critical_points</span> <span class="o">=</span> <span class="n">sm</span><span class="p">.</span><span class="n">solve</span><span class="p">([</span><span class="n">sm</span><span class="p">.</span><span class="n">Eq</span><span class="p">(</span><span class="n">rev</span><span class="p">.</span><span class="n">diff</span><span class="p">(</span><span class="n">var</span><span class="p">),</span> <span class="mi">0</span><span class="p">)</span> <span class="k">for</span> <span class="n">var</span> <span class="ow">in</span> <span class="p">[</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">]],</span> <span class="p">[</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">])</span>

<span class="k">print</span><span class="p">(</span><span class="n">sm</span><span class="p">.</span><span class="n">latex</span><span class="p">(</span><span class="n">critical_points</span><span class="p">[</span><span class="n">x</span><span class="p">]))</span>
<span class="k">print</span><span class="p">(</span><span class="n">sm</span><span class="p">.</span><span class="n">latex</span><span class="p">(</span><span class="n">critical_points</span><span class="p">[</span><span class="n">y</span><span class="p">]))</span>
</code></pre></div></div>

<p>We find that the critical points are:</p>

<p>$x_* = \frac{- 2 \beta_{x} \beta_{y2} + \beta_{xy} \beta_{y}}{4 \beta_{x2} \beta_{y2} - \beta_{xy}^{2}}$
$y_* = \frac{\beta_{x} \beta_{xy} - 2 \beta_{x2} \beta_{y}}{4 \beta_{x2} \beta_{y2} - \beta_{xy}^{2}}$</p>

<p>This gives us the general solution - if we estimate the coefficients from our data set, we can find the mix that maximizes revenue.</p>

<p>Let’s say that we fit the model from the data, and that we got the following estimated coefficient values:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">coefficient_values</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">(</span><span class="n">alpha</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span>
<span class="p">(</span><span class="n">beta_x</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> 
<span class="p">(</span><span class="n">beta_y</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> 
<span class="p">(</span><span class="n">beta_xy</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">),</span> 
<span class="p">(</span><span class="n">beta_x2</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">),</span> 
<span class="p">(</span><span class="n">beta_y2</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">)</span>
<span class="p">]</span>
</code></pre></div></div>

<p>We <code class="language-plaintext highlighter-rouge">subs</code>titute the estimated coefficients into the revenue function:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">rev_from_experiment</span> <span class="o">=</span> <span class="n">rev</span><span class="p">.</span><span class="n">subs</span><span class="p">(</span><span class="n">coefficient_values</span><span class="p">)</span>
</code></pre></div></div>

<p>That code generated a symbolic function. Let’s use it to create a numpy function which we can evaluate quickly using <code class="language-plaintext highlighter-rouge">lambdify</code>:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">numpy_rev_from_experiment</span> <span class="o">=</span> <span class="n">sm</span><span class="p">.</span><span class="n">lambdify</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">),</span> <span class="n">rev_from_experiment</span><span class="p">)</span>
</code></pre></div></div>

<p>Then, we’ll plot the revenue surface over the experiment space, and plot the maximum we found analytically:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">gca</span><span class="p">().</span><span class="n">yaxis</span><span class="p">.</span><span class="n">set_major_formatter</span><span class="p">(</span><span class="n">mtick</span><span class="p">.</span><span class="n">PercentFormatter</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="n">plt</span><span class="p">.</span><span class="n">gca</span><span class="p">().</span><span class="n">xaxis</span><span class="p">.</span><span class="n">set_major_formatter</span><span class="p">(</span><span class="n">mtick</span><span class="p">.</span><span class="n">PercentFormatter</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>

<span class="n">x_y_pairs</span> <span class="o">=</span> <span class="n">cartesian</span><span class="p">([</span><span class="n">np</span><span class="p">.</span><span class="n">linspace</span><span class="p">(</span><span class="o">-</span><span class="p">.</span><span class="mi">1</span><span class="p">,</span> <span class="p">.</span><span class="mi">1</span><span class="p">),</span> <span class="n">np</span><span class="p">.</span><span class="n">linspace</span><span class="p">(</span><span class="o">-</span><span class="p">.</span><span class="mi">1</span><span class="p">,</span> <span class="p">.</span><span class="mi">1</span><span class="p">)])</span>
<span class="n">z</span> <span class="o">=</span> <span class="p">[</span><span class="n">numpy_rev_from_experiment</span><span class="p">(</span><span class="n">x_i</span><span class="p">,</span> <span class="n">y_i</span><span class="p">)</span> <span class="k">for</span> <span class="n">x_i</span><span class="p">,</span> <span class="n">y_i</span> <span class="ow">in</span> <span class="n">x_y_pairs</span><span class="p">]</span>

<span class="n">x_plot</span><span class="p">,</span> <span class="n">y_plot</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">x_y_pairs</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">tricontourf</span><span class="p">(</span><span class="n">x_plot</span><span class="p">,</span> <span class="n">y_plot</span><span class="p">,</span> <span class="n">z</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">colorbar</span><span class="p">(</span><span class="n">label</span><span class="o">=</span><span class="s">'Revenue per user'</span><span class="p">)</span>

<span class="n">x_star</span> <span class="o">=</span> <span class="n">critical_points</span><span class="p">[</span><span class="n">x</span><span class="p">].</span><span class="n">subs</span><span class="p">(</span><span class="n">coefficient_values</span><span class="p">)</span>
<span class="n">y_star</span> <span class="o">=</span> <span class="n">critical_points</span><span class="p">[</span><span class="n">y</span><span class="p">].</span><span class="n">subs</span><span class="p">(</span><span class="n">coefficient_values</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">scatter</span><span class="p">([</span><span class="n">x_star</span><span class="p">],</span> <span class="p">[</span><span class="n">y_star</span><span class="p">],</span> <span class="n">marker</span><span class="o">=</span><span class="s">'x'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Revenue-maximizing choice'</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Change in frequency of email type 1'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Change in frequency of email type 2'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Revenue surface from experimental data'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">tight_layout</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/sympy/Figure_1.png" alt="Contour plot" /></p>

<p>And there you have it! We’ve used our expression for the maximum of the model to find the value of $x$ and $y$ that maximizes revenue. I’ll note here that in a full experimental analysis, you would want to do more than just this: you’d also want to check the specification of your quadratic model, and consider the uncertainty around the maximum. In practice, I’d probably do this by running a Bayesian version of the quadratic regression and getting the joint posterior of the critical points. You could probably also do some Taylor expanding to come up with standard errors for these, if you wanted to do <em>even more</em> calculus.</p>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[My job seems to involve just enough calculus that I can’t afford to forget it, but little enough that I always feel rusty when I need to do it. In those cases, I’m thankful to be able to check my work and make it reproducible with Sympy, a symbolic mathematics library in Python. Here are two examples of recent places I’ve used Sympy to do calculus. We’ll start by computing the expected value of a distribution by doing a symbolic definite integral. Then, we’ll find the maximum of a model by finding its partial derivatives symbolically, and setting it to zero.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/sympy.png" /><media:content medium="image" url="https://lmc2179.github.io/sympy.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Describing and Forecasting time series: Autoregressive models in Python</title><link href="https://lmc2179.github.io/posts/autoreg.html" rel="alternate" type="text/html" title="Describing and Forecasting time series: Autoregressive models in Python" /><published>2021-07-21T00:00:00+00:00</published><updated>2021-07-21T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/autoreg</id><content type="html" xml:base="https://lmc2179.github.io/posts/autoreg.html"><![CDATA[<p><em>Plenty of problems confronted by practicing data scientists have a time series component. Luckily, building time series models for forecasting and description is easy in statsmodels. We’ll walk through a forecasting problem using an autoregressive model with covariates (AR-X) model in Python.</em></p>

<h1 id="time-series-data-is-everywhere">Time series data is everywhere</h1>

<p>For practicing data scientists, time series data is everywhere - almost anything we care to observe can be observed over time. Some use cases that have shown up frequently in my work are:</p>
<ul>
  <li><strong>Monitoring metrics and KPIs</strong>: We use KPIs to understand some aspect of the business as it changes over time. We often want to model changes in KPIs to see what affects them, or construct a forecast for them into the near future.</li>
  <li><strong>Capacity planning</strong>: Many businesses have seasonal changes in their demand or supply. Understanding these trends helps us make sure we have enough production, bandwidth, sales staff, etc as conditions change.</li>
  <li><strong>Understanding the rollout of a new treatment or policy</strong>: As a new policy takes effect, what results do we see? How do our measurements compare with what we expected? By comparing post-treatment observations to a forecast, or including treatment indicators in the model, we can get an understanding of this.</li>
</ul>

<p>Each of these use cases is a combination of <strong>description</strong> (understanding the structure of the series as we observe it) and <strong>forecasting</strong> (predicting how the series will look in the future). We can perform both of these tasks using the implementation of Autoregressive models in Python found in statsmodels.</p>

<h1 id="example-airline-passenger-forecasting-and-the-ar-xp-model">Example: Airline passenger forecasting and the AR-X(p) model</h1>

<p>We’ll use a time series of <a href="https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv">monthly airline passenger counts from 1949 to 1960</a> in this example. An airline or shipping company might use this for capacity planning.</p>

<p>We’ll read in the data using pandas:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">patsy</span> <span class="kn">import</span> <span class="n">dmatrix</span><span class="p">,</span> <span class="n">build_design_matrices</span>

<span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s">'airline.csv'</span><span class="p">)</span>

<span class="n">df</span><span class="p">[</span><span class="s">'log_passengers'</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">)</span>

<span class="n">df</span><span class="p">[</span><span class="s">'year'</span><span class="p">]</span> <span class="o">=</span> <span class="n">df</span><span class="p">[</span><span class="s">'Month'</span><span class="p">].</span><span class="nb">apply</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="nb">int</span><span class="p">(</span><span class="n">x</span><span class="p">.</span><span class="n">split</span><span class="p">(</span><span class="s">'-'</span><span class="p">)[</span><span class="mi">0</span><span class="p">]))</span>
<span class="n">df</span><span class="p">[</span><span class="s">'month_number'</span><span class="p">]</span> <span class="o">=</span> <span class="n">df</span><span class="p">[</span><span class="s">'Month'</span><span class="p">].</span><span class="nb">apply</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="nb">int</span><span class="p">(</span><span class="n">x</span><span class="p">.</span><span class="n">split</span><span class="p">(</span><span class="s">'-'</span><span class="p">)[</span><span class="mi">1</span><span class="p">]))</span>
<span class="n">df</span><span class="p">[</span><span class="s">'t'</span><span class="p">]</span> <span class="o">=</span> <span class="n">df</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="n">values</span>
</code></pre></div></div>

<p>Then, we’ll split it into three segments: training, model selection, and forecasting. We’ll select the complexity of the model using the model selection set as a holdout, and then attempt to forecast into the future on the forecasting set. Note that this is time series data, so we need to split the data set into three sequential groups, rather than splitting it randomly. We’ll use a model selection/forecasting set of about 24 months each, a plausible period of time for an airline to forecast demand.</p>

<p>Note that we’ll use patsy’s <code class="language-plaintext highlighter-rouge">dmatrix</code> to turn the month number into a set of categorical dummy variables. This corresponds to the R-style formula <code class="language-plaintext highlighter-rouge">C(month_number)-1</code>; we could insert whatever R-style formula we like here to generate the design matrix for the additional factor matrix $X$ in the model above.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">train_cutoff</span> <span class="o">=</span> <span class="mi">96</span>
<span class="n">validate_cutoff</span> <span class="o">=</span> <span class="mi">120</span>

<span class="n">train_df</span> <span class="o">=</span> <span class="n">df</span><span class="p">[</span><span class="n">df</span><span class="p">[</span><span class="s">'t'</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="n">train_cutoff</span><span class="p">]</span>
<span class="n">select_df</span> <span class="o">=</span> <span class="n">df</span><span class="p">[(</span><span class="n">df</span><span class="p">[</span><span class="s">'t'</span><span class="p">]</span> <span class="o">&gt;</span> <span class="n">train_cutoff</span><span class="p">)</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s">'t'</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="n">validate_cutoff</span><span class="p">)]</span>
<span class="n">forecast_df</span> <span class="o">=</span> <span class="n">df</span><span class="p">[</span><span class="n">df</span><span class="p">[</span><span class="s">'t'</span><span class="p">]</span> <span class="o">&gt;</span> <span class="n">validate_cutoff</span><span class="p">]</span>

<span class="n">dm</span> <span class="o">=</span> <span class="n">dmatrix</span><span class="p">(</span><span class="s">'C(month_number)-1'</span><span class="p">,</span> <span class="n">df</span><span class="p">)</span>
<span class="n">train_exog</span> <span class="o">=</span> <span class="n">build_design_matrices</span><span class="p">([</span><span class="n">dm</span><span class="p">.</span><span class="n">design_info</span><span class="p">],</span> <span class="n">train_df</span><span class="p">,</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dataframe'</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">select_exog</span> <span class="o">=</span> <span class="n">build_design_matrices</span><span class="p">([</span><span class="n">dm</span><span class="p">.</span><span class="n">design_info</span><span class="p">],</span> <span class="n">select_df</span><span class="p">,</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dataframe'</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">forecast_exog</span> <span class="o">=</span> <span class="n">build_design_matrices</span><span class="p">([</span><span class="n">dm</span><span class="p">.</span><span class="n">design_info</span><span class="p">],</span> <span class="n">forecast_df</span><span class="p">,</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dataframe'</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
</code></pre></div></div>

<p>Let’s visualize the training and model selection data:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">train_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Training data'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">select_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">select_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Model selection holdout'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Airline passengers by month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Total passengers'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>

</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_1.png" alt="Plot of data" /></p>

<p>We can observe a few features of this data set which will show up in our model:</p>
<ul>
  <li>On the first date observed, the value is non-zero</li>
  <li>There is a positive trend</li>
  <li>There are regular cycles of 12 months</li>
  <li>The next point is close to the last point</li>
</ul>

<p>Our model will include:</p>
<ul>
  <li>An intercept term, representing the value at t = 0</li>
  <li>A linear trend term</li>
  <li>A set of lag terms, encoding how the next observation depends on those just before it</li>
  <li>A set of “additional factors”, which in our case will be dummy variables for the months of the year</li>
  <li>A <a href="https://otexts.com/fpp2/wn.html">white noise term</a>, the time-series analogue of IID Gaussian noise (the two are <a href="https://dsp.stackexchange.com/questions/23881/what-is-the-difference-between-i-i-d-noise-and-white-noise">not quite identical</a>, but the differences aren’t relevant here)</li>
</ul>

<p>Formally, the model we’ll use looks like this:</p>

\[log \underbrace{y_t}_\textrm{Outcome at time t} \sim
\underbrace{\alpha}_\textrm{Intercept} 
+ \underbrace{\gamma t}_\textrm{Trend}
+ \underbrace{(\sum_{i=1}^{p} \phi_i y_{t-i})}_\textrm{Lag terms} 
+ \underbrace{\beta X_t}_\textrm{Extra factors}
+ \underbrace{\epsilon_t}_\textrm{White Noise}\]

<p>The model above is a type of autoregressive model (so named because the target variable is regressed on lagged versions of itself). More precisely, this gives us the <a href="https://www.statsmodels.org/stable/generated/statsmodels.tsa.ar_model.AutoReg.html">AR-X(p) model</a>, an <a href="https://otexts.com/fpp2/AR.html">AR(p) model</a> with extra inputs.</p>

<p>As we’ve <a href="https://lmc2179.github.io/posts/multiplicative.html">previously discussed in this post</a>, it makes sense to take the log of the dependent variable here.</p>

<p>There’s one hyperparameter in this model - the number of lag terms to include, called $p$. For now we’ll set $p=5$, but we’ll tune this later with cross validation. Let’s fit the model, and see how the in-sample fit looks for our training set:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">statsmodels.tsa.ar_model</span> <span class="kn">import</span> <span class="n">AutoReg</span>

<span class="n">ar_model</span> <span class="o">=</span> <span class="n">AutoReg</span><span class="p">(</span><span class="n">endog</span><span class="o">=</span><span class="n">train_df</span><span class="p">.</span><span class="n">log_passengers</span><span class="p">,</span> <span class="n">exog</span><span class="o">=</span><span class="n">train_exog</span><span class="p">,</span> <span class="n">lags</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">trend</span><span class="o">=</span><span class="s">'ct'</span><span class="p">)</span>
<span class="n">ar_fit</span> <span class="o">=</span> <span class="n">ar_model</span><span class="p">.</span><span class="n">fit</span><span class="p">()</span>

<span class="n">train_log_pred</span> <span class="o">=</span> <span class="n">ar_fit</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="n">train_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">min</span><span class="p">(),</span> <span class="n">end</span><span class="o">=</span><span class="n">train_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">max</span><span class="p">(),</span> <span class="n">exog</span><span class="o">=</span><span class="n">train_exog</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">train_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Training data'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
         <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">train_log_pred</span><span class="p">),</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'In-sample prediction'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Airline passengers by month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Total passengers'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_2.png" alt="In-sample fit" /></p>

<p>So far, so good! Since we’re wary of overfitting, we’ll check the out-of-sample fit in the next section. Before we do, I want to point out that we can call <code class="language-plaintext highlighter-rouge">summary()</code> on the AR model to see the usual regression output:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">print</span><span class="p">(</span><span class="n">ar_fit</span><span class="p">.</span><span class="n">summary</span><span class="p">())</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                            AutoReg Model Results
==============================================================================
Dep. Variable:         log_passengers   No. Observations:                  121
Model:                  AutoReg-X(17)   Log Likelihood                 224.797
Method:               Conditional MLE   S.D. of innovations              0.028
Date:                Fri, 16 Jul 2021   AIC                             -6.546
Time:                        10:11:20   BIC                             -5.732
Sample:                            17   HQIC                            -6.216
                                  121
=======================================================================================
                          coef    std err          z      P&gt;|z|      [0.025      0.975]
---------------------------------------------------------------------------------------
intercept               1.0672      0.461      2.314      0.021       0.163       1.971
trend                   0.0023      0.001      1.980      0.048    2.31e-05       0.005
log_passengers.L1       0.6367      0.092      6.958      0.000       0.457       0.816
log_passengers.L2       0.2344      0.109      2.151      0.031       0.021       0.448
log_passengers.L3      -0.0890      0.111     -0.799      0.425      -0.308       0.129
log_passengers.L4      -0.1726      0.110     -1.576      0.115      -0.387       0.042
log_passengers.L5       0.2048      0.108      1.900      0.057      -0.007       0.416
log_passengers.L6       0.0557      0.111      0.504      0.615      -0.161       0.272
log_passengers.L7      -0.1228      0.110     -1.113      0.266      -0.339       0.093
log_passengers.L8      -0.0741      0.111     -0.667      0.505      -0.292       0.143
log_passengers.L9       0.1571      0.111      1.418      0.156      -0.060       0.374
log_passengers.L10     -0.0411      0.112     -0.367      0.713      -0.260       0.178
log_passengers.L11      0.0325      0.111      0.292      0.771      -0.186       0.251
log_passengers.L12      0.0735      0.112      0.654      0.513      -0.147       0.294
log_passengers.L13      0.0475      0.111      0.429      0.668      -0.169       0.264
log_passengers.L14     -0.0263      0.109     -0.240      0.810      -0.241       0.188
log_passengers.L15      0.0049      0.109      0.045      0.964      -0.208       0.218
log_passengers.L16     -0.2845      0.105     -2.705      0.007      -0.491      -0.078
log_passengers.L17      0.1254      0.094      1.339      0.181      -0.058       0.309
C(month_number)[1]      0.0929      0.053      1.738      0.082      -0.012       0.198
C(month_number)[2]      0.0067      0.050      0.134      0.893      -0.091       0.105
C(month_number)[3]      0.1438      0.044      3.250      0.001       0.057       0.230
C(month_number)[4]      0.1006      0.045      2.233      0.026       0.012       0.189
C(month_number)[5]      0.0541      0.048      1.123      0.261      -0.040       0.149
C(month_number)[6]      0.1553      0.047      3.290      0.001       0.063       0.248
C(month_number)[7]      0.2453      0.050      4.897      0.000       0.147       0.343
C(month_number)[8]      0.1108      0.056      1.990      0.047       0.002       0.220
C(month_number)[9]     -0.0431      0.055     -0.785      0.433      -0.151       0.065
C(month_number)[10]     0.0151      0.053      0.283      0.777      -0.089       0.120
C(month_number)[11]     0.0165      0.053      0.311      0.756      -0.087       0.120
C(month_number)[12]     0.1692      0.053      3.207      0.001       0.066       0.273
</code></pre></div></div>

<p>In this case, we see that there’s a positive intercept, a positive trend, and a spike in travel over the summary (months 6, 7, 8) and the winter holidays (month 12).</p>

<h1 id="model-checking-and-model-selection">Model checking and model selection</h1>

<p>Since our in-sample fit looked good, let’s see how the $p=5$ model performs out-of-sample.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">select_log_pred</span> <span class="o">=</span> <span class="n">ar_fit</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="n">select_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">min</span><span class="p">(),</span> <span class="n">end</span><span class="o">=</span><span class="n">select_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">max</span><span class="p">(),</span> <span class="n">exog_oos</span><span class="o">=</span><span class="n">select_exog</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">train_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Training data'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">select_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">select_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Model selection holdout'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
         <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">train_log_pred</span><span class="p">),</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'In-sample prediction'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">select_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
         <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">select_log_pred</span><span class="p">),</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Validation set prediction'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Airline passengers by month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Total passengers'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_3.png" alt="OoS fit" /></p>

<p>Visually, this seems pretty good - our model seems to capture the long-term trend and cyclic structure of the data. However, our choice of $p=5$ was a guess; perhaps a more or less complex model (that is, a model with more or fewer lag terms) would perform better. We’ll perform cross-validation by trying different values of $p$ with the holdout set.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="kn">import</span> <span class="n">sem</span>

<span class="n">lag_values</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">40</span><span class="p">)</span>
<span class="n">mse</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">error_sem</span> <span class="o">=</span> <span class="p">[]</span>

<span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">lag_values</span><span class="p">:</span>
    <span class="n">ar_model</span> <span class="o">=</span> <span class="n">AutoReg</span><span class="p">(</span><span class="n">endog</span><span class="o">=</span><span class="n">train_df</span><span class="p">.</span><span class="n">log_passengers</span><span class="p">,</span> <span class="n">exog</span><span class="o">=</span><span class="n">train_exog</span><span class="p">,</span> <span class="n">lags</span><span class="o">=</span><span class="n">p</span><span class="p">,</span> <span class="n">trend</span><span class="o">=</span><span class="s">'ct'</span><span class="p">)</span>
    <span class="n">ar_fit</span> <span class="o">=</span> <span class="n">ar_model</span><span class="p">.</span><span class="n">fit</span><span class="p">()</span>
    
    <span class="n">select_log_pred</span> <span class="o">=</span> <span class="n">ar_fit</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="n">select_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">min</span><span class="p">(),</span> <span class="n">end</span><span class="o">=</span><span class="n">select_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">max</span><span class="p">(),</span> <span class="n">exog_oos</span><span class="o">=</span><span class="n">select_exog</span><span class="p">)</span>
    <span class="n">select_resid</span> <span class="o">=</span> <span class="n">select_df</span><span class="p">.</span><span class="n">Passengers</span> <span class="o">-</span> <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">select_log_pred</span><span class="p">)</span>
    <span class="n">mse</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">select_resid</span><span class="o">**</span><span class="mi">2</span><span class="p">))</span>
    <span class="n">error_sem</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">sem</span><span class="p">(</span><span class="n">select_resid</span><span class="o">**</span><span class="mi">2</span><span class="p">))</span>
    
<span class="n">mse</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">(</span><span class="n">mse</span><span class="p">)</span>
<span class="n">error_sem</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">(</span><span class="n">error_sem</span><span class="p">)</span>
    
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">lag_values</span><span class="p">,</span> <span class="n">mse</span><span class="p">,</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">fill_between</span><span class="p">(</span><span class="n">lag_values</span><span class="p">,</span> <span class="n">mse</span> <span class="o">-</span> <span class="n">error_sem</span><span class="p">,</span> <span class="n">mse</span> <span class="o">+</span> <span class="n">error_sem</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="p">.</span><span class="mi">1</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Lag Length P'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'MSE'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Lag length vs error'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_4.png" alt="Lag selection" /></p>

<p>Adding more lags seems to improve the model, but has diminishing returns. We’ve computed a standard error on the average squared residual. Using the <a href="https://lmc2179.github.io/posts/cvci.html">one standard error rule</a>, we’ll pick $p=17$, the lag which is smallest but within 1 standard error of the best model.</p>

<p>Now that we’ve picked the lag length, let’s see whether the model assumptions hold. When we subtract out the predictions of our model, we should be left with something that looks like Gaussian white noise - errors which are normally distributed around zero, and which have no autocorrelection. Let’s start by</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">train_and_select_df</span> <span class="o">=</span> <span class="n">df</span><span class="p">[</span><span class="n">df</span><span class="p">[</span><span class="s">'t'</span><span class="p">]</span> <span class="o">&lt;=</span> <span class="n">validate_cutoff</span><span class="p">]</span>
<span class="n">train_and_select_exog</span> <span class="o">=</span> <span class="n">build_design_matrices</span><span class="p">([</span><span class="n">dm</span><span class="p">.</span><span class="n">design_info</span><span class="p">],</span> <span class="n">train_and_select_df</span><span class="p">,</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dataframe'</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>

<span class="n">ar_model</span> <span class="o">=</span> <span class="n">AutoReg</span><span class="p">(</span><span class="n">endog</span><span class="o">=</span><span class="n">train_and_select_df</span><span class="p">.</span><span class="n">log_passengers</span><span class="p">,</span> 
                   <span class="n">exog</span><span class="o">=</span><span class="n">train_and_select_exog</span><span class="p">,</span> <span class="n">lags</span><span class="o">=</span><span class="mi">17</span><span class="p">,</span> <span class="n">trend</span><span class="o">=</span><span class="s">'ct'</span><span class="p">)</span>
<span class="n">ar_fit</span> <span class="o">=</span> <span class="n">ar_model</span><span class="p">.</span><span class="n">fit</span><span class="p">()</span>

<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Residuals'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">ar_fit</span><span class="p">.</span><span class="n">resid</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_5.png" alt="Residual plot" /></p>

<p>The mean residual is about zero. If I run <code class="language-plaintext highlighter-rouge">np.mean</code> and <code class="language-plaintext highlighter-rouge">sem</code>, we see that average residual is 3.2e-14, with a standard error of .003. So this does appear to be centered around zero. To see if it’s uncorrelated with itself, we’ll compute the <a href="https://en.wikipedia.org/wiki/Partial_autocorrelation_function">partial autocorrelation</a>.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">statsmodels.graphics.tsaplots</span> <span class="kn">import</span> <span class="n">plot_pacf</span>

<span class="n">plot_pacf</span><span class="p">(</span><span class="n">ar_fit</span><span class="p">.</span><span class="n">resid</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_6.png" alt="PACF plot" /></p>

<p>This plot is exactly what we’d hope to see - we can’t find any lag for which there is a non-zero partial autocorrelation.</p>

<h1 id="producing-forecasts-and-prediction-intervals">Producing forecasts and prediction intervals</h1>

<p>So far we’ve selected a model, and confirm the model assumptions. Now, let’s re-fit the model up to the forecast period, and see how we do on some new dates.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">train_and_select_log_pred</span> <span class="o">=</span> <span class="n">ar_fit</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="n">train_and_select_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">min</span><span class="p">(),</span> <span class="n">end</span><span class="o">=</span><span class="n">train_and_select_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">max</span><span class="p">(),</span> <span class="n">exog_oos</span><span class="o">=</span><span class="n">train_and_select_exog</span><span class="p">)</span>
<span class="n">forecast_log_pred</span> <span class="o">=</span> <span class="n">ar_fit</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="n">forecast_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">min</span><span class="p">(),</span> <span class="n">end</span><span class="o">=</span><span class="n">forecast_df</span><span class="p">.</span><span class="n">t</span><span class="p">.</span><span class="nb">max</span><span class="p">(),</span> <span class="n">exog_oos</span><span class="o">=</span><span class="n">forecast_exog</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_and_select_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">train_and_select_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Training data'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">forecast_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">forecast_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Out-of-sample'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_and_select_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
         <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">train_and_select_log_pred</span><span class="p">),</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'In-sample prediction'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">forecast_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
         <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">forecast_log_pred</span><span class="p">),</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Forecast'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Airline passengers by month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Total passengers'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_7.png" alt="Forecast demo" /></p>

<p>Our predictions look pretty good! Our selected model performs well when forecasting data it did not see during the training or model selection process. The predictions are arrived at recursively - so by predicting next month’s value, then using that to predict the month after that, etc. <code class="language-plaintext highlighter-rouge">statsmodels</code> hides that annoying recursion behind a nice interface, letting us get a point forecast out into the future.</p>

<p>In addition to a point prediction, it’s often useful to make an interval prediction. For example:</p>
<ul>
  <li>In capacity planning you often want to know the largest value that might occur in the future</li>
  <li>In risk management you often want to know the smallest value that your investments might produce in the future</li>
  <li>When monitoring metrics, you might want to know whether the observed value is within the bounds of what we expect.</li>
</ul>

<p>Because our prediction is recursive, our prediction intervals will get wider as the forecast range gets further out. I think this makes intuitive sense; forecasts of the distance future are harder than the immediate future, since errors pile up more and more as you go further out in time.</p>

<p>More formally, our white noise has some standard deviation, say $\sigma$. We can get a point estimate, $\hat{\sigma}$ by looking at the standard deviation of the residuals. In that case, a 95% prediction interval for the next time step is $\pm 1.96 \hat{\sigma}$. If we want to forecast two periods in the future, we’re adding two white noise steps to our prediction, meaning the prediction interval is $\pm 1.96 \sqrt{2 \hat{\sigma}^2}$ since the <a href="https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables">the variance of the sum is the sum of the variances</a>. In general, the prediction interval for $k$ time steps in the future is $\pm 1.96 \sqrt{k \hat{\sigma}^2}$.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">residual_variance</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">var</span><span class="p">(</span><span class="n">ar_fit</span><span class="p">.</span><span class="n">resid</span><span class="p">)</span>
<span class="n">prediction_interval_variance</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">forecast_df</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span> <span class="o">*</span> <span class="n">residual_variance</span>
<span class="n">forecast_log_pred_lower</span> <span class="o">=</span> <span class="n">forecast_log_pred</span> <span class="o">-</span> <span class="mf">1.96</span><span class="o">*</span><span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">prediction_interval_variance</span><span class="p">)</span>
<span class="n">forecast_log_pred_upper</span> <span class="o">=</span> <span class="n">forecast_log_pred</span> <span class="o">+</span> <span class="mf">1.96</span><span class="o">*</span><span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">prediction_interval_variance</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_and_select_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">train_and_select_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Training data'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">forecast_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> <span class="n">forecast_df</span><span class="p">.</span><span class="n">Passengers</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Out-of-sample'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">train_and_select_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
         <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">train_and_select_log_pred</span><span class="p">),</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'In-sample prediction'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">forecast_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
         <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">forecast_log_pred</span><span class="p">),</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dashed'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Forecast'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">fill_between</span><span class="p">(</span><span class="n">forecast_df</span><span class="p">.</span><span class="n">t</span><span class="p">,</span> 
        <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">forecast_log_pred_lower</span><span class="p">),</span> <span class="n">np</span><span class="p">.</span><span class="n">exp</span><span class="p">(</span><span class="n">forecast_log_pred_upper</span><span class="p">),</span> 
        <span class="n">label</span><span class="o">=</span><span class="s">'Prediction interval'</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="p">.</span><span class="mi">1</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Airline passengers by month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Total passengers'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/autoreg/Figure_8.png" alt="Prediction intervals" /></p>

<p>And there we have it! Our prediction intervals fully cover the observations in the forecast period; note how the intervals become wider as the forecast window gets larger.</p>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[Plenty of problems confronted by practicing data scientists have a time series component. Luckily, building time series models for forecasting and description is easy in statsmodels. We’ll walk through a forecasting problem using an autoregressive model with covariates (AR-X) model in Python.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/autoreg.png" /><media:content medium="image" url="https://lmc2179.github.io/autoreg.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Machine learning models for decision making in Python: Picking thresholds for asymmetric payoffs</title><link href="https://lmc2179.github.io/posts/decisions.html" rel="alternate" type="text/html" title="Machine learning models for decision making in Python: Picking thresholds for asymmetric payoffs" /><published>2021-07-10T00:00:00+00:00</published><updated>2021-07-10T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/decisions</id><content type="html" xml:base="https://lmc2179.github.io/posts/decisions.html"><![CDATA[<p><em>Machine learning practitioners spend a lot of time thinking about whether their model makes good predictions, usually in the form of checking calibration, accuracy, ROC-AUC, precision or recall. But for ML to add value, its predictions need to be harnessed for decision making, not just prediction. We’ll walk through how you can use probabilistic classifiers not just to make accurate predictions, but to make decisions that lead to the best outcomes.</em></p>

<h1 id="machine-learning-gives-us-a-prediction-which-we-use-to-make-a-decision">Machine learning gives us a prediction, which we use to make a decision</h1>

<p>Lots of use cases for ML classifiers in production involve using the classifier to predict whether a newly observed instance is in the class of items we would like to perform some action on. For example:</p>
<ul>
  <li>Systems which try to detect <strong>irrelevant content</strong> on platforms do so because we’d like to <strong>limit the distribution of this content</strong>.</li>
  <li>Systems which try to detect <strong>fraudulent users</strong> do so because we’d like to <strong>ban these users</strong>.</li>
  <li>Systems which try to detect the presence of <strong>treatable illnesses</strong> do so because we’d like to <strong>refer people with illnesses for further testing or treatment</strong>.</li>
</ul>

<p>In all of these cases, there are <strong>two classes: a class that we have targeted for treatment</strong> (irrelevant content, fraudulent users, people with treatable illnesses), and <strong>a class that we’d like to leave alone</strong> (relevant content, legitimate users, healthy people). Some systems choose between more than just these two options, but let’s keep things simple for now. It’s common to have a workflow that goes something like this:</p>

<ol>
  <li>Train the model on historical data. The model will compute the probability that an instance is in the class targeted for treatment.</li>
  <li>Observe the newest instance we want to make a decision about.</li>
  <li>Use our model to predict the probability that this instance belongs to the class we have targeted for action.</li>
  <li>If the probability that the instance is in the targeted class is greater than $\frac{1}{2}$, apply the treatment.</li>
</ol>

<p>The use of $\frac{1}{2}$ as a threshold is a priori pretty reasonable - we’ll end up predicting the class that is more likely for a given instance. It’s so commonly used that it’s the default for the <code class="language-plaintext highlighter-rouge">predict</code> method in <code class="language-plaintext highlighter-rouge">scikit-learn</code>. However, in most real life situations, we’re not just looking for a model that is accurate, we’re looking for a model that helps us make a decision. We need to consider the payoffs and risks of incorrect decisions, and use the probability output by the classifier to make our decision. The main question will be something like: <strong>“How do we use the output of a probabilistic classifier to decide if we should take an action? What threshold should we apply?”</strong>. The answer, it turns out, will depend on whether or not your use case involves asymmetric risks.</p>

<h1 id="a-prototypical-example-disease-detection">A prototypical example: Disease detection</h1>

<p>Assume we’ve used our favorite library to build a model which predicts the probability that an individual has a malignant tumor based on some tests we ran. We’re going to use this prediction to decide whether we want to refer the patient for a more detailed test, which is more accurate but more costly and invasive. Following tradition, we refer to the test data as $X$ and the estimated probability of a malignant tumor as $\hat{y}$. We think, based on cross-validation, that our model proves a well-calibrated estimate of $\mathbb{P}(Cancer \mid X) = \hat{y}$. For some particular patient, we run their test results ($X$) through our model, and compute their probability of a malignant tumor, $\hat{y}$. We’ve used our model to make a prediction, now comes the decision: <em>Should we refer the patient for further, more accurate (but more invasive) testing?</em></p>

<p>There are four possible outcomes of this process:</p>
<ul>
  <li>We <strong>refer</strong> the patient for further testing, but the second test reveals the tumor is <strong>benign</strong>. This means our initial test provided a <strong><em>false positive (FP)</em></strong>.</li>
  <li>We <strong>refer</strong> the patient for further testing, and the second test reveals the tumor is <strong>malignant</strong>. This means our initial test provided a <strong><em>true positive (TP)</em></strong>.</li>
  <li>We <strong>decline</strong> to pursue further testing. Unknown to us, the second test would have shown the tumor is <strong>benign</strong>. This means our initial test provided a <strong><em>true negative (TN)</em></strong>.</li>
  <li>We <strong>decline</strong> to pursue further testing. Unknown to us, the second test would have shown the tumor is <strong>malignant</strong>. This means our initial test provided a <strong><em>false negative (FN)</em></strong>.</li>
</ul>

<p>We can group the outcomes into “bad” outcomes (false positives, false negatives), as well as “good” outcomes (true positives, true negatives). However, there’s a small detail here we need to keep in mind - not all bad outcomes are equally bad. A false positive results in costly testing and psychological distress for the patient, which is certainly an outcome we’d like to avoid; however, a false negative results in an untreated cancer, posing a risk to the patient’s life. There’s an important <strong>asymmetry</strong> here, in that <strong>the cost of a FN is much larger than the cost of a FP</strong>.</p>

<p>Let’s be really specific about the costs of each of these outcomes, by assigning a score to each. Specifically, we’ll say:</p>
<ul>
  <li>In the case of a <strong>True Negative</strong> (correctly detecting that there is no illness), nothing has really changed for the patient. Since this is the status quo case, we’ll assign this outcome <strong>a score of 0</strong>.</li>
  <li>In the case of a <strong>True Positive</strong> (correctly detecting that there is illness), we’ve successfully found someone who needs treatment. While such therapies are notoriously challenging for those who endure them, this is a positive outcome for our system because we’re improving the health of people. We’ll assign this outcome <strong>a score of 1</strong>.</li>
  <li>In the case of a <strong>False Positive</strong> (referring for more testing, which will reveal no illness), we’ve incurred extra costs of testing and inflicted undue distress on the patient. This is a bad outcome, and we’ll assign it <strong>a score of -1</strong>.</li>
  <li>In the case of a <strong>False Negative</strong> (failing to refer for testing, which would have revealed an illness), we’ve let a potentially deadly disease continue to grow. This is a bad outcome, but it’s much worse than the previous one. We’ll assign it <strong>a score of -100, reflecting our belief that it is about 100 times worse than a False Positive</strong>.</li>
</ul>

<p>We’ll write each of these down in the form of a <strong>payoff matrix</strong>, which looks like this:</p>

\[P = 

\begin{bmatrix}
\text{TN value} &amp; \text{FP value}\\ 
\text{FN value} &amp; \text{TP value}
\end{bmatrix}

=

\begin{bmatrix}
0 &amp; -1\\ 
-100 &amp; 1
\end{bmatrix}\]

<p>The matrix here has the same format as the commonly used <a href="https://en.wikipedia.org/wiki/Confusion_matrix">confusion matrix</a>. It is written (in this case) in unitless “utility” points which are relatively interpretable, but for some business problems we could write the matrix in dollars or another convenient unit. This particular matrix implies that a false negative is 100 times worse than a false positive, but that’s based on nothing except my subjective opinion. Some amount of subjectivity (or if you prefer, “expert judgement”) is usually required to set the values of this matrix, and the values are usually up for debate in any given use case. We’ll come back to the choice of specific values here in a bit.</p>

<p>We can now combine our estimate of malignancy probability ($\hat{y}$) with the payoff matrix to compute the expected value of both referring the patient for testing and declining future testing:</p>

\[\mathbb{E}[\text{Send for testing}] = \mathbb{P}(Cancer | X) \times \text{TP value} + (1 - \mathbb{P}(Cancer | X)) \times \text{FP value} \\
= \hat{y} \times 1 + (1 - \hat{y}) \times (-1)
= 2 \hat{y} - 1\]

\[\mathbb{E}[\text{Do not test}] = \mathbb{P}(Cancer | X) \times \text{FN value} + (1 - \mathbb{P}(Cancer | X)) \times \text{TN value} \\
= \hat{y} \times (-100) + (1 - \hat{y}) \times 0
= -100 \hat{y}\]

<p>What value of $\hat{y}$ is large enough that we should refer the patient for further testing? That is - what <strong>threshold</strong> should we use to turn the probabilistic output of our model into a decision to treat? We want to send the patient for testing whenver $\mathbb{E}[\text{Send for testing}] \geq \mathbb{E}[\text{Do not test}]$. So we can set the two expected values equal, and find the point at whch they cross to get <strong>the threshold value, which we’ll call $y_*$</strong>:</p>

<p>\(2 y_* - 1 = -100 y_*\)
\(\Rightarrow y_* = \frac{1}{102}\)</p>

<p>So we should refer a patient for testing whenever $\hat{y} \geq \frac{1}{102}$. This is <em>very</em> different than the aproach we would get if we used the default classifier threshold, which in scikit-learn is $\frac{1}{2}$.</p>

<h1 id="picking-the-best-threshold-and-evaluating-out-of-sample-decision-making-in-python">Picking the best threshold and evaluating out-of-sample decision-making in Python</h1>

<p>We can do a little algebra to show that if we know the 2x2 payoff matrix, then the optimal threshold is:</p>

<p>$y_* = \frac{\text{TN value - FP value}}{\text{TP value + TN value - FP value - FN value}}$</p>

<p>Let’s compute this threshold and apply it to the in-sample predictions in Python:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">sklearn.datasets</span> <span class="kn">import</span> <span class="n">load_breast_cancer</span>
<span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="kn">import</span> <span class="n">LogisticRegression</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span>

<span class="n">payoff</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="p">[</span><span class="o">-</span><span class="mi">100</span><span class="p">,</span> <span class="mi">1</span><span class="p">]])</span>

<span class="n">X</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">load_breast_cancer</span><span class="p">(</span><span class="n">return_X_y</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span> <span class="mi">1</span><span class="o">-</span><span class="n">y</span> <span class="c1"># In the original dataset, 1 = Benign
</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">LogisticRegression</span><span class="p">(</span><span class="n">max_iter</span><span class="o">=</span><span class="mi">10000</span><span class="p">)</span>
<span class="n">model</span><span class="p">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>

<span class="n">y_threshold</span> <span class="o">=</span> <span class="p">(</span><span class="n">payoff</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">-</span> <span class="n">payoff</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">])</span> <span class="o">/</span> <span class="p">(</span><span class="n">payoff</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">payoff</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span> <span class="o">-</span> <span class="n">payoff</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span> <span class="o">-</span> <span class="n">payoff</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">0</span><span class="p">])</span>

<span class="n">send_for_testing</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="n">predict_proba</span><span class="p">(</span><span class="n">X</span><span class="p">)[:,</span><span class="mi">1</span><span class="p">]</span> <span class="o">&gt;=</span> <span class="n">y_threshold</span>
</code></pre></div></div>

<p>Does the $y_*$ we computed lead to optimal decision making on this data set? Let’s find out by computing the average out-of-sample payoff for each threshold:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Cross val - show that the theoretical threshold is the best one for this data
</span>
<span class="kn">from</span> <span class="nn">sklearn.metrics</span> <span class="kn">import</span> <span class="n">confusion_matrix</span>
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">cross_val_predict</span>

<span class="n">y_pred</span> <span class="o">=</span> <span class="n">cross_val_predict</span><span class="p">(</span><span class="n">LogisticRegression</span><span class="p">(</span><span class="n">max_iter</span><span class="o">=</span><span class="mi">10000</span><span class="p">),</span> <span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">method</span><span class="o">=</span><span class="s">'predict_proba'</span><span class="p">)[:,</span><span class="mi">1</span><span class="p">]</span>

<span class="n">thresholds</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">linspace</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="p">.</span><span class="mi">95</span><span class="p">,</span> <span class="mi">1000</span><span class="p">)</span>
<span class="n">avg_payoffs</span> <span class="o">=</span> <span class="p">[]</span>

<span class="k">for</span> <span class="n">threshold</span> <span class="ow">in</span> <span class="n">thresholds</span><span class="p">:</span>
  <span class="n">cm</span> <span class="o">=</span> <span class="n">confusion_matrix</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="n">y_pred</span> <span class="o">&gt;</span> <span class="n">threshold</span><span class="p">)</span>
  <span class="n">avg_payoffs</span> <span class="o">+=</span> <span class="p">[</span><span class="n">np</span><span class="p">.</span><span class="nb">sum</span><span class="p">(</span><span class="n">cm</span> <span class="o">*</span> <span class="n">payoff</span><span class="p">)</span> <span class="o">/</span> <span class="n">np</span><span class="p">.</span><span class="nb">sum</span><span class="p">(</span><span class="n">cm</span><span class="p">)]</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">thresholds</span><span class="p">,</span> <span class="n">avg_payoffs</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Effect of threshold on average payoff'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">axvline</span><span class="p">(</span><span class="n">y_threshold</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'orange'</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dotted'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Theoretically optimal threshold'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Threshold'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Average payoff'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>
<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/decisions/chart_1.png" alt="Threshold vs Average payoff" /></p>

<p>Our $y_*$ is very close to optimal on this data set. It is much better in average payoff terms than the sklearn default of $\frac{1}{2}$.</p>

<p>Note that in the above example we calculate the out-of-sample confusion matrix <code class="language-plaintext highlighter-rouge">cm</code>, and estimate the average out-of-sample payoff as <code class="language-plaintext highlighter-rouge">np.sum(cm * payoff) / np.sum(cm)</code>. <strong>We could also use this as a metric for model selection, letting us directly select the model that makes the best decisions on average.</strong></p>

<h1 id="when-is-the-optimal-threshold-y_--frac12">When <em>is</em> the optimal threshold $y_* = \frac{1}{2}?$</h1>

<p>In the cancer example above, we may think it’s more likely than not that the patient is healthy, yet still refer them for testing. Because the cost of a false negative is so large, the optimal behavior is to act conservatively, recommending testing in all but the most clear-cut cases.</p>

<p>How would things be different if our goal was simply to make our predictions as <em>accurate</em> as possible? In this case we might imagine a payoff matrix like</p>

\[P_{accuracy} = \begin{bmatrix} 1 &amp; 0\\  0 &amp; 1 \end{bmatrix}\]

<p>For this payoff matrix, we are awarded a point for each correct prediction (TP or TN), and no points for incorrect predictions (FP or FN). IF we do the math for this payoff matrix, we see that $y_* = \frac{1}{2}$. That is, the default threshold of $\frac{1}{2}$ makes sense when we want to maximize the prediction accuracy, and there are no asymmetric payoffs. Other “accuracy-like” payoff matrices like</p>

\[P_{accuracy} = \begin{bmatrix} 0 &amp; -1\\  -1 &amp; 0 \end{bmatrix}\]

<p>or perhaps</p>

\[P_{accuracy} = \begin{bmatrix} 1 &amp; -1\\  -1 &amp; 1 \end{bmatrix}\]

<p>also have $y_* = \frac{1}{2}$.</p>

<p>You might at this point wonder whether the $y_* = \frac{1}{2}$ threshold also maximizes other popular metrics under symmetric payoffs, like <a href="https://en.wikipedia.org/wiki/Precision_and_recall">precision and recall</a>. We can define a “precision” payoff matrix (1 point for true positives, -1 point for false positives, 0 otherwise) as something like</p>

\[P_{precision} = \begin{bmatrix} 0 &amp; -1\\  0 &amp; 1 \end{bmatrix}\]

<p>If we plug $P_{precision}$ into the formula from before, we see that  $y_* = \frac{1}{2}$ in this case too.</p>

<p>Repeating the exercise for a “recall-like” matrix (1 point for true positives, -1 point for false negatives, 0 otherwise):</p>

\[P_{recall} = \begin{bmatrix} 0 &amp; 0\\  -1 &amp; 1 \end{bmatrix}\]

<p>This yields something different - for this matrix, $y_* = 0$. This might be initially surprising - but if we inspect the definition of recall, we see that we will not be penalized for false positives, so we might as well treat every instance we come across (this is why it’s often used in tandem with precision, which <em>does</em> penalize false positives).</p>

<h1 id="where-do-the-numbers-in-the-payoff-matrix-come-from">Where do the numbers in the payoff matrix come from?</h1>

<p>In the easiest case, we the know the values a priori, or someone has measured the effects of each outcome. If we know these values in dollars or some other fungible unit, we can plug them right into the payoff matrix. In some cases, you might be able to run an experiment, or a causal analysis, to estimate the values of the matrix. We would expect the payoffs along the main diagonal (TP, TN) to be positive or zero, and the payoffs off the diagonal (FP, FN) to be negative.</p>

<p>If you don’t have those available to you, or there’s no obvious unit of measurement, you can put values into the matrix which accord with your relative preferences between the outcomes. In the cancer example, our choice of payoff matrix reflected our conviction that a FN was 100x worse than a FP - it’s a statement about our preferences, not something we computed from the data. This is not ideal in a lot of ways, but such an encoding of preferences is usually much more realistic than the implicit assumption that payoffs are symmetric, which is what we get when we use the default. When you take this approach, it may be worth running a sensitivity analysis, and understanding how sensitive your ideal threshold is to small changes in your preferences.</p>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[Machine learning practitioners spend a lot of time thinking about whether their model makes good predictions, usually in the form of checking calibration, accuracy, ROC-AUC, precision or recall. But for ML to add value, its predictions need to be harnessed for decision making, not just prediction. We’ll walk through how you can use probabilistic classifiers not just to make accurate predictions, but to make decisions that lead to the best outcomes.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/decision.png" /><media:content medium="image" url="https://lmc2179.github.io/decision.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">What customer group drove the change in my favorite metric? Exact decompositions of change over time</title><link href="https://lmc2179.github.io/posts/metric_decomposition.html" rel="alternate" type="text/html" title="What customer group drove the change in my favorite metric? Exact decompositions of change over time" /><published>2021-03-03T00:00:00+00:00</published><updated>2021-03-03T00:00:00+00:00</updated><id>https://lmc2179.github.io/posts/metric_decomposition</id><content type="html" xml:base="https://lmc2179.github.io/posts/metric_decomposition.html"><![CDATA[<p><em>As analytics professionals, we frequently summarize the state of the business with metrics that measure some aspect of its performance. We check these metrics every day, week, or month, and try to understand what changed them. Often we inspect a few familiar subgroups (maybe your customer regions, or demographics) to understand how much each group contributed to the change. This pattern is so common and so useful that it’s worth noting some general-purpose decompositions that we can use when we come across this problem. This initial perspective can give us the intuition to plan a deeper statistical or causal analysis.</em></p>

<h1 id="are-my-sales-growing-which-customers-are-driving-it">Are my sales growing? Which customers are driving it?</h1>

<p>A <a href="https://en.wikipedia.org/wiki/Performance_indicator">KPI (or metric)</a> is a single-number snapshot of the business that summarizes something we care about. Data Scientists design and track metrics regularly in order to understand how the business is doing - if it’s achieving its goals, where it needs to allocate more resources, and whether anything surprising is happening. When these metrics move (whether that move is positive or negative), we usually want to understand <em>why</em> that happened, so we than think about what (if anything) needs to be done about it. A common tactic for doing this is to think about the different segments that make up your base of customers, and how each one contributed to the way your KPI changed.</p>

<p>A prototypical example is something like a retail store, whose operators make money by selling things to their customers. In order to take a practical look at how metrics might inform our understanding of the business situation, we’ll look at <a href="https://archive.ics.uci.edu/ml/datasets/Online+Retail+II">data from a UK-based online retailer</a> which tracks their total sales and total customers over time for the countries they operate in. As an online retailer, you produce value by selling stuff; you can measure the total volume of stuff you sold by looking at total revenue, and your efficiency by looking at the revenue produced per customer. This kind of retailer might make marketing, product, sales or inventory decisions at the country level, so it would be useful to understand how each country contributed to your sales growth and value growth.</p>

<h1 id="where-did-my-revenue-come-from">Where did my revenue come from</h1>

<p>As a retailer, one reasonable way to measure your business’ success is by looking at your total revenue over time. We’ll refer to the <strong>total revenue in month $t$</strong> as $R_t$. The total revenue is the revenue across each country we operate in, so</p>

\[R_t = r_t^{UK} + r_t^{Germany} + r_t^{Australia} + r_t^{France} + r_t^{Other} = \sum\limits_g r_t^g\]

<p>We’ll use this kind of notation throughout - the superscript (like $g$) indicates the group of customers, the subscript (like $t$) indicates the time period. Our groups will be countries, and our time periods will be months of the year 2011.</p>

<p>We can plot $R_t$ to see how our revenue evolved over time.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">total_rev_df</span> <span class="o">=</span> <span class="n">monthly_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'date'</span><span class="p">).</span><span class="nb">sum</span><span class="p">()</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">total_rev_df</span><span class="p">.</span><span class="n">index</span><span class="p">,</span> <span class="n">total_rev_df</span><span class="p">[</span><span class="s">'revenue'</span><span class="p">]</span> <span class="o">/</span> <span class="mf">1e6</span><span class="p">,</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Monthly revenue'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Total Revenue, millions'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_1.png" alt="Revenue over time" /></p>

<p align="center"><i> A plot of the revenue over time, $ R_t.$ </i></p>

<p>Presumably, if some revenue is good, more must be better; we want to know the <strong>revenue growth</strong> each month. The revenue growth is just this month minus last month:</p>

\[\Delta R_t = R_t - R_{t-1}\]

<p>When $\Delta R_t &gt; 0$, things are getting better. Just like revenue $R_t$, we can plot growth $\Delta R_t$ each month:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">total_rev_df</span><span class="p">.</span><span class="n">index</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> <span class="n">np</span><span class="p">.</span><span class="n">diff</span><span class="p">(</span><span class="n">total_rev_df</span><span class="p">[</span><span class="s">'revenue'</span><span class="p">]</span> <span class="o">/</span> <span class="mf">1e6</span><span class="p">),</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Monthly revenue change'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Month-over-month revenue change, millions'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">axhline</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dotted'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_2.png" alt="Change in revenue over time" /></p>

<p align="center"><i>A plot of the month-over-month change in revenue, $\Delta R_t.$ </i></p>

<p>So far, we’ve tracked revenue and revenue growth. But we haven’t made any statements about which customers groups saw the most growth. We can get a better understanding of which customer groups changed their behavior, increasing or decreasing their spending, by decomposing $\Delta R_t$ by customer group:</p>

\[\Delta R_t = \underbrace{r_t^{UK} - r_{t-1}^{UK}}_\textrm{UK revenue growth} 
+ \underbrace{r_t^{Germany} - r_{t-1}^{Germany}}_\textrm{Germany revenue growth}
+ \underbrace{r_t^{Australia} - r_{t-1}^{Australia}}_\textrm{Australia revenue growth} 
+ \underbrace{r_t^{France} - r_{t-1}^{France}}_\textrm{France revenue growth} 
+ \underbrace{r_t^{Other} - r_{t-1}^{Other}}_\textrm{Other country revenue growth}\]

<p>Or a little more compactly:</p>

\[\Delta R_t = \sum\limits_g (r_t^g - r_{t-1}^g) = \sum\limits_g \Delta R^g_t\]

<p>We can write a quick python function to perform this decomposition:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">decompose_total_rev</span><span class="p">(</span><span class="n">df</span><span class="p">):</span>
  <span class="n">dates</span><span class="p">,</span> <span class="n">date_dfs</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="p">[(</span><span class="n">t</span><span class="p">,</span> <span class="n">t_df</span><span class="p">.</span><span class="n">sort_values</span><span class="p">(</span><span class="s">'country_coarse'</span><span class="p">).</span><span class="n">reset_index</span><span class="p">())</span> <span class="k">for</span> <span class="n">t</span><span class="p">,</span> <span class="n">t_df</span> <span class="ow">in</span> <span class="n">df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'date'</span><span class="p">,</span> <span class="n">sort</span><span class="o">=</span><span class="bp">True</span><span class="p">)])</span>
  <span class="n">first</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
  <span class="n">groups</span> <span class="o">=</span> <span class="n">first</span><span class="p">[</span><span class="s">'country_coarse'</span><span class="p">]</span>
  <span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="s">'total'</span><span class="p">]</span> <span class="o">+</span> <span class="nb">list</span><span class="p">(</span><span class="n">groups</span><span class="p">)</span>
  <span class="n">result_rows</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">empty</span><span class="p">((</span><span class="nb">len</span><span class="p">(</span><span class="n">dates</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">groups</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">))</span>
  <span class="n">result_rows</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">first</span><span class="p">[</span><span class="s">'revenue'</span><span class="p">].</span><span class="nb">sum</span><span class="p">()</span>
  <span class="n">result_rows</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">:]</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
  <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">result_rows</span><span class="p">)):</span>
    <span class="n">result_rows</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="s">'revenue'</span><span class="p">].</span><span class="nb">sum</span><span class="p">()</span>
    <span class="n">result_rows</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="mi">1</span><span class="p">:]</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="s">'revenue'</span><span class="p">]</span> <span class="o">-</span> <span class="n">date_dfs</span><span class="p">[</span><span class="n">t</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="s">'revenue'</span><span class="p">]</span>
  <span class="n">result_df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">result_rows</span><span class="p">,</span> <span class="n">columns</span><span class="o">=</span><span class="n">columns</span><span class="p">)</span>
  <span class="n">result_df</span><span class="p">[</span><span class="s">'date'</span><span class="p">]</span> <span class="o">=</span> <span class="n">dates</span>
  <span class="k">return</span> <span class="n">result_df</span>
</code></pre></div></div>

<p>And then plot the country-level contributions to change:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">ALL_COUNTRIES</span> <span class="o">=</span> <span class="p">[</span><span class="s">'United Kingdom'</span><span class="p">,</span> <span class="s">'Germany'</span><span class="p">,</span> <span class="s">'France'</span><span class="p">,</span> <span class="s">'Australia'</span><span class="p">,</span> <span class="s">'All others'</span><span class="p">]</span>

<span class="n">total_revenue_factors_df</span> <span class="o">=</span> <span class="n">decompose_total_rev</span><span class="p">(</span><span class="n">monthly_df</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Monthly revenue change, by country'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Month-over-month revenue change, millions'</span><span class="p">)</span>

<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">ALL_COUNTRIES</span><span class="p">:</span>
  <span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">total_revenue_factors_df</span><span class="p">[</span><span class="s">'date'</span><span class="p">],</span> <span class="n">total_revenue_factors_df</span><span class="p">[</span><span class="n">c</span><span class="p">],</span> <span class="n">label</span><span class="o">=</span><span class="n">c</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_3.png" alt="Revenue over time by country" /></p>

<p align="center"><i> A plot of the change in revenue by country, $\Delta R_t^g.$ </i></p>

<p>As we might expect for a UK-based retailer, the UK is almost always the main driver of the revenue change. The revenue metric is is mostly measure what happens in the UK, since customers there supply an outsize amount (5x or 10x, depending on the month) of their revenue.</p>

<p>We might also plot a scaled version, $\Delta R_t^g / \Delta R_t$, normalizing by the total size of each month’s change.</p>

<h1 id="why-did-my-value-per-customer-change">Why did my value per customer change</h1>

<p>We commonly decompose revenue into</p>

\[\text{Revenue} = \underbrace{\frac{\text{Revenue}}{\text{Customer}}}_\textrm{Value of a customer}  \times \text{Total customers}\]

<p>We do this because the things that affect the first term might be different from those that affect the second. For example, further down-funnel changes to our product might affect the value of a customer, but not produce any new customers. As a result, the value per customer is a useful KPI on its own.</p>

<p>We’ll define the value of a customer in month $t$ as the total revenue over all regions divided by the customer count over all regions.</p>

<p>$V_t = \frac{\sum\limits_g r^g_t}{\sum\limits_g c^g_t}$</p>

<p>We can plot the value of the average customer over time:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">value_per_customer_series</span> <span class="o">=</span> <span class="n">monthly_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'date'</span><span class="p">).</span><span class="nb">sum</span><span class="p">()[</span><span class="s">'revenue'</span><span class="p">]</span> <span class="o">/</span> <span class="n">monthly_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'date'</span><span class="p">).</span><span class="nb">sum</span><span class="p">()[</span><span class="s">'n_customers'</span><span class="p">]</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Average Value per customer'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Value, $'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">value_per_customer_series</span><span class="p">.</span><span class="n">index</span><span class="p">,</span> <span class="n">value_per_customer_series</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_4.png" alt="Revenue over time by country" /></p>

<p align="center"><i> A plot of the customer value over time, $V_t$.</i></p>

<p>As with revenue, we often want to look at the change in customer value from one month to the next:</p>

<p>$\Delta V_t = V_t - V_{t-1}$</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">value_per_customer_series</span> <span class="o">=</span> <span class="n">monthly_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'date'</span><span class="p">).</span><span class="nb">sum</span><span class="p">()[</span><span class="s">'revenue'</span><span class="p">]</span> <span class="o">/</span> <span class="n">monthly_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'date'</span><span class="p">).</span><span class="nb">sum</span><span class="p">()[</span><span class="s">'n_customers'</span><span class="p">]</span>
<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Monthly Change in Average Value per customer'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Value, $'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">value_per_customer_series</span><span class="p">.</span><span class="n">index</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> <span class="n">np</span><span class="p">.</span><span class="n">diff</span><span class="p">(</span><span class="n">value_per_customer_series</span><span class="p">),</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">axhline</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dotted'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_5.png" alt="Revenue over time by country" /></p>

<p align="center"><i>A plot of the month-over-month change in customer value, $\Delta V_t$.</i></p>

<p>By grouping and calculating $V_t$, we could get the value of a customer in each region:</p>

<p>$V^g_t = \frac{r^g_t}{c^g_t}$</p>

<p>We want to look a little deeper into how country-level changes roll up into the overall change in value that we see.</p>

<h2 id="why-did-our-customer-value-change">Why did our customer value change?</h2>

<p>There are two ways to increase the value of our customers:</p>
<ul>
  <li>We can change the mix of our customers so that more of them come from more valuable countries. For example, we might market to customers in a particularly lucrative country.</li>
  <li>We can increase the value of the customers in a specific country. For example, we might try to understand what new features will appeal to customers in a particular country.</li>
</ul>

<p>Both of these are potential sources of change in any given month. How much of this month’s change in value was because the mix of customers changed? How much was due to within-country factors? A clever decomposition from <a href="https://www.casact.org/pubs/forum/00wforum/00wf305.pdf">this note by Daniel Corro</a> allows us to get a perspective on this.</p>

<p>The value growth decomposition given by Corro is:</p>

<p>$\Delta V_t = \alpha_t + \beta_t = \sum\limits_g (\alpha_t^g + \beta_t^g)$</p>

<p>Where we have defined the total number of customers at time $t$ across all countries:</p>

<p>$C_t = \sum\limits_g c_t^g$</p>

<p>In this decomposition there are two main components, $\alpha_t$ and $\beta_t$. $\alpha_t$ is the mix component, which tells us how much of the change was due to the mix of customers changing across countries. $\beta_t$ is the matched difference component, which tells us how much of the change was due to within-country factors.</p>

<p>The mix component is:</p>

<p>$\alpha_t = \sum\limits_g \alpha_t^g = \sum\limits_g V_{t-1}^g (\frac{c_t^g}{C_t} - \frac{c_{t-1}^g}{C_{t-1}})$</p>

<p>The idea here is that $\alpha_t$ is the change that we get when we apply the new mix without changing the value per country.</p>

<p>The matched difference component is:</p>

<p>$\beta_t = \sum\limits_g \beta_t^g = \sum\limits_g (V_t^g - V_{t-1}^g) (\frac{c_t^g}{C_t})$</p>

<p>$\beta_t$ is the change we would get if we updated the country-level values to what we see at time $t$, but keep the mix the same.</p>

<p>If we’re less interested in the mix vs matched difference distinction, and more interested in a country-level perspective, we can collapse the two to show contribution by country:</p>

<p>$\Delta V_t = \sum\limits_g \Delta V_t^g$</p>

<p>Where we’re defined the country-level contribution:</p>

<p>$\Delta V_t^g = \alpha^g_t + \beta^g_t = V_t^g \frac{c_t^g}{C_t} - V_{t-1}^g \frac{c_{t-1}^g}{C_{t-1}}$</p>

<p>Okay, let’s see that in code. We can write a python function to perform the decomposition for us, and give us back a dataframe that indicates each contributor to the change over time:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">decompose_value_per_customer</span><span class="p">(</span><span class="n">df</span><span class="p">):</span>
  <span class="n">dates</span><span class="p">,</span> <span class="n">date_dfs</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="p">[(</span><span class="n">t</span><span class="p">,</span> <span class="n">t_df</span><span class="p">.</span><span class="n">sort_values</span><span class="p">(</span><span class="s">'country_coarse'</span><span class="p">).</span><span class="n">reset_index</span><span class="p">())</span> <span class="k">for</span> <span class="n">t</span><span class="p">,</span> <span class="n">t_df</span> <span class="ow">in</span> <span class="n">df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'date'</span><span class="p">,</span> <span class="n">sort</span><span class="o">=</span><span class="bp">True</span><span class="p">)])</span>
  <span class="n">first</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
  <span class="n">groups</span> <span class="o">=</span> <span class="n">first</span><span class="p">[</span><span class="s">'country_coarse'</span><span class="p">]</span>
  <span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="s">'value'</span><span class="p">,</span> <span class="s">'a'</span><span class="p">,</span> <span class="s">'b'</span><span class="p">]</span> <span class="o">+</span> <span class="p">[</span><span class="s">'{0}_a'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">g</span><span class="p">)</span> <span class="k">for</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">groups</span><span class="p">]</span> <span class="o">+</span> <span class="p">[</span><span class="s">'{0}_b'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">g</span><span class="p">)</span> <span class="k">for</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">groups</span><span class="p">]</span>
  <span class="n">result_rows</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">empty</span><span class="p">((</span><span class="nb">len</span><span class="p">(</span><span class="n">dates</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">columns</span><span class="p">)))</span>
  <span class="n">cust_t</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([</span><span class="n">dt_df</span><span class="p">[</span><span class="s">'n_customers'</span><span class="p">].</span><span class="nb">sum</span><span class="p">()</span> <span class="k">for</span> <span class="n">dt_df</span> <span class="ow">in</span> <span class="n">date_dfs</span><span class="p">])</span>
  <span class="n">rev_t</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([</span><span class="n">dt_df</span><span class="p">[</span><span class="s">'revenue'</span><span class="p">].</span><span class="nb">sum</span><span class="p">()</span> <span class="k">for</span> <span class="n">dt_df</span> <span class="ow">in</span> <span class="n">date_dfs</span><span class="p">])</span>
  <span class="n">value_t</span> <span class="o">=</span> <span class="n">rev_t</span> <span class="o">/</span> <span class="n">cust_t</span>
  <span class="n">result_rows</span><span class="p">[:,</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">value_t</span>
  <span class="n">result_rows</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">:]</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
  <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">result_rows</span><span class="p">)):</span>
    <span class="n">cust_t_g</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="s">'n_customers'</span><span class="p">]</span>
    <span class="n">rev_t_g</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="s">'revenue'</span><span class="p">]</span>
    <span class="n">value_t_g</span>  <span class="o">=</span> <span class="n">rev_t_g</span> <span class="o">/</span> <span class="n">cust_t_g</span>
    <span class="n">cust_t_previous_g</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="n">t</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="s">'n_customers'</span><span class="p">]</span>
    <span class="n">rev_t_previous_g</span> <span class="o">=</span> <span class="n">date_dfs</span><span class="p">[</span><span class="n">t</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="s">'revenue'</span><span class="p">]</span>
    <span class="n">value_t_previous_g</span>  <span class="o">=</span> <span class="n">rev_t_previous_g</span> <span class="o">/</span> <span class="n">cust_t_previous_g</span>
    <span class="n">a_t_g</span> <span class="o">=</span> <span class="n">value_t_previous_g</span> <span class="o">*</span> <span class="p">((</span><span class="n">cust_t_g</span> <span class="o">/</span> <span class="n">cust_t</span><span class="p">[</span><span class="n">t</span><span class="p">])</span> <span class="o">-</span> <span class="p">(</span><span class="n">cust_t_previous_g</span> <span class="o">/</span> <span class="n">cust_t</span><span class="p">[</span><span class="n">t</span><span class="o">-</span><span class="mi">1</span><span class="p">]))</span>
    <span class="n">b_t_g</span> <span class="o">=</span> <span class="p">(</span><span class="n">value_t_g</span> <span class="o">-</span> <span class="n">value_t_previous_g</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">cust_t_g</span> <span class="o">/</span> <span class="n">cust_t</span><span class="p">[</span><span class="n">t</span><span class="p">])</span>
    <span class="n">result_rows</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="mi">3</span><span class="p">:</span><span class="mi">3</span><span class="o">+</span><span class="nb">len</span><span class="p">(</span><span class="n">groups</span><span class="p">)]</span> <span class="o">=</span> <span class="n">a_t_g</span>
    <span class="n">result_rows</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="mi">3</span><span class="o">+</span><span class="nb">len</span><span class="p">(</span><span class="n">groups</span><span class="p">):]</span> <span class="o">=</span> <span class="n">b_t_g</span>
    <span class="n">result_rows</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nb">sum</span><span class="p">(</span><span class="n">a_t_g</span><span class="p">)</span>
    <span class="n">result_rows</span><span class="p">[</span><span class="n">t</span><span class="p">][</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nb">sum</span><span class="p">(</span><span class="n">b_t_g</span><span class="p">)</span>
  <span class="n">result_df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">result_rows</span><span class="p">,</span> <span class="n">columns</span><span class="o">=</span><span class="n">columns</span><span class="p">)</span>
  <span class="n">result_df</span><span class="p">[</span><span class="s">'dates'</span><span class="p">]</span> <span class="o">=</span> <span class="n">dates</span>
  <span class="k">return</span> <span class="n">result_df</span>
</code></pre></div></div>

<p>Then we can use it to plot the contributions of the mix component vs the matched difference component to the monthly change:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">customer_value_breakdown_df</span> <span class="o">=</span> <span class="n">decompose_value_per_customer</span><span class="p">(</span><span class="n">monthly_df</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Breaking down monthly changes'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Change in customer value, $'</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">.</span><span class="n">dates</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> 
         <span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="s">'a'</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Mix'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">.</span><span class="n">dates</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> 
         <span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="s">'b'</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Matched difference'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">axhline</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dotted'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span> 
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_6.png" alt="Revenue over time by country" /></p>

<p align="center"><i>A plot of the mix and matched-difference components of Corro's decomposition, $\alpha_t$ and $\beta_t$. </i></p>

<p>We see that the main driver of changing customer value is within-country factors, rather than changes in the customer mix.</p>

<p>Since this fluctuates a lot, it can be helpful to plot the scaled versions of each, $\frac{\alpha_t}{\alpha_t + \beta_t}$ and $\frac{\beta_t}{\alpha_t + \beta_t}$</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Breaking down monthly changes, scaled'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Scaled Change in customer value, $'</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">.</span><span class="n">dates</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> 
         <span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="s">'a'</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span> <span class="o">/</span> <span class="n">np</span><span class="p">.</span><span class="n">diff</span><span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="s">'value'</span><span class="p">]),</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Mix'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">.</span><span class="n">dates</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> 
         <span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="s">'b'</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span> <span class="o">/</span> <span class="n">np</span><span class="p">.</span><span class="n">diff</span><span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="s">'value'</span><span class="p">]),</span> <span class="n">marker</span><span class="o">=</span><span class="s">'o'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s">'Matched difference'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">axhline</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">linestyle</span><span class="o">=</span><span class="s">'dotted'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_7.png" alt="Revenue over time by country" /></p>

<p align="center"><i>A plot of the scaled mix and matched difference components of change, $\frac{\alpha_t}{\alpha_t + \beta_t}$ and $\frac{\beta_t}{\alpha_t + \beta_t}$. </i></p>

<p>We see that August is the only month in which the mix was the more important component. In that month, it looks like the value of each country didn’t change, but our mix across countries did.</p>

<p>Lastly, we can plot the country level contribution, scaled in a similar way:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plt</span><span class="p">.</span><span class="n">title</span><span class="p">(</span><span class="s">'Breaking down monthly changes by country, scaled'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s">'Month'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s">'Scaled Change in customer value, $'</span><span class="p">)</span>

<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">ALL_COUNTRIES</span><span class="p">:</span>
  <span class="n">plt</span><span class="p">.</span><span class="n">plot</span><span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="s">'dates'</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> 
           <span class="p">(</span><span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="n">c</span><span class="o">+</span><span class="s">'_a'</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span> <span class="o">+</span> <span class="n">customer_value_breakdown_df</span><span class="p">[</span><span class="n">c</span><span class="o">+</span><span class="s">'_b'</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:]),</span> 
           <span class="n">label</span><span class="o">=</span><span class="n">c</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>

<span class="c1"># Australia contributed disproportionately positively in August, because Australians became more valuable customers in August
# Correlations between country contributions?
</span></code></pre></div></div>

<p><img src="https://raw.githubusercontent.com/lmc2179/lmc2179.github.io/master/assets/img/metric_decomposition/Figure_8.png" alt="Revenue over time by country" /></p>

<p align="center"><i>A plot of each country's contribution to the change in customer value each month, $\Delta V_t^g$. </i></p>

<p>As with change in revenue, the UK is the biggest contributor to the change in customer value.</p>

<h1 id="quantifying-uncertainty">Quantifying uncertainty</h1>

<p>At this point, we’ve got some exact decompositions which we can use to understand which subgroups contributed the most to the change in our favorite metric. However, we might ask whether the change we saw was statistically significant - or perhaps more usefully, we might try to quantify the uncertainty around the $\alpha_t$ or $\beta_t$ that we estimated.</p>

<p>Corro suggests (p 6) paired weighted T-tests for based on the observed value of each group. These test the hypotheses $\alpha_t = 0$ and  $\beta_t = 0$. These probably wouldn’t be hard to implement using <a href="https://www.statsmodels.org/stable/generated/statsmodels.stats.weightstats.ttost_paired.html#statsmodels.stats.weightstats.ttost_paired">weightstats.ttost_paired in statsmodels</a>.</p>

<h1 id="appendix-notation-reference">Appendix: Notation reference</h1>

<table>
  <thead>
    <tr>
      <th>Symbol</th>
      <th>Definition</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>$g$</td>
      <td>Subgroup index</td>
    </tr>
    <tr>
      <td>$t$</td>
      <td>Discrete time step index</td>
    </tr>
    <tr>
      <td>$r_t^g$</td>
      <td>Revenue at time $t$ for group $g$</td>
    </tr>
    <tr>
      <td>$R_t$</td>
      <td>Total revenue at time $t$ summed over all groups</td>
    </tr>
    <tr>
      <td>$\Delta R_t$</td>
      <td>Month-to-month change in revenue, $R_t - R_{t-1}$</td>
    </tr>
    <tr>
      <td>$c_t^g$</td>
      <td>Number of customers at time $t$ in group $g$</td>
    </tr>
    <tr>
      <td>$C_t$</td>
      <td>Number of customers at time $t$ summed over all groups</td>
    </tr>
    <tr>
      <td>$V_t$</td>
      <td>Customer value; revenue per customer at time $t$</td>
    </tr>
    <tr>
      <td>$\Delta V_t$</td>
      <td>Month-to-month change in value at time $t$, $V_t - V_{t-1}$</td>
    </tr>
    <tr>
      <td>$\alpha_t^g$</td>
      <td>Mix component of $\Delta V_t$ for group $g$</td>
    </tr>
    <tr>
      <td>$\beta_t^g$</td>
      <td>Matched difference component of $\Delta V_t$ for group $g$</td>
    </tr>
    <tr>
      <td>$\alpha_t$</td>
      <td>Mix component of $\Delta V_t$ summed over all groups</td>
    </tr>
    <tr>
      <td>$\beta_t$</td>
      <td>Matched difference component of $\Delta V_t$ summed over all groups</td>
    </tr>
    <tr>
      <td>$\Delta V_t^g$</td>
      <td>Contribution of group $g$ to $\Delta V_t$</td>
    </tr>
  </tbody>
</table>

<h1 id="appendix-import-statements-and-data-cleaning">Appendix: Import statements and data cleaning</h1>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl https://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx --output online_retail.xlsx
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns

retail_df = pd.read_excel('online_retail.xlsx')

begin = pd.to_datetime('2011-01-01 00:00:00', yearfirst=True)
end = pd.to_datetime('2011-12-01 00:00:00', yearfirst=True)

retail_df = retail_df[(retail_df['InvoiceDate'] &gt; begin) &amp; (retail_df['InvoiceDate'] &lt; end)]

COUNTRIES = {'United Kingdom', 'France', 'Australia', 'Germany'}

retail_df['country_coarse'] = retail_df['Country'].apply(lambda x: x if x in COUNTRIES else 'All others')
retail_df['date'] = retail_df['InvoiceDate'].apply(lambda x: x.month)
retail_df['revenue'] = retail_df['Quantity'] * retail_df['UnitPrice']
# Add number of customers in this country

monthly_gb = retail_df[['date', 'country_coarse', 'revenue', 'CustomerID']].groupby(['date', 'country_coarse'])
monthly_df  = pd.DataFrame(monthly_gb['revenue'].sum())
monthly_df['n_customers'] = monthly_gb['CustomerID'].nunique()
monthly_df = monthly_df.reset_index()
</code></pre></div></div>]]></content><author><name>Louis Cialdella</name></author><category term="posts" /><category term="datascience" /><summary type="html"><![CDATA[As analytics professionals, we frequently summarize the state of the business with metrics that measure some aspect of its performance. We check these metrics every day, week, or month, and try to understand what changed them. Often we inspect a few familiar subgroups (maybe your customer regions, or demographics) to understand how much each group contributed to the change. This pattern is so common and so useful that it’s worth noting some general-purpose decompositions that we can use when we come across this problem. This initial perspective can give us the intuition to plan a deeper statistical or causal analysis.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://lmc2179.github.io/revenue_sources.png" /><media:content medium="image" url="https://lmc2179.github.io/revenue_sources.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>