<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Random Realizations</title>
<link>https://randomrealizations.com/writing.html</link>
<atom:link href="https://randomrealizations.com/writing.xml" rel="self" type="application/rss+xml"/>
<description>A blog about data science, statistics, machine learning, and the scientific method</description>
<image>
<url>https://randomrealizations.com/opengraph.png</url>
<title>Random Realizations</title>
<link>https://randomrealizations.com/writing.html</link>
<height>76</height>
<width>144</width>
</image>
<generator>quarto-1.10.19</generator>
<lastBuildDate>Wed, 11 Nov 2026 08:00:00 GMT</lastBuildDate>
<item>
  <title>Causality and the Prediction-Decision Gap</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/</link>
  <description><![CDATA[ 





<section id="the-purpose-of-data-science" class="level2">
<h2 class="anchored" data-anchor-id="the-purpose-of-data-science">The Purpose of Data Science</h2>
<p>Every once in a while my mom asks me if I can re-explain to her what data scientists do. It’s a great question really—we in the field should ask ourselves more often. In a single sentence I’d say: the purpose of data science is to create value from data. And what’s valuable to the organizations we serve? Well an organization has goals, and in order to achieve those goals it needs to make decisions about which actions to take. At its most effective, data science is about decision intelligence—informing a decision making process to help achieve desired outcomes. These decisions come in many forms, from executive deliberation on strategic bets to streaming automations occuring millions of times per day.</p>
<p>Examples include: * What price to charge for this ride share trip? * Which product to recommend to this user? * What treatment to give this pneumonia patient?</p>
<p>Behind each of these decisions is a set of “what if” questions of the form: What would happen if I did this? What would happen if I did that? To inform the decision we could predict answers to these what if questions.</p>
<p>For data scientists of my generation who spent the early part of their careers getting good at machine learning, this probably sounds an awful lot like a supervised learning problem. We could follow the typical ML playbook and train a model that minimizes out of sample prediction error. That means it would be the best predictor of outcomes from actions and an ideal “what if” function to use in our decisions, right?</p>
<p>Well, maybe; maybe not.</p>
<p>There is a key difference between a predictive model and the kind of “what if” function we want for decision making that I call the <em>prediction-decision gap</em>.</p>
<p><strong>Predictive models tell us the expected outcome given what we observe, while decisions require knowing the expected outcome given that we take a certain action</strong>.</p>
<p>Using well-fitting statistical models or accuracy-maxing ML models for decision making can fail, not just slightly, but catastrophically. Many of these failure modes arise from errors in reasoning about what causes what and how. In this post we’ll look at two types of prediction-decision failure modes that can occur because of mishandling causality. The first is about the consequences of misreading the causal mechanisms behind the correlations we exploit for prediction, and the second is about how a model can undermine itself by changing the process that generated its own training data. The key idea is that using statistical or ML models for decision making requires careful causal reasoning, and lucky for you, this is the first post in a forthcoming series on Causal Inference.</p>
<p>So let’s kick this series off by seeing some of the scary things that can happen when we naively use predictive models for decision making.</p>
</section>
<section id="prediction-decision-failure-modes" class="level2">
<h2 class="anchored" data-anchor-id="prediction-decision-failure-modes">Prediction-Decision Failure Modes</h2>
<section id="correlation-does-not-imply-causation-except-when-it-does" class="level3">
<h3 class="anchored" data-anchor-id="correlation-does-not-imply-causation-except-when-it-does">Correlation does not imply causation — except when it does</h3>
<p>We’ve all had it drilled into our heads — <em><a href="https://en.wikipedia.org/wiki/Correlation_does_not_imply_causation">correlation does not imply causation</a></em> — meaning it isn’t possible to deduce a cause-and-effect relationship between two events solely on the basis of an observed correlation or other statistical association between them. This does not mean there isn’t a cause effect relationship between the correlated variables; it just means we can’t tell what kind of relationship it is. To put a finer point on this, consider <a href="https://plato.stanford.edu/entries/physics-Rpcc/">Reichenbach’s Common Cause Principle</a>, which states that if two events are correlated, there must either be a causal relationship between them or a third event that causes both. That means that a true correlation between two variables tells us that one causes the other, the other causes the one, or another variable causes both. Note that Tyler-Vigen-style “<a href="https://tylervigen.com/spurious-correlations">spurious correlations</a>” (found by chance when dredging for high sample correlations between small samples of unrelated variables) don’t count as “true” correlations here, since they arise from sampling noise or shared time trends.</p>
<p>So in a sense, correlation <em>does</em> imply causation, but alone it cannot tell us <em>which</em> causal relationship exists between the variables. Let that sink in, this means that no matter how much observed data we collect, without bringing in additional assumptions, it’s not possible from the data alone to determine which variables are causes and which are effects. Furthermore, since predictive models simply leverage correlations and associations among variables from a sample of training data, a predictive model cannot tell us what causes what. This isn’t a problem for prediction, but in decision making, what causes what is absolutely critical. Operating with the wrong causal mechanism in mind can lead us to make misguided, suboptimal, or even terrible decisions.</p>
</section>
<section id="failure-mode-1-misreading-the-mechanism" class="level3">
<h3 class="anchored" data-anchor-id="failure-mode-1-misreading-the-mechanism">Failure Mode 1: misreading the mechanism</h3>
<p>Suppose we’re looking at some app usage data, and we want to figure out whether notifications can help to increase user engagement.</p>
<ul>
<li><strong>notifications</strong>: user enables push notifications during their first two weeks.</li>
<li><strong>sessions</strong>: engagement, measured by the number of sessions in the first two weeks.</li>
</ul>
<p>The data shows a strong positive correlation between notifications and sessions. We build a predictive model that predicts higher engagement when users have notifications enabled. Our goal is to increase engagement, and we need to make a decision about how to do that — specifically, <em>should we prompt every new user on day 1 to turn notifications on</em>? Well the model predicts that more users with notifications enabled gives more engagement, so naively using the predictive model as our “what if” function, we’d decide to go ahead and prompt every user to enable on day 1. There are many different causal mechanisms that could produce the observed correlation between notifications and sessions; let’s look at a few of them and what it would mean for our prediction-based decision to prompt users on day 1.</p>
<section id="notifications-cause-sessions" class="level4">
<h4 class="anchored" data-anchor-id="notifications-cause-sessions">1. Notifications cause sessions</h4>
<p>Suppose notifications remind people to come back, so each enabled user opens the app more often.</p>
<div id="cell-4" class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> graphviz</span>
<span id="cb1-2"></span>
<span id="cb1-3">dot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> graphviz.Digraph()</span>
<span id="cb1-4">dot.attr(rankdir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"LR"</span>)</span>
<span id="cb1-5">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"node"</span>, shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"box"</span>, style<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rounded,filled"</span>, fillcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f8f9fa"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ced4da"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>)</span>
<span id="cb1-6">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"edge"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#495057"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"9"</span>)</span>
<span id="cb1-7"></span>
<span id="cb1-8">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Notifications"</span>)</span>
<span id="cb1-9">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sessions"</span>)</span>
<span id="cb1-10"></span>
<span id="cb1-11">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>)</span>
<span id="cb1-12"></span>
<span id="cb1-13">dot</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="49">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/part_1_files/figure-html/cell-2-output-1.svg" class="img-fluid figure-img" alt="A causal DAG where Notifications causes Sessions."></p>
<figcaption>A causal diagram showing that notifications causes sessions. If you’re unfamiliar with causal diagrams, just read arrows as pointing from cause to effect</figcaption>
</figure>
</div>
</div>
</div>
<p>If we prompt users on day 1, sessions go up — we made the right decision!</p>
</section>
<section id="reverse-causation-sessions-cause-notifications" class="level4">
<h4 class="anchored" data-anchor-id="reverse-causation-sessions-cause-notifications">2. Reverse causation: sessions cause notifications</h4>
<p>Suppose the default OS notification permission prompt automatically fires after a user’s 5th session. Engaged users with many sessions see the prompt and many of them accept, while users who only open the app a few times never see it and thus few of them enable notifications. Suppose further the notifications themselves have no effect on sessions.</p>
<div id="cell-6" class="cell" data-execution_count="50">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> graphviz</span>
<span id="cb2-2"></span>
<span id="cb2-3">dot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> graphviz.Digraph()</span>
<span id="cb2-4">dot.attr(rankdir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"LR"</span>)</span>
<span id="cb2-5">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"node"</span>, shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"box"</span>, style<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rounded,filled"</span>, fillcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f8f9fa"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ced4da"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>)</span>
<span id="cb2-6">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"edge"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#495057"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"9"</span>)</span>
<span id="cb2-7"></span>
<span id="cb2-8">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sessions"</span>)</span>
<span id="cb2-9">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prompt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Prompt"</span>)</span>
<span id="cb2-10">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Notifications on"</span>)</span>
<span id="cb2-11"></span>
<span id="cb2-12">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prompt"</span>)</span>
<span id="cb2-13">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prompt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>)</span>
<span id="cb2-14"></span>
<span id="cb2-15">dot</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="50">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/part_1_files/figure-html/cell-3-output-1.svg" class="img-fluid figure-img" alt="A causal DAG where Sessions causes Seeing the Prompt, which causes Notifications to be enabled."></p>
</figure>
</div>
</div>
</div>
<p>Under this mechanism, sessions cause the prompt to fire, which causes notifications. If we prompt users to enable notifications on day 1, sessions won’t actually increase.</p>
</section>
<section id="common-cause-invites-cause-notifications-and-sessions" class="level4">
<h4 class="anchored" data-anchor-id="common-cause-invites-cause-notifications-and-sessions">3. Common cause: invites cause notifications and sessions</h4>
<p>Suppose many users discover the app through an invite link sent by a friend. They enable notifications to get updated on what their friends are doing, and they also use the app more than non-invite users because of that social pull. Again, notifications don’t actually increase engagement.</p>
<div id="cell-8" class="cell" data-execution_count="51">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> graphviz</span>
<span id="cb3-2"></span>
<span id="cb3-3">dot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> graphviz.Digraph()</span>
<span id="cb3-4">dot.attr(rankdir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TB"</span>)</span>
<span id="cb3-5">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"node"</span>, shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"box"</span>, style<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rounded,filled"</span>, fillcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f8f9fa"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ced4da"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>)</span>
<span id="cb3-6">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"edge"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#495057"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"9"</span>)</span>
<span id="cb3-7"></span>
<span id="cb3-8">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"invite"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Invite"</span>)</span>
<span id="cb3-9">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Notifications"</span>)</span>
<span id="cb3-10">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sessions"</span>)</span>
<span id="cb3-11"></span>
<span id="cb3-12">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"invite"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>)</span>
<span id="cb3-13">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"invite"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>)</span>
<span id="cb3-14"></span>
<span id="cb3-15">dot</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="51">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/part_1_files/figure-html/cell-4-output-1.svg" class="img-fluid figure-img" alt="A causal DAG where Invite is a common cause of both Notifications and Sessions."></p>
</figure>
</div>
</div>
</div>
<p>If we prompt users to enable notifications on day 1, more non-invited users enable notifications, but this doesn’t actually affect engagement.</p>
</section>
<section id="common-cause-with-annoying-notifications" class="level4">
<h4 class="anchored" data-anchor-id="common-cause-with-annoying-notifications">4. Common cause with annoying notifications</h4>
<p>Suppose we have the same common cause mechanism as before but now the notifications are actually slightly annoying to users, causing a small reduction in engagement.</p>
<div id="cell-10" class="cell" data-execution_count="52">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> graphviz</span>
<span id="cb4-2"></span>
<span id="cb4-3">dot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> graphviz.Digraph()</span>
<span id="cb4-4">dot.attr(rankdir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TB"</span>, nodesep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.8"</span>, ranksep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.6"</span>)</span>
<span id="cb4-5">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"node"</span>, shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"box"</span>, style<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rounded,filled"</span>, fillcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f8f9fa"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ced4da"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>)</span>
<span id="cb4-6">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"edge"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#495057"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"9"</span>)</span>
<span id="cb4-7"></span>
<span id="cb4-8">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"invite"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Invite"</span>)</span>
<span id="cb4-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> dot.subgraph() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> s:</span>
<span id="cb4-10">    s.attr(rank<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"same"</span>)</span>
<span id="cb4-11">    s.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Notifications"</span>)</span>
<span id="cb4-12">    s.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sessions"</span>)</span>
<span id="cb4-13"></span>
<span id="cb4-14">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"invite"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>)</span>
<span id="cb4-15">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"invite"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>)</span>
<span id="cb4-16">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"notifications"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sessions"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" reduces sessions"</span>)</span>
<span id="cb4-17"></span>
<span id="cb4-18">dot</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="52">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/part_1_files/figure-html/cell-5-output-1.svg" class="img-fluid figure-img" alt="A causal DAG where Invite is a common cause of Notifications and Sessions, and Notifications reduces Sessions."></p>
</figure>
</div>
</div>
</div>
<p>Note that because the tendency of invite to increase both notifications and engagement is stronger than the tendency of notifications to reduce sessions, we’ll still see that positive correlation between notifications and sessions in the data and predictive model. If we prompt users to enable notifications on day 1, we actually end up decreasing engagement.</p>
<hr>
<p>To recap, here’s the effect of prompting to enable notifications for each of the potential causal mechanisms:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">Causal Mechanism</th>
<th style="text-align: left;">Effect of Prompting Notifications</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">notifications → sessions</td>
<td style="text-align: left;">sessions go up</td>
</tr>
<tr class="even">
<td style="text-align: left;">reverse causation: sessions → notifications</td>
<td style="text-align: left;">no impact on sessions</td>
</tr>
<tr class="odd">
<td style="text-align: left;">common cause: notifications ← invite → sessions</td>
<td style="text-align: left;">no impact on sessions</td>
</tr>
<tr class="even">
<td style="text-align: left;">common cause with annoying notifications</td>
<td style="text-align: left;">sessions go down</td>
</tr>
</tbody>
</table>
<p>Under all four of the causal mechanisms for our notifications example, the data and predictive model would show a positive correlation between notifications and sessions, but choosing to prompt users to enable notifications on day 1 would only help under the first one. Under the second and third we’d produce no effect and under the fourth we’d actually achieve the exact opposite of what we intended.</p>
<p>Failure mode 1 boils down to misreading the true causal mechanisms, thereby incorrectly measuring the true effect of the action on the outcome ; this produces a misleading “what if” function which then misguides our decision.</p>
</section>
</section>
<section id="failure-mode-2-model-deployment-changes-the-environment" class="level3">
<h3 class="anchored" data-anchor-id="failure-mode-2-model-deployment-changes-the-environment">Failure Mode 2: model deployment changes the environment</h3>
<p>To make matters worse, even if we know the true direction of the causal effect of the action on the outcome, predictive models can still lead us astray when we deploy them to guide policy decisions. Admitedly it seems natural to use a predictive model as the “what if” function behind such a policy, e.g.&nbsp; irrigate crops when the model predicts low soil moisture, salt roads when the model predicts slippery conditions, admit the patient to intensive care when the model predicts high risk. But when we do this, model deployment can actually change the environment in ways that invalidate the statistical associations the model learned in training.</p>
<section id="triaging-pneumonia-patients" class="level4">
<h4 class="anchored" data-anchor-id="triaging-pneumonia-patients">Triaging pneumonia patients</h4>
<p>In the mid 1990s, Cost-Effective HealthCare funded a study that sought to use machine learning models to predict pneumonia risk using patient attributes like age, blood pressure, and whether they had asthma (<a href="https://www.sciencedirect.com/science/article/abs/pii/S0933365796003673">Cooper et al.&nbsp;1997</a>, <a href="https://dl.acm.org/doi/10.1145/2783258.2788613">Caruana et al.&nbsp;2015</a>). Here we’ll look at a stylized version of the story; check the paper for the real details. The goal was to reduce healthcare costs by using these predictions to triage patients, deciding whether they should be admitted to the intensive care unit (ICU) or treated in the general ward. While asthma is known to increase mortality in pneumonia patients, counterintuitively, these models learned that having asthma was predictive of increased patient survival probability. Why?</p>
<p>Consider the causal mechanisms:</p>
<div id="cell-13" class="cell" data-execution_count="53">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> graphviz</span>
<span id="cb5-2"></span>
<span id="cb5-3">dot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> graphviz.Digraph()</span>
<span id="cb5-4">dot.attr(rankdir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TB"</span>, nodesep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.0"</span>, ranksep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.8"</span>)</span>
<span id="cb5-5">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"node"</span>, shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"box"</span>, style<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rounded,filled"</span>, fillcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f8f9fa"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ced4da"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>)</span>
<span id="cb5-6">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"edge"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#495057"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"9"</span>)</span>
<span id="cb5-7"></span>
<span id="cb5-8">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"asthma"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Asthma"</span>)</span>
<span id="cb5-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> dot.subgraph() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> s:</span>
<span id="cb5-10">    s.attr(rank<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"same"</span>)</span>
<span id="cb5-11">    s.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"icu"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ICU"</span>)</span>
<span id="cb5-12">    s.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"survival"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Survival"</span>)</span>
<span id="cb5-13"></span>
<span id="cb5-14">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"asthma"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"icu"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" policy:</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> asthma increases ICU"</span>)</span>
<span id="cb5-15">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"asthma"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"survival"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" reduces survival"</span>)</span>
<span id="cb5-16">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"icu"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"survival"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" strongly</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> increases survival"</span>)</span>
<span id="cb5-17"></span>
<span id="cb5-18">dot</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="53">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/part_1_files/figure-html/cell-6-output-1.svg" class="img-fluid figure-img" alt="A causal DAG showing Asthma increasing ICU admission policy, Asthma reducing survival, and ICU strongly increasing survival."></p>
</figure>
</div>
</div>
</div>
<p>In the instances from the training data, providers had correctly identified the asthma patients as high-risk pneumonia cases and sent them to the ICU. Intensive care then greatly increased their survival probability. This induces a positive correlation between asthma and survival in the dataset. Since the dataset contained patient attributes but not details about their care, ICU remained unobserved, and the predictive models learned the positive association between asthma and survival.</p>
<p>Imagine what would happen if we actually deployed this model, replacing the previous policy of provider triage with a policy based on the model’s risk prediction.</p>
<div id="cell-15" class="cell" data-execution_count="61">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> graphviz</span>
<span id="cb6-2"></span>
<span id="cb6-3">dot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> graphviz.Digraph()</span>
<span id="cb6-4">dot.attr(rankdir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TB"</span>, nodesep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.0"</span>, ranksep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.8"</span>)</span>
<span id="cb6-5">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"node"</span>, shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"box"</span>, style<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rounded,filled"</span>, fillcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f8f9fa"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ced4da"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>)</span>
<span id="cb6-6">dot.attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"edge"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#495057"</span>, fontname<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sans-serif"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"9"</span>)</span>
<span id="cb6-7"></span>
<span id="cb6-8">dot.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"asthma"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Asthma"</span>)</span>
<span id="cb6-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> dot.subgraph() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> s:</span>
<span id="cb6-10">    s.attr(rank<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"same"</span>)</span>
<span id="cb6-11">    s.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"icu"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ICU"</span>)</span>
<span id="cb6-12">    s.node(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"survival"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Survival"</span>)</span>
<span id="cb6-13"></span>
<span id="cb6-14">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"asthma"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"icu"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" new policy:</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">asthma reduces predicted risk</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">which reduces ICU "</span>, fontcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#d9534f"</span>)</span>
<span id="cb6-15">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"asthma"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"survival"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" reduces survival"</span>, fontcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#d3d3d3"</span>)</span>
<span id="cb6-16">dot.edge(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"icu"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"survival"</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" strongly</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">increases survival"</span>, fontcolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#d3d3d3"</span>)</span>
<span id="cb6-17"></span>
<span id="cb6-18">dot</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display" data-execution_count="61">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/part_1_files/figure-html/cell-7-output-1.svg" class="img-fluid figure-img" alt="A causal DAG showing a new model policy where Asthma reduces predicted risk and ICU admission, Asthma reduces survival, and ICU strongly increases survival."></p>
</figure>
</div>
</div>
</div>
<p>The model would indicate asthma patients are low risk and should therefore not be sent to the ICU — a potentially catastrophic mistake.</p>
<hr>
<p>In this failure mode, we may actually know the correct causal mechanisms and treatment effect (ICU increases survival). Yet because the model is trained under a certain policy (asthma patients are sent to the ICU), the relationships it learns between the contextual variables (asthma) and the outcome (survival) are only valid under that policy. When we change this policy by using the model predictions to guide it instead, we can break the relationships the model relied on for prediction, and this can lead us to make misguided, suboptimal, or even catastrophic decisions.</p>
</section>
</section>
</section>
<section id="the-case-for-causality" class="level2">
<h2 class="anchored" data-anchor-id="the-case-for-causality">The case for causality</h2>
<p>We’ve seen that decision making is inherently causal — we take action so that the efffect serves the desired outcome. Determining the right action involves asking a “what if” question that looks a lot like a prediction problem, but predictive models are not necessarily causal; they are based on statistical associations and correlations among variables in their training data. We’ve seen two types of failure modes where use of predictive models for decision making can go wrong, both of them lead to models that incorrectly answer their “what if” questions because of causal errors. In the first mode, we misjudge what the action does by misreading the actual underlying causal mechanisms. In the second mode, we know the action helps, but the model learns the relationship between context and outcome with the old policy silently baked in; deploying the model changes the policy, which invalidates what the model learned in training.</p>
<p>Don’t succumb to these and other pitfalls. Become a savvy causal inference practitioner instead.</p>
<p>Join me through the rest of this series on causal modeling in data science. In the series we’ll cover: what exactly is causality, the potential outcomes tradition, the graphical models tradition, why there are two causality traditions, where causal modeling fits in the data science stack, and how to efficiently learn all this causality stuff. This series has been a long time in the making, mostly because causal inference is hard, and it’s taken me a long time to wrap my head around it enough to explain it cogently. So, dear reader, I’m very excited to finally bring this series to you. See you there!</p>
</section>
<section id="resources" class="level2">
<h2 class="anchored" data-anchor-id="resources">Resources</h2>
<p>Here are a couple of excellent references on the gap between prediction and causality. Check them out.</p>
<ul>
<li><a href="https://matheusfacure.github.io/python-causality-handbook/When-Prediction-Fails.html">Why Prediction Fails</a> from <a href="https://matheusfacure.github.io/python-causality-handbook/landing-page.html">Causal Inference for the Brave and True</a></li>
<li><a href="https://shap.readthedocs.io/en/latest/example_notebooks/overviews/Be%20careful%20when%20interpreting%20predictive%20models%20in%20search%20of%20causal%20insights.html">Be careful when interpreting predictive models in search of causal insights</a> from the <a href="https://shap.readthedocs.io/en/latest/index.html">SHAP documentation</a></li>
</ul>


</section>

 ]]></description>
  <category>causal inference</category>
  <guid>https://randomrealizations.com/posts/causality-and-the-prediction-decision-gap/</guid>
  <pubDate>Wed, 11 Nov 2026 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/enso-thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>The t-test is a Special Case of OLS (aka my attempt to write a quick post)</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/t-test-is-ols/</link>
  <description><![CDATA[ 





<p>Well for a while now I’ve been thinking it might be nice to be able to fire off a quick post now and then, instead of working on these huge months long sagas that I edit and re edit a bazilion times before posting to yall. So here’s my attempt to quickly write a cute little post. We’re just going to run through the math to convince ourselves that the two-sample t-test is mathematically identical to ordinary least squares regression on a single covariate, and therefore the t-test is a special case of OLS. I know there are a bunch of t-test variants, but we’ll focus on the garden variety two sample equal variance one from your intro stats class.</p>
<section id="two-sample-t-test" class="level2">
<h2 class="anchored" data-anchor-id="two-sample-t-test">Two-Sample t-test</h2>
<p>We’ll look at the t-test from two perspectives—the classical setup and a linear regression reformulation. In each case we’ll break the approach down into these items: data generating process, estimator, expectation and variance of the estimator, test statistic, and sampling distribution of the test statistic. You can use this kind of breakdown to understand pretty much any classical statistical test. In this case, the point is to clearly show that the classical t-test and the linear regression formulation yield identical tests.</p>
<section id="the-classical-t-test-approach" class="level3">
<h3 class="anchored" data-anchor-id="the-classical-t-test-approach">The Classical t-test Approach</h3>
<p><strong>The data generating process</strong></p>
<p>You have two populations or processes <img src="https://latex.codecogs.com/png.latex?Y_0"> and <img src="https://latex.codecogs.com/png.latex?Y_1">, and you want to know whether their true means <img src="https://latex.codecogs.com/png.latex?%5Cmu_0"> and <img src="https://latex.codecogs.com/png.latex?%5Cmu_1"> are equal. We assume that both processes are Gaussian with equal but unknown variance <img src="https://latex.codecogs.com/png.latex?%5Csigma%5E2">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%20Y_0%20%5Csim%20N(%5Cmu_0,%20%5Csigma%5E2),%20%5Cquad%20Y_1%20%5Csim%20N(%5Cmu_1,%20%5Csigma%5E2)%20"></p>
<p><strong>The estimator</strong></p>
<p>You draw <img src="https://latex.codecogs.com/png.latex?n_0"> samples from group 0 and <img src="https://latex.codecogs.com/png.latex?n_1"> samples from group 1 for a total of <img src="https://latex.codecogs.com/png.latex?n=n_0+n_1"> samples, and compute the sample means <img src="https://latex.codecogs.com/png.latex?%5Cbar%7BY%7D_0"> and <img src="https://latex.codecogs.com/png.latex?%5Cbar%7BY%7D_1">. Your estimator for the difference in means is simply:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cdelta%7D%20=%20%5Cbar%7BY%7D_1%20-%20%5Cbar%7BY%7D_0"></p>
<p><strong>Expectation of the estimator</strong></p>
<p>Since <img src="https://latex.codecogs.com/png.latex?E%5B%5Cbar%7BY%7D_0%5D%20=%20%5Cmu_0"> and <img src="https://latex.codecogs.com/png.latex?E%5B%5Cbar%7BY%7D_1%5D%20=%20%5Cmu_1">, we have:</p>
<p><img src="https://latex.codecogs.com/png.latex?E%5B%5Chat%7B%5Cdelta%7D%5D%20=%20E%5B%5Cbar%7BY%7D_1%20-%20%5Cbar%7BY%7D_0%5D%20=%20%5Cmu_1%20-%20%5Cmu_0"></p>
<p>So <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cdelta%7D"> is an unbiased estimator of the true difference in means.</p>
<p><strong>Standard error of the estimator</strong></p>
<p>The sample means are independent, so:</p>
<p><img src="https://latex.codecogs.com/png.latex?Var%5B%5Chat%7B%5Cdelta%7D%5D%20=%20Var%5B%5Cbar%7BY%7D_1%5D%20+%20Var%5B%5Cbar%7BY%7D_0%5D%20=%20%5Cfrac%7B%5Csigma%5E2%7D%7Bn_1%7D%20+%20%5Cfrac%7B%5Csigma%5E2%7D%7Bn_0%7D%20=%20%5Csigma%5E2%5Cleft(%5Cfrac%7B1%7D%7Bn_1%7D%20+%20%5Cfrac%7B1%7D%7Bn_0%7D%5Cright)"></p>
<p>Since we don’t know <img src="https://latex.codecogs.com/png.latex?%5Csigma%5E2">, we estimate it with the pooled sample variance:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2%20=%20%5Cfrac%7B(n_0-1)s_0%5E2%20+%20(n_1-1)s_1%5E2%7D%7Bn_0%20+%20n_1%20-%202%7D"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?s_0%5E2"> and <img src="https://latex.codecogs.com/png.latex?s_1%5E2"> are the sample variances for each group. This gives us the estimated standard error:</p>
<p><img src="https://latex.codecogs.com/png.latex?SE(%5Chat%7B%5Cdelta%7D)%20=%20%5Csqrt%7B%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2%5Cleft(%5Cfrac%7B1%7D%7Bn_0%7D%20+%20%5Cfrac%7B1%7D%7Bn_1%7D%5Cright)%7D"></p>
<p><strong>The test statistic</strong></p>
<p>We form the test statistic by dividing our estimator by its standard error:</p>
<p><img src="https://latex.codecogs.com/png.latex?t%20=%20%5Cfrac%7B%5Chat%7B%5Cdelta%7D%7D%7BSE(%5Chat%7B%5Cdelta%7D)%7D%20=%20%5Cfrac%7B%5Cbar%7BY%7D_1%20-%20%5Cbar%7BY%7D_0%7D%7B%5Csqrt%7B%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2%20(1/n_0%20+%201/n_1)%7D%7D"></p>
<p><strong>Sampling distribution</strong></p>
<p>Under the null hypothesis <img src="https://latex.codecogs.com/png.latex?H_0:%20%5Cmu_1%20=%20%5Cmu_0">, this test statistic follows a Student’s t-distribution with <img src="https://latex.codecogs.com/png.latex?n_0%20+%20n_1%20-%202"> degrees of freedom.</p>
<p>Having horrifying flashbacks to your intro to stats class yet? No worries. Let’s look at it from a new perspective.</p>
</section>
<section id="the-regression-approach" class="level3">
<h3 class="anchored" data-anchor-id="the-regression-approach">The Regression Approach</h3>
<p><strong>The data generating process</strong></p>
<p>We can express the exact same data generating process as a linear regression model. Stack all observations into a single length-<img src="https://latex.codecogs.com/png.latex?n"> vector <img src="https://latex.codecogs.com/png.latex?Y"> and create a dummy variable <img src="https://latex.codecogs.com/png.latex?X%20%5Cin%20%5C%7B0,1%5C%7D"> indexing which group each observation came from:</p>
<p><img src="https://latex.codecogs.com/png.latex?%20Y%20=%20%5Cbeta_0%20+%20%5Cbeta_1%20X%20+%20%5Cepsilon%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cepsilon%20%5Coverset%7Biid%7D%7B%5Csim%7D%20N(0,%20%5Csigma%5E2)">.</p>
<p>Taking conditional expectations:</p>
<p><img src="https://latex.codecogs.com/png.latex?%20E%5BY%7CX=0%5D%20=%20%5Cbeta_0%20=%20%5Cmu_0%20"> <img src="https://latex.codecogs.com/png.latex?%20E%5BY%7CX=1%5D%20=%20%5Cbeta_0%20+%20%5Cbeta_1%20=%20%5Cmu_1%20"></p>
<p>So we can see that <img src="https://latex.codecogs.com/png.latex?%5Cbeta_1%20=%20%5Cmu_1%20-%20%5Cmu_0">, meaning the regression coefficient <img src="https://latex.codecogs.com/png.latex?%5Cbeta_1"> directly represents the difference in population means.</p>
<p><strong>The estimator</strong></p>
<p>The ordinary least squares estimator for <img src="https://latex.codecogs.com/png.latex?%5Cbeta_1"> is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cbeta%7D_1%20=%20%5Cfrac%7B%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(X_i%20-%20%5Cbar%7BX%7D)(Y_i%20-%20%5Cbar%7BY%7D)%7D%7B%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(X_i%20-%20%5Cbar%7BX%7D)%5E2%7D"></p>
<p>For our dummy variable where <img src="https://latex.codecogs.com/png.latex?%5Cbar%7BX%7D%20=%20n_1/(n_0%20+%20n_1)">, after some algebra that you can crank through on your own this simplifies to:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cbeta%7D_1%20=%20%5Cbar%7BY%7D_1%20-%20%5Cbar%7BY%7D_0"></p>
<p>Well look at that—the regression coefficient estimate is exactly the difference in sample means!</p>
<p><strong>Expectation of the estimator</strong></p>
<p>By the properties of OLS under our model assumptions:</p>
<p><img src="https://latex.codecogs.com/png.latex?E%5B%5Chat%7B%5Cbeta%7D_1%5D%20=%20%5Cbeta_1%20=%20%5Cmu_1%20-%20%5Cmu_0"></p>
<p>So <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cbeta%7D_1"> is also an unbiased estimator of the difference in means.</p>
<p><strong>Standard error of the estimator</strong></p>
<p>The standard error formula for an OLS coefficient is:</p>
<p><img src="https://latex.codecogs.com/png.latex?SE(%5Chat%7B%5Cbeta%7D_1)%20=%20%5Csqrt%7B%5Chat%7B%5Csigma%7D%5E2%20%5Ccdot%20%5Cfrac%7B1%7D%7B%5Csum_%7Bi=1%7D%5E%7Bn%7D(X_i%20-%20%5Cbar%7BX%7D)%5E2%7D%7D"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Csigma%7D%5E2"> is the residual variance from the regression:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Csigma%7D%5E2%20=%20%5Cfrac%7B1%7D%7Bn_0%20+%20n_1%20-%202%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D(Y_i%20-%20%5Chat%7BY%7D_i)%5E2"></p>
<p>For our dummy variable, it turns out that: - The residual variance <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Csigma%7D%5E2"> equals the pooled variance <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2"> - The sum <img src="https://latex.codecogs.com/png.latex?%5Csum_%7Bi=1%7D%5E%7Bn%7D(X_i%20-%20%5Cbar%7BX%7D)%5E2%20=%20%5Cfrac%7Bn_0%20n_1%7D%7Bn_0%20+%20n_1%7D"></p>
<p>Substituting these:</p>
<p><img src="https://latex.codecogs.com/png.latex?SE(%5Chat%7B%5Cbeta%7D_1)%20=%20%5Csqrt%7B%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2%20%5Ccdot%20%5Cfrac%7Bn_0%20+%20n_1%7D%7Bn_0%20n_1%7D%7D%20=%20%5Csqrt%7B%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2%5Cleft(%5Cfrac%7B1%7D%7Bn_0%7D%20+%20%5Cfrac%7B1%7D%7Bn_1%7D%5Cright)%7D"></p>
<p>This is exactly the same standard error we got from the classical approach.</p>
<p><strong>The test statistic</strong></p>
<p>We form the test statistic by dividing our coefficient estimate by its standard error:</p>
<p><img src="https://latex.codecogs.com/png.latex?t%20=%20%5Cfrac%7B%5Chat%7B%5Cbeta%7D_1%7D%7BSE(%5Chat%7B%5Cbeta%7D_1)%7D%20=%20%5Cfrac%7B%5Cbar%7BY%7D_1%20-%20%5Cbar%7BY%7D_0%7D%7B%5Csqrt%7B%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2%20(1/n_0%20+%201/n_1)%7D%7D"></p>
<p><strong>Sampling distribution</strong></p>
<p>Under the null hypothesis <img src="https://latex.codecogs.com/png.latex?H_0:%20%5Cbeta_1%20=%200">, this test statistic follows a Student’s t-distribution with <img src="https://latex.codecogs.com/png.latex?n_0%20+%20n_1%20-%202"> degrees of freedom (the residual degrees of freedom from the regression).</p>
</section>
<section id="the-punchline" class="level3">
<h3 class="anchored" data-anchor-id="the-punchline">The Punchline</h3>
<p>See what just happened? The two approaches give us:</p>
<ul>
<li>The same point estimate: <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cdelta%7D%20=%20%5Chat%7B%5Cbeta%7D_1%20=%20%5Cbar%7BY%7D_1%20-%20%5Cbar%7BY%7D_0"></li>
<li>The same standard error: <img src="https://latex.codecogs.com/png.latex?%5Csqrt%7B%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2(1/n_0%20+%201/n_1)%7D"></li>
<li>The same test statistic: <img src="https://latex.codecogs.com/png.latex?t%20=%20%5Cfrac%7B%5Cbar%7BY%7D_1%20-%20%5Cbar%7BY%7D_0%7D%7B%5Csqrt%7B%5Chat%7B%5Csigma%7D_%7B%5Ctext%7Bpooled%7D%7D%5E2%20(1/n_0%20+%201/n_1)%7D%7D"></li>
<li>The same sampling distribution: <img src="https://latex.codecogs.com/png.latex?t_%7Bn_0+n_1-2%7D"></li>
<li>Therefore, the same p-value</li>
</ul>
<p>In other words these approaches are mathematically equivalent.</p>
</section>
<section id="implementation" class="level3">
<h3 class="anchored" data-anchor-id="implementation">Implementation</h3>
<p>Let’s simulate some data and implement both testing approaches.</p>
<div id="4230263f" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> stats</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> statsmodels.api <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sm</span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Simulate data</span></span>
<span id="cb1-6">np.random.seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb1-7">n0, n1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span></span>
<span id="cb1-8">mu0, mu1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span></span>
<span id="cb1-9">sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb1-10">group0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.normal(mu0, sigma, n0)</span>
<span id="cb1-11">group1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.normal(mu1, sigma, n1)</span>
<span id="cb1-12"></span>
<span id="cb1-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Traditional t-test</span></span>
<span id="cb1-14">t_stat, p_val_ttest <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stats.ttest_ind(group1, group0, equal_var<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-15"></span>
<span id="cb1-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Regression approach</span></span>
<span id="cb1-17">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.concatenate([group0, group1])</span>
<span id="cb1-18">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.concatenate([np.zeros(n0), np.ones(n1)])</span>
<span id="cb1-19">X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sm.add_constant(x)</span>
<span id="cb1-20">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sm.OLS(y, X).fit()</span>
<span id="cb1-21"></span>
<span id="cb1-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Compare</span></span>
<span id="cb1-23"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"t-test statistic: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>t_stat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.6f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-24"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Regression t-stat for β₁: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>model<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>tvalues[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.6f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-25"></span>
<span id="cb1-26"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">t-test p-value: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>p_val_ttest<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.6f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-27"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Regression p-value: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>model<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>pvalues[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.6f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>t-test statistic: 3.258749
Regression t-stat for β₁: 3.258749

t-test p-value: 0.002190
Regression p-value: 0.002190</code></pre>
</div>
</div>
<p>As promised, the two-sample equal-variance t-test yields identical results to a linear regression with a dummy variable.</p>
</section>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Ok, I mostly just wanted to prove to myself that I could write a short post that didn’t take an embarrassing amount of time to research and write. Let’s consider this experiment a success! See you next time.</p>


</section>

 ]]></description>
  <category>statistics</category>
  <guid>https://randomrealizations.com/posts/t-test-is-ols/</guid>
  <pubDate>Mon, 19 Jan 2026 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/enso-thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Logistic Regression with PyTorch</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/logistic-regression-with-pytorch/</link>
  <description><![CDATA[ 





<!-- Well, dear reader, while I know you've grown to appreciate the meticulous craftsmanship of the typical Random Realizations article, I've been curious lately whether we might both benefit from a more rapid publication cadence with more incremental and perhaps slightly less polished posts.
So today we'll give it a try, and you can let me know how it's working for you. -->
<p>Note from December 2025: Well dear reader, it looks like I wrote this post back in July and forgot to publish it, so here’s my early Christmas present to you. Enjoy!</p>
<p>In this post we’ll bridge the gap between traditional ML and deep learning by showing that logistic regression is a special case of a neural network, and we’ll compare the classic scikit-learn logistic regression to a neural network implementation that we’ll build in PyTorch. Then we’ll add some hidden layers to our PyTorch model to go from logistic regression to the multi-layer perceptron, a simple deep neural network that’s like the major scale of deep learning model architectures.</p>
<!-- ![Some MNIST Digits](digits.png "") -->
<section id="multiclass-logistic-regressiontraditional-ml-vs-neural-network" class="level2">
<h2 class="anchored" data-anchor-id="multiclass-logistic-regressiontraditional-ml-vs-neural-network">Multiclass Logistic Regression—Traditional ML vs Neural Network</h2>
<p>We want to classify <img src="https://latex.codecogs.com/png.latex?N"> instances, each a <img src="https://latex.codecogs.com/png.latex?D"> dimensional input, into one of <img src="https://latex.codecogs.com/png.latex?K"> discrete classes by predicting the probability mass function over the <img src="https://latex.codecogs.com/png.latex?K"> classes. In matrix notation, the classical ML model is</p>
<p><img src="https://latex.codecogs.com/png.latex?%20z%20=%20%20X%20W%5ET%20+%20b%20"> <img src="https://latex.codecogs.com/png.latex?%20%5Chat%7Bp%7D%20=%20%5Ctext%7Bsoftmax%7D(z)%20=%20%5Cfrac%7B%5Cexp%20(z)%7D%20%7B%5Csum_%7Bk=1%7D%5EK%20%5Cexp%20(z_k)%7D"></p>
<p>where</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?X%20%5Cin%20%5Cmathbb%7BR%7D%5E%7BN%20%5Ctimes%20D%7D"> is the <img src="https://latex.codecogs.com/png.latex?D"> dimensional input data for each instance</li>
<li><img src="https://latex.codecogs.com/png.latex?W%20%5Cin%20%5Cmathbb%7BR%7D%5E%7BK%20%5Ctimes%20D%7D"> is the coefficient matrix (<img src="https://latex.codecogs.com/png.latex?D"> coefficients for each class)</li>
<li><img src="https://latex.codecogs.com/png.latex?b%20%5Cin%20%5Cmathbb%7BR%7D%5EK"> is the intercept for each class</li>
<li><img src="https://latex.codecogs.com/png.latex?z%20%5Cin%20%5Cmathbb%7BR%7D%5E%7BN%20%5Ctimes%20K%7D"> are the <img src="https://latex.codecogs.com/png.latex?K"> raw logits or linear scores for each instance</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsoftmax%7D(%5Ccdot):%5Cmathbb%7BR%7D%5EK%5Crightarrow(0,1)%5EK"> is applied to each instance to transform the logits in <img src="https://latex.codecogs.com/png.latex?(-%5Cinfty,%20%5Cinfty)"> to probabilities in <img src="https://latex.codecogs.com/png.latex?(0,1)">.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Chat%7Bp%7D%20%5Cin%20(0,1)%5E%7BN%20%5Ctimes%20K%7D"> are the <img src="https://latex.codecogs.com/png.latex?K"> class probabilities predicted for each instance</li>
</ul>
<p>In neural network terms we can express the above formulation as a network with</p>
<ul>
<li>Input layer: <img src="https://latex.codecogs.com/png.latex?X"></li>
<li>Linear layer: <img src="https://latex.codecogs.com/png.latex?z=XW%5ET+b"></li>
<li>Non-linear activation: <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsoftmax%7D(z)"></li>
</ul>
<p>In both cases, model training is guided by a negative log likelihood loss function.</p>
<blockquote class="blockquote">
<p>FYI these formulations are also closely related to multi-class gradient boosting, which We talked about back in the <a href="../../posts/gradient-boosting-multi-class-classification-from-scratch/">gradient boosting for multi-class classification from scratch</a> post. You can go back and reread that post for some additional intuition on how multi-class classification works.</p>
</blockquote>
<p>Let’s implement logistic regression as a traditional ML model and as a neural network.</p>
</section>
<section id="mnist-data" class="level2">
<h2 class="anchored" data-anchor-id="mnist-data">MNIST Data</h2>
<p>We’ll train our logistic regression models to classify the handwritten digits in the classic <a href="https://en.wikipedia.org/wiki/MNIST_database">MNIST dataset</a>. Adapting this <a href="https://scikit-learn.org/stable/auto_examples/linear_model/plot_sparse_logistic_regression_mnist.html">scikit-learn example</a>, we’ll load up the data, plot some of the digits, normalize the input images, and then fit a classical logistic regression model.</p>
<div id="50537e0a" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> fetch_openml</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.linear_model <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LogisticRegression</span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StandardScaler</span>
<span id="cb1-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.utils <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> check_random_state</span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Load data from https://www.openml.org/d/554</span></span>
<span id="cb1-11">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fetch_openml(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mnist_784"</span>, version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, return_X_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb1-12"></span>
<span id="cb1-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shuffle the data</span></span>
<span id="cb1-14">random_state <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> check_random_state(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-15">permutation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> random_state.permutation(X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb1-16">X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X[permutation]</span>
<span id="cb1-17">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y[permutation]</span>
<span id="cb1-18">X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X.reshape((X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb1-19"></span>
<span id="cb1-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train test split</span></span>
<span id="cb1-21">train_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10_000</span></span>
<span id="cb1-22">test_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10_000</span></span>
<span id="cb1-23">X_train, X_test, y_train, y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(</span>
<span id="cb1-24">    X, y, train_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_samples, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>test_samples</span>
<span id="cb1-25">)</span>
<span id="cb1-26"></span>
<span id="cb1-27"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Normalize image data</span></span>
<span id="cb1-28">scaler <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> StandardScaler()</span>
<span id="cb1-29">X_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scaler.fit_transform(X_train)</span>
<span id="cb1-30">X_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scaler.transform(X_test)</span></code></pre></div></div>
</div>
<div id="bde8a220" class="cell" data-execution_count="152">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Number of classes: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(np.unique(y))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb2-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Shape of X: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>X<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Number of classes: 10
Shape of X: (70000, 784)</code></pre>
</div>
</div>
<p>We have <img src="https://latex.codecogs.com/png.latex?K=10"> classes corresponding to the digits 0-9. The image data in <code>X</code> is stored as a <img src="https://latex.codecogs.com/png.latex?N%20%5Ctimes%20D"> array with <img src="https://latex.codecogs.com/png.latex?N=70000"> images and each image having <img src="https://latex.codecogs.com/png.latex?D=784"> pixels. In this raw form, the images are flattened out into a single dimension, which is ideal for modeling. To visualize them, we’ll need to reshape each image from <img src="https://latex.codecogs.com/png.latex?1%20%5Ctimes%20784"> to <img src="https://latex.codecogs.com/png.latex?28%20%5Ctimes%2028">.</p>
<div id="9c38bb45" class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_digits(X, n_rows, n_cols):</span>
<span id="cb4-2">    X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>)</span>
<span id="cb4-3">    n_images <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n_rows <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_cols</span>
<span id="cb4-4">    fig, axs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(n_rows, n_cols, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>n_cols, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>n_rows))</span>
<span id="cb4-5"></span>
<span id="cb4-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Flatten axs to iterate easily</span></span>
<span id="cb4-7">    axs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axs.flatten()</span>
<span id="cb4-8"></span>
<span id="cb4-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n_images):</span>
<span id="cb4-10">        axs[i].imshow(X[i], cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gray"</span>)</span>
<span id="cb4-11">        axs[i].axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># turn off axes completely</span></span>
<span id="cb4-12"></span>
<span id="cb4-13">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Remove all spacing between plots</span></span>
<span id="cb4-14">    plt.subplots_adjust(wspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, hspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-15">    plt.tight_layout(pad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-16">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># return fig, axs</span></span>
<span id="cb4-17"></span>
<span id="cb4-18">plot_digits(X, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># post image</span></span>
<span id="cb4-19"></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/logistic-regression-with-pytorch/nn_files/figure-html/cell-4-output-1.png" class="img-fluid figure-img" alt="grid of digit images"></p>
<figcaption>Some instances from the MNIST hand-written digit dataset</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="logistic-regression-with-scikit-learn" class="level2">
<h2 class="anchored" data-anchor-id="logistic-regression-with-scikit-learn">Logistic Regression with scikit-learn</h2>
<p>We’ll start with the traditional logistic regression model implementation from scikit-learn.</p>
<div id="25a08d16" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Classical Logistic Regression</span></span>
<span id="cb5-2"></span>
<span id="cb5-3">clf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LogisticRegression(penalty<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, solver<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sag"</span>, tol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>) </span>
<span id="cb5-4">clf.fit(X_train, y_train)</span>
<span id="cb5-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Test Accuracy: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> clf<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>score(X_test, y_test)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Test Accuracy: 89.39%</code></pre>
</div>
</div>
<p>Now to visualize what this model is doing, let’s have a look at its coefficients.</p>
<div id="38d06056" class="cell" data-execution_count="95">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">clf.coef_.shape</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="95">
<pre><code>(10, 784)</code></pre>
</div>
</div>
<p>Recall the coefficients <img src="https://latex.codecogs.com/png.latex?W"> are in a <img src="https://latex.codecogs.com/png.latex?K%20%5Ctimes%20D"> array, so each of the <img src="https://latex.codecogs.com/png.latex?K"> rows contains the <img src="https://latex.codecogs.com/png.latex?D"> coefficients for the corresponding class. Let’s reshape each of the rows into a 28 by 28 image and plot them.</p>
<div id="513712bd" class="cell" data-execution_count="96">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_class_weights(weights: np.ndarray, title: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Classification Weights"</span>):</span>
<span id="cb9-2">    num_classes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> weights.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb9-3">    n_rows, n_cols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, (num_classes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb9-4"></span>
<span id="cb9-5">    fig, axs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(n_rows, n_cols, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb9-6">    scale <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(weights).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()</span>
<span id="cb9-7"></span>
<span id="cb9-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Set up shared color scale</span></span>
<span id="cb9-9">    cmap <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.cm.viridis</span>
<span id="cb9-10">    norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.Normalize(vmin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span>scale, vmax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>scale)</span>
<span id="cb9-11"></span>
<span id="cb9-12">    axs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axs.flatten()</span>
<span id="cb9-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_classes):</span>
<span id="cb9-14">        ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axs[i]</span>
<span id="cb9-15">        im <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax.imshow(</span>
<span id="cb9-16">            weights[i].reshape(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>),</span>
<span id="cb9-17">            interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nearest"</span>,</span>
<span id="cb9-18">            cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cmap,</span>
<span id="cb9-19">            norm<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>norm</span>
<span id="cb9-20">        )</span>
<span id="cb9-21">        ax.set_xticks(())</span>
<span id="cb9-22">        ax.set_yticks(())</span>
<span id="cb9-23">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ax.set_xlabel(f"Class {i}")</span></span>
<span id="cb9-24">        ax.set_xlabel(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Class </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, labelpad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb9-25">        ax.xaxis.set_label_position(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'top'</span>)</span>
<span id="cb9-26"></span>
<span id="cb9-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_classes, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(axs)):</span>
<span id="cb9-28">        axs[j].axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'off'</span>)</span>
<span id="cb9-29"></span>
<span id="cb9-30">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add colorbar BELOW the entire figure</span></span>
<span id="cb9-31">    cbar_ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fig.add_axes([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>])  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [left, bottom, width, height]</span></span>
<span id="cb9-32">    fig.colorbar(</span>
<span id="cb9-33">        plt.cm.ScalarMappable(norm<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>norm, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cmap),</span>
<span id="cb9-34">        cax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cbar_ax,</span>
<span id="cb9-35">        orientation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"horizontal"</span></span>
<span id="cb9-36">    ).set_label(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"value"</span>)</span>
<span id="cb9-37"></span>
<span id="cb9-38">    fig.suptitle(title)</span>
<span id="cb9-39">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># plt.tight_layout(rect=[0, 0.05, 1, 0.95])  # Make space for suptitle</span></span>
<span id="cb9-40">    plt.show()</span></code></pre></div></div>
</details>
</div>
<div id="d801fd5e" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">plot_class_weights(clf.coef_, title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Scikit-learn Logistic Regression Coefficients"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/logistic-regression-with-pytorch/nn_files/figure-html/cell-8-output-1.png" class="img-fluid figure-img" alt="Traditional logistic regression coefficients for each class"></p>
<figcaption>Traditional logistic regression coefficients for each class</figcaption>
</figure>
</div>
</div>
</div>
<p>Intuitively, for a given digit, we’d expect the coefficients to be positive on pixels where the digit is typically located, and we’d expect the coefficients to be zero or perhaps even negative on pixels where other digits tend to be located. We can see that’s more or less what this model is doing.</p>
</section>
<section id="logistic-regression-in-pytorch" class="level2">
<h2 class="anchored" data-anchor-id="logistic-regression-in-pytorch">Logistic Regression in PyTorch</h2>
<p>I recommend checking out the PyTorch <a href="https://docs.pytorch.org/tutorials/beginner/basics/intro.html">Basic Tutorial</a> to get started with the library’s API. Our basic flow for creating PyTorch models will look like</p>
<ol type="1">
<li>Create <code>Dataset</code> and <code>DataLoader</code> objects.</li>
<li>Build the model.</li>
<li>Train the model.</li>
</ol>
<section id="create-pytorch-dataset-and-dataloader-objects" class="level3">
<h3 class="anchored" data-anchor-id="create-pytorch-dataset-and-dataloader-objects">Create PyTorch <code>Dataset</code> and <code>DataLoader</code> Objects</h3>
<div id="b50a8d9a" class="cell" data-execution_count="98">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch</span>
<span id="cb11-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> torch.utils.data <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TensorDataset, DataLoader</span>
<span id="cb11-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch.nn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> nn</span>
<span id="cb11-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch.optim <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> optim</span>
<span id="cb11-5"></span>
<span id="cb11-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Convert to torch tensors</span></span>
<span id="cb11-7">X_train_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor(X_train, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.float32)</span>
<span id="cb11-8">y_train_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor(y_train.astype(np.int64), dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">long</span>)</span>
<span id="cb11-9">X_test_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor(X_test, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.float32)</span>
<span id="cb11-10">y_test_tensor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor(y_test.astype(np.int64), dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>torch.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">long</span>)</span>
<span id="cb11-11"></span>
<span id="cb11-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Wrap in TensorDataset</span></span>
<span id="cb11-13">train_dataset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TensorDataset(X_train_tensor, y_train_tensor)</span>
<span id="cb11-14">test_dataset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TensorDataset(X_test_tensor, y_test_tensor)</span>
<span id="cb11-15"></span>
<span id="cb11-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create DataLoaders</span></span>
<span id="cb11-17">batch_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">64</span></span>
<span id="cb11-18">train_loader <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataLoader(train_dataset, batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>batch_size, shuffle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb11-19">test_loader <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DataLoader(test_dataset, batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>batch_size, shuffle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span></code></pre></div></div>
</div>
</section>
<section id="build-the-model" class="level3">
<h3 class="anchored" data-anchor-id="build-the-model">Build the Model</h3>
<div id="98b1afca" class="cell" data-execution_count="128">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Logistic Regression Model</span></span>
<span id="cb12-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> LogReg(nn.Module):</span>
<span id="cb12-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb12-4">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>()</span>
<span id="cb12-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.linear <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">784</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb12-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.activation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.LogSoftmax(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># returns log probabilities</span></span>
<span id="cb12-7"></span>
<span id="cb12-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> forward(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb12-9">        z <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.linear(x)</span>
<span id="cb12-10">        p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.activation(z)</span>
<span id="cb12-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> p</span>
<span id="cb12-12"></span>
<span id="cb12-13">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LogReg()</span></code></pre></div></div>
</div>
</section>
<section id="train-the-model" class="level3">
<h3 class="anchored" data-anchor-id="train-the-model">Train the Model</h3>
<div id="4dc0164b" class="cell" data-execution_count="129">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Hyperparameters</span></span>
<span id="cb13-2">num_epochs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb13-3">learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span></span>
<span id="cb13-4"></span>
<span id="cb13-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Loss</span></span>
<span id="cb13-6">criterion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.NLLLoss() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># expects log probabilities</span></span>
<span id="cb13-7"></span>
<span id="cb13-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Optimizer</span></span>
<span id="cb13-9">optimizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optim.SGD(model.parameters(), lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>learning_rate)</span>
<span id="cb13-10"></span>
<span id="cb13-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Training loop</span></span>
<span id="cb13-12"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> epoch <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_epochs):</span>
<span id="cb13-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> images, labels <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> train_loader:</span>
<span id="cb13-14">        images <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> images.view(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Flatten</span></span>
<span id="cb13-15">        outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(images)</span>
<span id="cb13-16">        loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> criterion(outputs, labels)</span>
<span id="cb13-17"></span>
<span id="cb13-18">        optimizer.zero_grad()</span>
<span id="cb13-19">        loss.backward()</span>
<span id="cb13-20">        optimizer.step()</span>
<span id="cb13-21"></span>
<span id="cb13-22">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Epoch [</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>epoch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_epochs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">], Training Loss: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>loss<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>item()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Epoch [1/5], Training Loss: 0.4151
Epoch [2/5], Training Loss: 0.1858
Epoch [3/5], Training Loss: 0.1102
Epoch [4/5], Training Loss: 0.5600
Epoch [5/5], Training Loss: 0.4414</code></pre>
</div>
</div>
</section>
<section id="evaluate-the-model" class="level3">
<h3 class="anchored" data-anchor-id="evaluate-the-model">Evaluate the Model</h3>
<div id="5c79af15" class="cell" data-execution_count="130">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Evaluate model</span></span>
<span id="cb15-2">model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb15-3">correct <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb15-4">total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb15-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.no_grad():</span>
<span id="cb15-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> images, labels <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> test_loader:</span>
<span id="cb15-7">        images <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> images.view(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>)</span>
<span id="cb15-8">        outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(images)</span>
<span id="cb15-9">        _, predicted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(outputs.data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb15-10">        total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> labels.size(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb15-11">        correct <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> (predicted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> labels).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().item()</span>
<span id="cb15-12"></span>
<span id="cb15-13"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Test Accuracy: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> correct <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> total<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Test Accuracy: 90.71%</code></pre>
</div>
</div>
</section>
<section id="pytorch-model-weights" class="level3">
<h3 class="anchored" data-anchor-id="pytorch-model-weights">PyTorch Model Weights</h3>
<p>Let’s take a look at the weights.</p>
<div id="2b787d80" class="cell" data-execution_count="131">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.linear.weight.detach().numpy()</span>
<span id="cb17-2">weights.shape</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="131">
<pre><code>(10, 784)</code></pre>
</div>
</div>
<div id="79baf6df" class="cell" data-execution_count="132">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1">plot_class_weights(weights, title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"PyTorch Logistic Regression Weights"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/logistic-regression-with-pytorch/nn_files/figure-html/cell-14-output-1.png" class="img-fluid figure-img" alt="PyTorch logistic regression coefficients for each class"></p>
<figcaption>PyTorch logistic regression coefficients for each class</figcaption>
</figure>
</div>
</div>
</div>
<p>Nice! We can see that the weights from the neural network are qualitatively similar to the coefficients from the logistic regression model. Interestingly, the neural network weight patterns look a bit more noisy than the classical logistic regression coefficients, and yet, the models are performing similarly on the test data (89-90%). Likely there are a lot of logistic regression parameter solutions that yield similar performance, and these two models have found slightly different solutions in parameter space.</p>
</section>
</section>
<section id="multilayer-perceptron-in-pytorch" class="level2">
<h2 class="anchored" data-anchor-id="multilayer-perceptron-in-pytorch">Multilayer Perceptron in PyTorch</h2>
<p>Well, logistic regression is great and all, but of course, the reason for messing around with PyTorch is so that we can start building more interesting neural network architectures. The next obvious step is to build out a <a href="https://en.wikipedia.org/wiki/Multilayer_perceptron">multilayer perceptron</a> (MLP). The MLP is a network with</p>
<ul>
<li>An input layer</li>
<li>One or more hidden layers comprised of a linear transformation passed to a non-linear activation function</li>
<li>An output layer, e.g.&nbsp;returning class probabilities</li>
</ul>
<p>When we add “hidden” layers between the input and output layers, the network earns the modifier “deep”, meaning that MLP’s are deep networks. We’ll build a model with two hidden layers that uses <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">rectified linear unit activation functions</a> (ReLU). The ReLU just replaces negative inputs with zero and passes positive inputs through unchanged—a very simple form of non-linearity.</p>
<div id="a6038b9e" class="cell" data-execution_count="153">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> MLP(nn.Module):</span>
<span id="cb20-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb20-3">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>()</span>
<span id="cb20-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.net <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Sequential(</span>
<span id="cb20-5">            nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">784</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">256</span>),   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Input layer</span></span>
<span id="cb20-6">            nn.ReLU(),</span>
<span id="cb20-7">            nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">256</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">128</span>),   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Hidden layer</span></span>
<span id="cb20-8">            nn.ReLU(),</span>
<span id="cb20-9">            nn.Linear(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">128</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>),</span>
<span id="cb20-10">            nn.LogSoftmax(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># output layer - log probabilities</span></span>
<span id="cb20-11">        )</span>
<span id="cb20-12"></span>
<span id="cb20-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> forward(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb20-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.net(x)</span>
<span id="cb20-15"></span>
<span id="cb20-16">mlp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MLP()</span></code></pre></div></div>
</div>
<div id="1a69b7d4" class="cell" data-execution_count="154">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Hyperparameters</span></span>
<span id="cb21-2">num_epochs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span></span>
<span id="cb21-3">learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span></span>
<span id="cb21-4"></span>
<span id="cb21-5">optimizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.optim.Adam(mlp.parameters(), lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>learning_rate)</span>
<span id="cb21-6">criterion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.NLLLoss() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># expects log probability</span></span>
<span id="cb21-7"></span>
<span id="cb21-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Training loop</span></span>
<span id="cb21-9">mlp.train()</span>
<span id="cb21-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> epoch <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_epochs):</span>
<span id="cb21-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> images, labels <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> train_loader:</span>
<span id="cb21-12">        images <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> images.view(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Flatten</span></span>
<span id="cb21-13">        outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mlp(images)</span>
<span id="cb21-14">        loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> criterion(outputs, labels)</span>
<span id="cb21-15"></span>
<span id="cb21-16">        optimizer.zero_grad()</span>
<span id="cb21-17">        loss.backward()</span>
<span id="cb21-18">        optimizer.step()</span>
<span id="cb21-19"></span>
<span id="cb21-20">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Epoch [</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>epoch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_epochs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">], Training Loss: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>loss<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>item()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Epoch [1/20], Training Loss: 0.4061
Epoch [2/20], Training Loss: 0.0821
Epoch [3/20], Training Loss: 0.0214
Epoch [4/20], Training Loss: 0.0585
Epoch [5/20], Training Loss: 0.0027
Epoch [6/20], Training Loss: 0.0086
Epoch [7/20], Training Loss: 0.0005
Epoch [8/20], Training Loss: 0.0018
Epoch [9/20], Training Loss: 0.0016
Epoch [10/20], Training Loss: 0.0809
Epoch [11/20], Training Loss: 0.0024
Epoch [12/20], Training Loss: 0.0000
Epoch [13/20], Training Loss: 0.0002
Epoch [14/20], Training Loss: 0.0001
Epoch [15/20], Training Loss: 0.0001
Epoch [16/20], Training Loss: 0.0004
Epoch [17/20], Training Loss: 0.0015
Epoch [18/20], Training Loss: 0.0011
Epoch [19/20], Training Loss: 0.0004
Epoch [20/20], Training Loss: 0.0000</code></pre>
</div>
</div>
<div id="1bc26754" class="cell" data-execution_count="155">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Evaluate model</span></span>
<span id="cb23-2">mlp.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb23-3">correct <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb23-4">total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb23-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.no_grad():</span>
<span id="cb23-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> images, labels <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> test_loader:</span>
<span id="cb23-7">        images <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> images.view(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>)</span>
<span id="cb23-8">        outputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mlp(images)</span>
<span id="cb23-9">        _, predicted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(outputs.data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb23-10">        total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> labels.size(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb23-11">        correct <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> (predicted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> labels).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().item()</span>
<span id="cb23-12"></span>
<span id="cb23-13"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Test Accuracy: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> correct <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> total<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">%"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Test Accuracy: 95.83%</code></pre>
</div>
</div>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Nice! In this post we’ve bridged the gap between classic ML and deep learning by showing that logistic regression is a special case of a neural network, building a logistic regression model in PyTorch, and then adding hidden layers to that model to obtain a multilayer perceptron.</p>


</section>

 ]]></description>
  <category>python</category>
  <category>tutorial</category>
  <category>pytorch</category>
  <guid>https://randomrealizations.com/posts/logistic-regression-with-pytorch/</guid>
  <pubDate>Fri, 04 Jul 2025 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Bayesian Modeling Primer</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/bayesian-modeling-primer/</link>
  <description><![CDATA[ 





<p>Well, dear reader, I know I haven’t been posting very much lately. That’s because I’ve been busy moving to a new city and working a new DS gig and learning some new things, including Bayesian modeling. In particular I’ve been reading Richard McElreath’s excellent book <a href="https://xcelab.net/rm/">Statistical Rethinking</a>, which I recommend to you as well. As a dedicated reader of this blog, I’m sure you’re perfectly capable of digesting a 600 page statistics textbook on your own, but just for fun, today I present to you my Bayesian statistics crash course.</p>
<p>My primary goal is to illuminate the major steps in the Bayesian workflow, that way you have a mental framework where you can store and contextualize new pieces of information as you learn. My secondary goal is to give you an intuitive understanding of Bayesian modeling from two interconnected perspectives: a mathematical formulation based primarily in probability theory and a probabilistic programming approach based on writing code to generate random data. Each perspective supports the other, and they are both necessary to grasp the full picture. I will attempt to weave these two perspectives throughout the description of the workflow, which is motivated by a toy example we’ll use throughout the post.</p>
<p>Let’s do this! ➡️</p>
<section id="the-rock-paper-scissors-pro" class="level2">
<h2 class="anchored" data-anchor-id="the-rock-paper-scissors-pro">🪨📄✂️ The Rock Paper Scissors Pro</h2>
<p>I spent a summer as an intern at RAND Corporation during my PhD. It was a fascinating place full of fascinating characters. One of the researchers, Fritz R, liked to take each cohort of interns out for drinks at some point in the summer. After picking up our first round himself, Fritz offered to buy a second drink for any of the interns who could beat him in a rock paper scissors (RPS) match, warning us that he was “pretty good at it.”</p>
<p>Let’s fact check his claim. We’d like to know something about his actual RPS win rate, but that is unobservable. We can’t observe it directly, but we could observe some match outcomes and make an inference about what his actual win rate might plausibly be.</p>
<p>Let’s say that after facing off with the 10 interns, Fritz racks up the following match outcomes.</p>
<div id="cell-3" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">observed_outcomes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span></code></pre></div></div>
</div>
<p>He won 7 out of 10 matches—not bad. But is his performance the result of skill or simply a lucky round? We’re going to address this question using Bayesian statistical analysis.</p>
</section>
<section id="the-bayesian-workflow-in-3-steps" class="level2">
<h2 class="anchored" data-anchor-id="the-bayesian-workflow-in-3-steps">🛠️ The Bayesian Workflow in 3 Steps</h2>
<p>I consider the Bayesian workflow to have 3 major steps:</p>
<ol type="1">
<li><strong>Modeling</strong> - specify the data generating process as a generative model</li>
<li><strong>Inference</strong> - use the model, the observed data, and some inference algorithm to infer the values of unknown model parameters</li>
<li><strong>Interpretation</strong> - summarize and interpret the inferred model parameters to answer your analysis questions</li>
</ol>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/modeling-inference-interpretation.png" title="." class="img-fluid figure-img"></p>
<figcaption>The Bayesian Workflow: modeling, inference, interpretation.</figcaption>
</figure>
</div>
</section>
<section id="step-1.-modeling" class="level2">
<h2 class="anchored" data-anchor-id="step-1.-modeling">⚙️ Step 1. Modeling</h2>
<section id="modeling-the-data-generating-process" class="level3">
<h3 class="anchored" data-anchor-id="modeling-the-data-generating-process">Modeling the Data Generating Process</h3>
<p>In this step, we’re going to build a <em>generative model</em>, i.e.&nbsp;a model that can simulate data similar to our observed data. If you’re coming from ML, the key mental shift is to think about modeling the <em>data generating process (DGP)</em>, rather than curve-fitting the data itself. Practically this means our model is a set of random variables which relate to one another in some way and from which we can draw realizations… random realizations, that is. You can invent a DGP as follows:</p>
<ol type="1">
<li>Identify the key variables in the system.</li>
<li>Define each variable as a draw from some probability distribution, or in terms of the other variables.</li>
<li>Use unknown parameters as needed in the probability distributions or in the functional relationships among the key variables.</li>
</ol>
<p>In our RPS example, there is one key variable—Fritz’s match outcome. We can define the match outcome variable as a random draw from some distribution, e.g.&nbsp;a Bernoulli distribution. The Bernoulli distribution has one parameter—the success probability—which corresponds here to Fritz’s actual true win rate. Given some true win rate, we can simulate match outcomes by drawing realizations from the Bernoulli distribution.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20y_i%20%5Csim%20%5Ctext%7BBernoulli%7D(%5Ctheta)%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?y_i%20=%200"> if Fritz loses to intern <img src="https://latex.codecogs.com/png.latex?i"> and <img src="https://latex.codecogs.com/png.latex?y_i%20=%201"> if he wins, and <img src="https://latex.codecogs.com/png.latex?i=1,%5Cdots,N"> where <img src="https://latex.codecogs.com/png.latex?N=10">. In this DGP, the parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> corresponds to Fritz’s true win rate.</p>
<p>This is a good start, but we can’t simulate data from this model yet because <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> has no particular value. So, what value should we use?</p>
</section>
<section id="probability-as-relative-plausibility" class="level3">
<h3 class="anchored" data-anchor-id="probability-as-relative-plausibility">Probability as Relative Plausibility</h3>
<p>One of the key ideas in Bayesian modeling is that we can represent the relative plausibility of potential values of any unobserved variable using a probability distribution. Highly plausible values get higher probability, and less plausible values get lower probability.</p>
<p><em>It is this view of probability as a measure of relative plausibility that distinguishes Bayesian statistics from Frequentist statistics, which views probability as the relative frequency of events.</em></p>
<p>We don’t know the true value of Fritz’s RPS win rate, but even before collecting any data, we might have some contextual knowledge about how the world works which can provide some prior information about the relative plausibility of its possible values. For me it’s easiest to think in terms of how surprising a given true value would be. I wouldn’t be surprised at all if his win rate was near 0.5, but I would be shocked if it was 0.9 or 0.1, hence 0.5 has higher relative plausibility than 0.9 or 0.1.</p>
<p>Let’s represent the prior relative plausibility of values of Fritz’s RPS win rate with a probability distribution. Below are a few different probability distributions defined over the possible values <img src="https://latex.codecogs.com/png.latex?0%20%5Cle%20%5Ctheta%20%5Cle%201">.</p>
<div id="cell-7" class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb2-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb2-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb2-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.stats <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> beta, bernoulli</span>
<span id="cb2-5"></span>
<span id="cb2-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># set colors for later</span></span>
<span id="cb2-7">prior_color <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"C0"</span></span>
<span id="cb2-8">post_color <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"C1"</span></span>
<span id="cb2-9"></span>
<span id="cb2-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># prior beta parameters</span></span>
<span id="cb2-11">parameters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb2-12">    (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>),</span>
<span id="cb2-13">    (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>),</span>
<span id="cb2-14">    (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb2-15">]</span>
<span id="cb2-16"></span>
<span id="cb2-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># plot the prior</span></span>
<span id="cb2-18">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb2-19">plt.figure()</span>
<span id="cb2-20"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, (alpha, beta_val) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(parameters):</span>
<span id="cb2-21">    y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> beta.pdf(x, alpha, beta_val)</span>
<span id="cb2-22">    label <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Beta($</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">alpha$=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>alpha<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, $</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">beta$=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>beta_val<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)'</span></span>
<span id="cb2-23">    plt.plot(x, y, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>label)</span>
<span id="cb2-24"></span>
<span id="cb2-25">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"win rate (theta)"</span>)</span>
<span id="cb2-26">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Probability Density"</span>)</span>
<span id="cb2-27">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Relative Plausibility of RPS Win Rate'</span>)</span>
<span id="cb2-28">plt.legend()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-3-output-1.png" class="img-fluid figure-img" alt="beta distribution priors"></p>
</figure>
</div>
</div>
</div>
<p>Each of these PDFs has a mode at <img src="https://latex.codecogs.com/png.latex?%5Ctheta=0.5"> and decreases toward 0 and 1. They’re all aligned with the relative plausibilities we discussed earlier.</p>
<p>You can check the relative plausibility between two possible values of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> implied by a given pdf by taking the ratio of the height of the pdf at one value of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> versus the height at another value of <img src="https://latex.codecogs.com/png.latex?%5Ctheta">.</p>
<p>For example, let’s compare <img src="https://latex.codecogs.com/png.latex?%5Ctheta=0.5"> to <img src="https://latex.codecogs.com/png.latex?%5Ctheta=0.7"> for a Beta(10, 10) prior.</p>
<div id="cell-9" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">beta.pdf(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> beta.pdf(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="3">
<pre><code>np.float64(4.802710683776413)</code></pre>
</div>
</div>
<p>The Beta(10, 10) distribution implies that a 0.5 win rate is about 5 times more plausible than a 0.7 win rate, which sounds, ahem, plausible.</p>
</section>
<section id="priors" class="level3">
<h3 class="anchored" data-anchor-id="priors">Priors</h3>
<p>We can include this prior information about the relative plausibility of values of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> in our model as follows.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctheta%20%5Csim%20%5Ctext%7BBeta%7D(10,%2010)%0A"> <img src="https://latex.codecogs.com/png.latex?%0Ay_i%20%5Csim%20%5Ctext%7BBernoulli%7D(%5Ctheta)%0A"></p>
<p>In Bayesian parlance, we call the probability distribution that represents the relative plausibilities of an unobserved parameter its <em>prior distribution</em>, or simply its <em>prior</em>. Notice that with the addition of the prior for <img src="https://latex.codecogs.com/png.latex?%5Ctheta">, our model is now fully generative.</p>
</section>
<section id="implementing-the-generative-model" class="level3">
<h3 class="anchored" data-anchor-id="implementing-the-generative-model">Implementing the generative model</h3>
<p>Let’s implement the DGP using random variables from <code>scipy</code>.</p>
<div id="cell-11" class="cell" data-execution_count="24">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Implementing the DGP as a generative model</span></span>
<span id="cb5-2"></span>
<span id="cb5-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> draw_from_prior(alpha_param, beta_param):</span>
<span id="cb5-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> beta.rvs(alpha_param, beta_param)</span>
<span id="cb5-5"></span>
<span id="cb5-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> simulate_one_outcome(theta, N):</span>
<span id="cb5-7">    y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bernoulli.rvs(theta, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>N)</span>
<span id="cb5-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theta"</span>: theta, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>: y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum_y"</span>: np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(y)}</span>
<span id="cb5-9"></span>
<span id="cb5-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> simulate_outcomes(n_outcomes, alpha_param, beta_param, N):</span>
<span id="cb5-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> pd.DataFrame([</span>
<span id="cb5-12">        simulate_one_outcome(theta<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>draw_from_prior(alpha_param, beta_param), N<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>N)</span>
<span id="cb5-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n_outcomes)</span>
<span id="cb5-14">    ])</span>
<span id="cb5-15"></span>
<span id="cb5-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># set DGP parameters</span></span>
<span id="cb5-17">alpha_param, beta_param <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb5-18">N <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb5-19"></span>
<span id="cb5-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># simulate outcomes from the generative model</span></span>
<span id="cb5-21">outcome_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> simulate_outcomes(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1_000</span>, alpha_param, beta_param, N)</span>
<span id="cb5-22">outcome_df.head()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="24">
<div>


<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">theta</th>
<th data-quarto-table-cell-role="th">y</th>
<th data-quarto-table-cell-role="th">sum_y</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>0.451620</td>
<td>[0, 0, 1, 1, 1, 0, 0, 1, 0, 0]</td>
<td>4</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>0.460305</td>
<td>[0, 1, 1, 0, 1, 1, 1, 0, 1, 1]</td>
<td>7</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>0.555594</td>
<td>[0, 0, 1, 1, 1, 1, 0, 1, 0, 0]</td>
<td>5</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>0.518724</td>
<td>[1, 0, 0, 0, 1, 1, 1, 0, 1, 0]</td>
<td>5</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>0.569247</td>
<td>[1, 0, 1, 1, 0, 1, 1, 1, 1, 1]</td>
<td>8</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<p>Each time you run this simulation, you first draw a new value of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> from its prior, then that value is used in the Bernoulli distribution to draw an array of binary match win/loss observations. To help us summarize the match observations in each simulated outcome, we also compute the sum of the match values, i.e.&nbsp;the number of wins.</p>
</section>
<section id="prior-predictive-check" class="level3">
<h3 class="anchored" data-anchor-id="prior-predictive-check">Prior Predictive Check</h3>
<p>But how do we know that the prior we chose is reasonable? There are two places we can look: (1) at the parameter itself and (2) at the downstream variables it influences. We already looked at the parameter itself by inspecting its pdf and thinking about the relative plausibilities it implies. To look at its impact on the downstream variables, we can simply run simulations from the model and inspect the outcome data it produces. If we see it’s generating lots of highly implausible outcomes, then we know something isn’t right. This process is called a <em>prior predictive check</em>, because we’re checking the simulated outcomes (a.k.a. predictions) implied by the prior. Let’s run our model simulation 1000 times and have a look at the distribution of the number of wins out of 10 matches that it predicts, i.e.&nbsp;the sum of the <code>y</code> variable from each simulation.</p>
<div id="cell-13" class="cell" data-execution_count="7">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">outcome_df.hist(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum_y"</span>, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>prior_color)</span>
<span id="cb6-2">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sum(y)'</span>)</span>
<span id="cb6-3">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'count'</span>)</span>
<span id="cb6-4">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Prior Predictive Check'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-6-output-1.png" class="img-fluid figure-img" alt="prior predictive check of number of match wins"></p>
</figure>
</div>
</div>
</div>
<p>The histogram shows most of the simulations yield between 3 and 7 wins, with very few outcomes less than 3 or greater than 7. That seems pretty reasonable.</p>
<p>Let’s look at what the prior predictive check might look like when things aren’t quite right.</p>
<div id="cell-15" class="cell" data-execution_count="8">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">simulate_outcomes(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1_000</span>, alpha_param<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, beta_param<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, N<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>).hist(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum_y"</span>, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>prior_color)</span>
<span id="cb7-2">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sum(y)'</span>)</span>
<span id="cb7-3">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'count'</span>)</span>
<span id="cb7-4">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Prior Predictive Check'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-7-output-1.png" class="img-fluid figure-img" alt="prior predictive check of the win rate, with unexpected distribution shape"></p>
</figure>
</div>
</div>
</div>
<p>In this simulation, many of the outcomes are close to 0 or 10 wins out of 10. From our prior knowledge about RPS, we know it would be possible but very unusual for someone to win either 0/10 or 10/10 matches. This tips us off that something isn’t right with our priors. At this point we would iterate on our priors until we find something reasonable like our Beta(10, 10).</p>
<p>Once we’ve got our generative model and its priors nailed down, we’re ready to move from the modeling step to the inference step!</p>
</section>
</section>
<section id="step-2.-inference" class="level2">
<h2 class="anchored" data-anchor-id="step-2.-inference">🧮 Step 2. Inference</h2>
<section id="the-goal-of-bayesian-inference" class="level3">
<h3 class="anchored" data-anchor-id="the-goal-of-bayesian-inference">The Goal of Bayesian Inference</h3>
<p>In the inference step, we use observed outcome data to infer the plausible values of the unobserved parameters. Whereas simulation passes information forward from parameters to outcomes, inference passes it backwards from observed outcomes to parameters. It’s analogous to model fitting or training in machine learning; it’s the part where we use data to learn about the model parameters. The specific output of inference is the updated relative plausibility of the unknown model parameters. Whereas we represent the prior relative plausibilities with the prior distribution, we represent the posterior relative plausibilities (after incorporating information from the data) with the <em>posterior distribution</em>, or simply, the <em>posterior</em>. Like the prior, our model’s posterior distribution is a probability density defined over the possible values of <img src="https://latex.codecogs.com/png.latex?%5Ctheta">, where larger values indicate higher relative plausibility.</p>
</section>
<section id="analytical-formulation-of-bayesian-inference" class="level3">
<h3 class="anchored" data-anchor-id="analytical-formulation-of-bayesian-inference">Analytical Formulation of Bayesian Inference</h3>
<p>Let’s nail down the mathematical formulation of Bayesian inference. We have data <img src="https://latex.codecogs.com/png.latex?y"> and parameter(s) <img src="https://latex.codecogs.com/png.latex?%5Ctheta">. These have a joint probability density <img src="https://latex.codecogs.com/png.latex?p(%5Ctheta,%20y)">. This joint distribution of data and parameters is defined by our generative model of the system—simulating data from our DGP is equivalent to drawing realizations from the joint distribution <img src="https://latex.codecogs.com/png.latex?p(%5Ctheta,%20y)">. Using the definition of conditional probability,, we can write the joint distribution as:</p>
<p><img src="https://latex.codecogs.com/png.latex?p(%5Ctheta,%20y)%20=%20p(y%7C%5Ctheta)p(%5Ctheta)%20"></p>
<p>where</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?p(%5Ctheta,%20y)"> is the <em>joint distribution</em> of parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> and data <img src="https://latex.codecogs.com/png.latex?y"></li>
<li><img src="https://latex.codecogs.com/png.latex?p(%5Ctheta)"> is the <em>prior </em> distribution of the parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta"></li>
<li><img src="https://latex.codecogs.com/png.latex?p(y%7C%5Ctheta)"> is the <em>likelihood</em>—the conditional distribution of observed data <img src="https://latex.codecogs.com/png.latex?y"> given parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta">.</li>
</ul>
<p>When we do inference we are interested in the relative plausibility of unknown parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> given data <img src="https://latex.codecogs.com/png.latex?y">, which we quantify as the conditional distribution of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> given <img src="https://latex.codecogs.com/png.latex?y">. Using Baye’s Rule, we can write the posterior as</p>
<p><img src="https://latex.codecogs.com/png.latex?%20p(%5Ctheta%20%7C%20y)%20=%20%5Cfrac%7B%20p(%5Ctheta,%20y)%20%7D%20%7B%20p(y)%20%7D%20=%20%5Cfrac%20%7B%20p(y%7C%5Ctheta)p(%5Ctheta)%20%20%7D%20%7B%20p(y)%20%7D%20%20"></p>
<p>where</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?p(%5Ctheta%20%7C%20y)"> is the <em>posterior</em> distribution of the parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta"></li>
<li><img src="https://latex.codecogs.com/png.latex?p(y)"> is the <em>marginal likelihood</em> of the data <img src="https://latex.codecogs.com/png.latex?y"> (to be explained soon)</li>
</ul>
<p>Technically, the joint distribution and the posterior are functions of <em>both</em> parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> and data <img src="https://latex.codecogs.com/png.latex?y">. But in practice when we compute the posterior, we’ll have some actual observed data—say <img src="https://latex.codecogs.com/png.latex?y_%7B%5Ctext%7Bobs%7D%7D">—so that <img src="https://latex.codecogs.com/png.latex?y"> is actually fixed at <img src="https://latex.codecogs.com/png.latex?y=y_%7B%5Ctext%7Bobs%7D%7D">. Substituting the fixed value <img src="https://latex.codecogs.com/png.latex?y_%7B%5Ctext%7Bobs%7D%7D"> in the posterior, we get</p>
<p><img src="https://latex.codecogs.com/png.latex?%20p(%5Ctheta%20%7C%20y_%7B%5Ctext%7Bobs%7D%7D)%20=%20%5Cfrac%7B%20p(%5Ctheta,%20y_%7B%5Ctext%7Bobs%7D%7D)%20%7D%20%7B%20p(y_%7B%5Ctext%7Bobs%7D%7D)%20%7D%20=%20%20%5Cfrac%20%7B%20p(y_%7B%5Ctext%7Bobs%7D%7D%7C%5Ctheta)p(%5Ctheta)%20%20%7D%20%7B%20%20%5Cint%20p(%5Ctheta%7Cy_%7B%5Ctext%7Bobs%7D%7D)p(%5Ctheta)%20d%20%5Ctheta%20%20%7D%20%20"></p>
<p>If we view <img src="https://latex.codecogs.com/png.latex?y_%7B%5Ctext%7Bobs%7D%7D"> as fixed, then the posterior can be interpreted as just the slice of the joint distribution where <img src="https://latex.codecogs.com/png.latex?y=y_%7B%5Ctext%7Bobs%7D%7D">. To get a proper conditional probability distribution, we just need to divide the sliced joint density function by the area under <img src="https://latex.codecogs.com/png.latex?p(%5Ctheta,y_%7B%5Ctext%7Bobs%7D%7D)"> along the <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> axis. And guess what? That’s exactly what the marginal likelihood is doing; <img src="https://latex.codecogs.com/png.latex?p(y_%7B%5Ctext%7Bobs%7D%7D)%20=%20%5Cint%20p(%5Ctheta%7Cy_%7B%5Ctext%7Bobs%7D%7D)p(%5Ctheta)%20d%20%5Ctheta"> is just the area under the sliced joint density, and it’s there in the denominator to normalize the sliced joint density so that we get a proper conditional distribution for the posterior.</p>
</section>
<section id="computing-the-posterior-using-grid-approximation" class="level3">
<h3 class="anchored" data-anchor-id="computing-the-posterior-using-grid-approximation">Computing the Posterior using Grid Approximation</h3>
<p>Let’s compute the posterior using the formulas we cooked up in the previous section. Earlier when we wrote down our generative model, we already identified all the pieces we need:</p>
<ul>
<li><strong>the prior</strong>—since <img src="https://latex.codecogs.com/png.latex?%5Ctheta%20%5Csim%20%5Ctext%7BBeta%7D(10,%2010)">, <img src="https://latex.codecogs.com/png.latex?p(%5Ctheta)"> is the probability density function of a <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BBeta%7D(10,10)"> random variable.</li>
<li><strong>the likelihood</strong>—since <img src="https://latex.codecogs.com/png.latex?y_i%20%5Csim%20%5Ctext%7BBernoulli%7D(%5Ctheta)">, the likelihood is the probability mass function of a Bernoulli random variable with parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta">… well, almost.</li>
</ul>
<p>The one remaining detail to iron out is that our observed data <img src="https://latex.codecogs.com/png.latex?y_%7B%5Ctext%7Bobs%7D%7D=%5By_1,%5Cdots,y_N%5D"> consists of <img src="https://latex.codecogs.com/png.latex?N=10"> observations of the binary match outcomes. Our likelihood needs to reflect the conditional probability of the entire dataset given <img src="https://latex.codecogs.com/png.latex?%5Ctheta">, not just a single observation. We know from probability theory that the joint probability of two independent events is the product of their individual probabilities. Therefore, assuming independence among our observations, the joint likelihood of the full dataset is the product of the likelihood of each observation.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20p(y_%7B%5Ctext%7Bobs%7D%7D%7C%5Ctheta)%20=%20p(y_1,%5Cdots,y_N%7C%5Ctheta)%20=%20%20%5Cprod_%7Bi=1%7D%5EN%20p(y_i%7C%5Ctheta)%20"></p>
<p>Let’s implement the prior, the likelihood, the joint distribution, and the posterior in python and plot out the prior and the posterior distribution of the parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta">.</p>
<div id="cell-18" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 0. Defining the observed data</span></span>
<span id="cb8-2"></span>
<span id="cb8-3">y_obs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(observed_outcomes)</span>
<span id="cb8-4">sum_y_obs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(y_obs)</span>
<span id="cb8-5"></span>
<span id="cb8-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1. Functions for Prior and Likelihood</span></span>
<span id="cb8-7"></span>
<span id="cb8-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> prior(theta):</span>
<span id="cb8-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> beta.pdf(theta, alpha_param, beta_param)</span>
<span id="cb8-10"></span>
<span id="cb8-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> likelihood(theta, y):</span>
<span id="cb8-12">    product_of_likelihoods <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb8-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> y_i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> y:</span>
<span id="cb8-14">        product_of_likelihoods <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> bernoulli.pmf(y_i, p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>theta)</span>
<span id="cb8-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> product_of_likelihoods</span>
<span id="cb8-16"></span>
<span id="cb8-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2. Function for Joint Density p(y, theta)</span></span>
<span id="cb8-18"></span>
<span id="cb8-19"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> joint_density(theta, y):</span>
<span id="cb8-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> likelihood(theta, y) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> prior(theta)</span>
<span id="cb8-21"></span>
<span id="cb8-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 3. Computing the Posterior by "Slicing" and Normalizing</span></span>
<span id="cb8-23"></span>
<span id="cb8-24"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> posterior_from_joint_slice(theta_values, y_observed_data):</span>
<span id="cb8-25">    </span>
<span id="cb8-26">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># compute grid of p(theta, y_obs) over values of theta and fixed y_obs</span></span>
<span id="cb8-27">    unnormalized_posterior_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([</span>
<span id="cb8-28">        joint_density(theta, y_observed_data) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> theta <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> theta_values</span>
<span id="cb8-29">    ])</span>
<span id="cb8-30">    </span>
<span id="cb8-31">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># numerical integration  to get marginal likelihood p(y_obs</span></span>
<span id="cb8-32">    delta_theta <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> theta_values[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> theta_values[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] </span>
<span id="cb8-33">    marginal_likelihood_approx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(unnormalized_posterior_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> delta_theta)</span>
<span id="cb8-34">    </span>
<span id="cb8-35">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># p(theta | y_obs) = p(theta, y_obs) / p(y_obs)</span></span>
<span id="cb8-36">    normalized_posterior_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> unnormalized_posterior_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> marginal_likelihood_approx</span>
<span id="cb8-37">    </span>
<span id="cb8-38">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> normalized_posterior_values</span></code></pre></div></div>
</div>
<div id="cell-19" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define a grid of theta values</span></span>
<span id="cb9-2">theta_grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.999</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>) </span>
<span id="cb9-3"></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate prior over the grid of theta values</span></span>
<span id="cb9-5">prior_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([prior(theta) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> theta <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> theta_grid])</span>
<span id="cb9-6"></span>
<span id="cb9-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate likelihood values over the grid of theta values and fixed y_obs</span></span>
<span id="cb9-8">likelihood_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([likelihood(theta, y_obs) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> theta <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> theta_grid])</span>
<span id="cb9-9"></span>
<span id="cb9-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate the posterior over the grid of theta values and fixed y_obs</span></span>
<span id="cb9-11">posterior_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> posterior_from_joint_slice(theta_grid, y_obs)</span></code></pre></div></div>
</div>
<div id="cell-20" class="cell" data-execution_count="11">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Plotting</span></span>
<span id="cb10-2">plt.plot(theta_grid, prior_values, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Prior p(theta) ~ Beta(</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>alpha_param<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">,</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>beta_param<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)'</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>prior_color)</span>
<span id="cb10-3">plt.plot(theta_grid, posterior_values, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Posterior p(theta|y_obs)'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>post_color, linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb10-4">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Bayesian Inference: Prior, Likelihood, and Posterior'</span>)</span>
<span id="cb10-5">plt.xlabel(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">heta</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">Probability of Match Win</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb10-6">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Density'</span>)</span>
<span id="cb10-7">plt.legend()</span>
<span id="cb10-8">plt.grid(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">':'</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>)</span>
<span id="cb10-9">plt.xlim(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb10-10">plt.ylim(bottom<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb10-11">plt.tight_layout()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-10-output-1.png" class="img-fluid figure-img" alt="plot of prior and posterior computed with  grid approximation"></p>
</figure>
</div>
</div>
</div>
<p>From the figure we can see that while the prior is centered at <img src="https://latex.codecogs.com/png.latex?%5Ctheta=0.5">, the posterior is actually pulled slightly toward larger values of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> by the observed data, indicating increased relative plausibility on win rates greater than 0.5.</p>
<p>It’s nice to see that the math works and that we can successfully implement it in code, but grid approximation is a pedagogical endeavor. In practice, when models start to get complicated, we’ll need a more flexible approach for finding the posterior.</p>
</section>
<section id="sampling-from-the-posterior" class="level3">
<h3 class="anchored" data-anchor-id="sampling-from-the-posterior">Sampling from the Posterior</h3>
<p>It turns out that we can do inference using our generative model and our observed data without having to compute the likelihood directly. But while the forward problem of simulating data from the model is quite straightforward, it’s less obvious how to approach the inverse problem of doing inference. There is no silver bullet here. In fact there are tons of different algorithms for doing inference on probabilistic models, but luckily, since virtually all the important inference algorithms use sampling-based approaches, e.g.&nbsp;Hamiltonian Monte Carlo, Metropolis-Hastings, and Variational Inference, no matter which algorithm we use under the hood, we’ll end up with the same kind of output at the end—samples of the unknown parameters which have been drawn from the posterior.</p>
<p>To get some intuition for how we can do inference by sampling from the generative model,, we’re going to implement a very simple inference algorithm called <em>rejection sampling</em>. The key idea is based on the insight we discussed earlier that the posterior is essentially a slice through the joint distribution where the data is fixed to what we actually observed. Since simulating from the generative model is equivalent to drawing samples from the joint distribution, isolating simulation outcomes where the simmulated data is equal to the observed data is equivalent to sampling from the joint distribution along the slice, and hence equivalent to sampling from the posterior.</p>
<p>The algorithm for doing Bayesian inference via rejection sampling is as follows</p>
<ol type="1">
<li>Generate a sample <img src="https://latex.codecogs.com/png.latex?(%5Ctheta%5E*,y%5E*)"> from the generative model.</li>
<li>Keep the sample if <img src="https://latex.codecogs.com/png.latex?y%5E*=y_%7B%5Ctext%7Bobs%7D%7D">, otherwise discard it.</li>
<li>Repeat 1 and 2 until the desired number of retained samples is collected.</li>
<li>The retained samples of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> can be interpreted as samples from the posterior.</li>
</ol>
<p>Let’s do this in python. In our example, the order of the wins and losses over the <img src="https://latex.codecogs.com/png.latex?N=10"> match observations doesn’t matter, so we’ll focus on the number of wins. Since <img src="https://latex.codecogs.com/png.latex?%5Csum_iy_i=7"> in our observed data, we’ll isolate the simulation outcomes where <code>sum_y</code> equals 7.</p>
<div id="cell-22" class="cell" data-execution_count="12">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb11-2">outcome_df.query(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sum_y != @sum_y_obs'</span>).plot(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum_y"</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theta"</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scatter"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"outcomes where $y^* </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">ne y_{</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">text</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{obs}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">}$"</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb11-3">outcome_df.query(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sum_y == @sum_y_obs'</span>).plot(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum_y"</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theta"</span>, kind<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scatter"</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>post_color, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"outcomes where $y^* = y_{</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">text</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{obs}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">}$"</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb11-4">ax.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sum_y_obs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>)</span>
<span id="cb11-5">ax.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sum_y_obs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>)</span>
<span id="cb11-6">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Samples from the Generative Model"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-11-output-1.png" class="img-fluid figure-img" alt="scatter plot of samples from joint distribution with posterior slice highlighted"></p>
</figure>
</div>
</div>
</div>
<p>Boom! By isolating the outcomes where <img src="https://latex.codecogs.com/png.latex?y=y_%7B%5Ctext%7Bobs%7D%7D">, we effectively have samples from the posterior. Let’s draw a larger number of samples so we get an adequate sample from the posterior.</p>
<div id="cell-24" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># drawing a large number of samples and isolating outcomes where y = y_obs</span></span>
<span id="cb12-2">rejection_sampling_outcome_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> simulate_outcomes(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10_000</span>, alpha_param, beta_param, N).query(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sum_y == @sum_y_obs'</span>)</span>
<span id="cb12-3"></span>
<span id="cb12-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># posterior samples from rejection sampling</span></span>
<span id="cb12-5">posterior_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rejection_sampling_outcome_df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theta"</span>]</span></code></pre></div></div>
</div>
<div id="cell-25" class="cell" data-execution_count="14">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1">posterior_samples.hist(bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>post_color)</span>
<span id="cb13-2">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theta"</span>)</span>
<span id="cb13-3">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Samples from the Posterior"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-13-output-1.png" class="img-fluid figure-img" alt="histogram of posterior"></p>
</figure>
</div>
</div>
</div>
<p>Now let’s put all the pieces together.</p>
<div id="cell-27" class="cell" data-execution_count="15">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb14-2">prior_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> outcome_df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theta"</span>]</span>
<span id="cb14-3">prior_samples.hist(density<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>prior_color, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prior samples"</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb14-4">posterior_samples.hist(density<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>post_color, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"posterior samples"</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb14-5">ax.plot(theta_grid, prior_values, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Prior p(theta) ~ Beta(</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>alpha_param<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">,</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>beta_param<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)'</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'--'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>prior_color)</span>
<span id="cb14-6">ax.plot(theta_grid, posterior_values, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Posterior p(theta|y_obs)'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>post_color, linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb14-7">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Bayesian Inference: Prior and Posterior'</span>)</span>
<span id="cb14-8">plt.xlabel(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">heta</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">(</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">Probability of Match Win</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">)</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb14-9">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Density'</span>)</span>
<span id="cb14-10">plt.legend()</span>
<span id="cb14-11">plt.grid(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">':'</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>)</span>
<span id="cb14-12">plt.xlim(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb14-13">plt.ylim(bottom<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb14-14">plt.tight_layout()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-14-output-1.png" class="img-fluid figure-img" alt="plot of prior and posterior as line plot from grid approximation and histogram from sampling"></p>
</figure>
</div>
</div>
</div>
<p>In this figure we have:</p>
<ol type="1">
<li>the functional form of the prior</li>
<li>the functional form of the posterior from grid approximation</li>
<li>samples from the prior drawn directly from the generative model</li>
<li>and samples of the posterior obtained by applying rejection sampling to the generative model.</li>
</ol>
<p>Great! Our sampling algorithms are generating samples from the prior and the posterior which are consistent with the functional forms we computed earlier!</p>
<p>While we used rejection sampling here, regardless of what sampling algorithm we choose, we’ll end up with the same thing after inference—a set of samples from the posterior distribution for each unknown parameter. Once we have those samples, we’re ready to move to the interpretation and analysis step.</p>
</section>
</section>
<section id="step-3.-interpretation" class="level2">
<h2 class="anchored" data-anchor-id="step-3.-interpretation">🔬 Step 3. Interpretation</h2>
<p>So how do we get insight into our analysis questions from this <code>posterior_samples</code> array? Well we’ve got samples from the posterior distribution of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> which represents our updated beliefs about the relative plausibility of different values of Fritz’s actual underlying RPS win rate. We can use them just like any other dataset to answer questions about his win rate.</p>
<p>Let’s start with getting a point estimate of his true win rate. We can simply take the mean of the samples.</p>
<div id="cell-31" class="cell" data-execution_count="25">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'point estimate of theta: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>np<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>mean(posterior_samples)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>point estimate of theta: 0.5655783348185507</code></pre>
</div>
</div>
<p>To get a confidence interval, often called a <em>credible interval</em> in the Bayesian context, we can just pull the quantiles of the posterior distribution. Note there are fancier ways to do this, e.g.&nbsp;computing highest posterior density intervals (HPDIs), but conceptually we’re basically just looking at the quantiles of the sample.</p>
<div id="cell-33" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'89% credible interval of theta:: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>np<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>quantile(posterior_samples, [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.055</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.945</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>89% credible interval of theta:: [0.42005907 0.70367915]</code></pre>
</div>
</div>
<p>What’s the probability that Fritz’s win rate is actually really good, say greater than 75%? We can just check the samples directly for the proportion greater than 0.75.</p>
<div id="cell-35" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'P[theta &gt; 0.75]: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>np<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>mean(posterior_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>P[theta &gt; 0.75]: 0.011933174224343675</code></pre>
</div>
</div>
<p>This means our analysis implies theres only a 1.5% chance that his true win rate is larger than 75%.</p>
<p>Now that we’ve taken a look at interpreting the posterior samples to get some insight into the unknown parameter <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> representing Fritz’s actual RPS win rate, we can take it one step further and make some predictions.</p>
<section id="posterior-predictive-distribution" class="level3">
<h3 class="anchored" data-anchor-id="posterior-predictive-distribution">Posterior Predictive Distribution</h3>
<p>We have one more character to meet in this cast of Bayesian players—the <em>posterior predictive</em> distribution.</p>
<p><img src="https://latex.codecogs.com/png.latex?p(y_%7B%5Ctext%7Bnew%7D%7D%7Cy_%7B%5Ctext%7Bobs%7D%7D)"></p>
<p>It represents the most plausible distribution of <em>new</em> data <img src="https://latex.codecogs.com/png.latex?y_%7B%5Ctext%7Bnew%7D%7D"> given that we observed data $y_{}, i.e.&nbsp;based on the posterior rather than the prior. Mathematically it is obtained by integrating the product of the likelihood for the new data and the posterior distribution over the parameter space.</p>
<p><img src="https://latex.codecogs.com/png.latex?p(y_%7B%5Ctext%7Bnew%7D%7D%7Cy_%7B%5Ctext%7Bobs%7D%7D)%20=%20%5Cint%20p(y_%7B%5Ctext%7Bnew%7D%7D%7C%5Ctheta)%20p(%5Ctheta%7Cy_%7B%5Ctext%7Bobs%7D%7D)%20d%5Ctheta"></p>
<p>where</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?p(y_%7B%5Ctext%7Bnew%7D%7D%7C%5Ctheta)"> is the likelihood of the new data, assuming a specific parameter value <img src="https://latex.codecogs.com/png.latex?%5Ctheta">. It’s the same likelihood function we used before, evaluated on <img src="https://latex.codecogs.com/png.latex?y_%7B%5Ctext%7Bnew%7D%7D">.</li>
<li><img src="https://latex.codecogs.com/png.latex?p(%5Ctheta%7Cy_%7B%5Ctext%7Bobs%7D%7D)"> is just the posterior distribution</li>
<li>the integral <img src="https://latex.codecogs.com/png.latex?%5Cint%20%5Cdots%20d%20%5Ctheta"> effectively “averages” the likelihood of the new data over all possible values of <img src="https://latex.codecogs.com/png.latex?%5Ctheta">, weighted by how plausible each value is according to the posterior.</li>
</ul>
<p>In terms of the DGP, we can generate samples from the posterior predictive by</p>
<ol type="1">
<li>Drawing a sample of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> from the posterior distribution.</li>
<li>Using this value of <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> to generate a value of <img src="https://latex.codecogs.com/png.latex?y"> from the generative model.</li>
</ol>
<p>Let’s implement this in python.</p>
<div id="cell-37" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> simulate_posterior_predictive(posterior_samples, N):</span>
<span id="cb21-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> pd.DataFrame([</span>
<span id="cb21-3">        simulate_one_outcome(theta<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>theta, N<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>N)</span>
<span id="cb21-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> theta <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> posterior_samples</span>
<span id="cb21-5">    ])</span>
<span id="cb21-6"></span>
<span id="cb21-7">posterior_predictive_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> simulate_posterior_predictive(posterior_samples, N)</span></code></pre></div></div>
</div>
<p>Here again, we can inspect the distribution using any familiar techniques for working with samples of data. Here’s a histogram of the posterior predictive.</p>
<div id="cell-39" class="cell" data-execution_count="21">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1">posterior_predictive_df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum_y"</span>].hist(density<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>post_color)</span>
<span id="cb22-2">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Posterior Predictive Distribution"</span>)</span>
<span id="cb22-3">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum(y)"</span>)</span>
<span id="cb22-4">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"probability mass"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/bayesian-modeling-primer/bayes_files/figure-html/cell-20-output-1.png" class="img-fluid figure-img" alt="posterior predictive of number of wins"></p>
</figure>
</div>
</div>
</div>
<p>We can use this for forecasting, e.g.&nbsp;what’s the probability that Fritz wins at least 7 games in his next round?</p>
<div id="cell-41" class="cell" data-execution_count="22">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Probability of winning &gt;= 7 in next round: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>np<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>mean(posterior_predictive_df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum_y"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Probability of winning &gt;= 7 in next round: 0.32537788385043753</code></pre>
</div>
</div>
<p>Here’s where things can get interesting. In addition to forecasting the outcome itself, we can also compute the probabilities of events that depend on the outcome. For example, let’s say Fritz has only $50 left in his wallet, and he wants to know the probability that he can cover his bill after the next round. Let’s assume each drink costs $12. We can compute that probability as follows.</p>
<div id="cell-43" class="cell" data-execution_count="23">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># probability that Fritz's next round bill is less than or equal to $50</span></span>
<span id="cb25-2"></span>
<span id="cb25-3">cost_per_drink <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">12.0</span></span>
<span id="cb25-4">posterior_predictive_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb25-5">    posterior_predictive_df</span>
<span id="cb25-6">    .assign(losses <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> x: N <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x.sum_y)</span>
<span id="cb25-7">    .assign(bill <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> x: cost_per_drink <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x.losses)</span>
<span id="cb25-8">)</span>
<span id="cb25-9"></span>
<span id="cb25-10"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Probability next round bill &lt;= $50: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>np<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>mean(posterior_predictive_df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bill"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Probability next round bill &lt;= $50: 0.5369928400954654</code></pre>
</div>
</div>
</section>
</section>
<section id="summary-of-the-bayesian-workflow" class="level2">
<h2 class="anchored" data-anchor-id="summary-of-the-bayesian-workflow">Summary of the Bayesian Workflow</h2>
<p>Wow, we covered a lot of ground today. Let’s summarize the key points.</p>
<p>The Bayesian Analysis Workflow has three major steps:</p>
<ol type="1">
<li>Modeling
<ul>
<li>We build a <em>generative model</em> that describes the relationships among key variables and unknown parameters to represent the data generating process.</li>
<li>We encode our prior knowledge about the relative plausibility of different parameter values in the <em>prior distribution</em> of the parameters.</li>
<li>We can use <em>prior predictive checks</em> to simulate outcome data from the generative model to sanity check our modeling assumptions.</li>
</ul></li>
<li>Inference
<ul>
<li>Based on our modeling assumptions, we can use observed data to infer the <em>posterior distribution</em>, which quantifies the relative plausibility of different values of the unknown parameters after observing data.</li>
<li>We can view simulations from the generative model as sampling from the joint distribution of data and parameters, and we can view the posterior as the result of conditioning the joint distribution on the data we actually observed.</li>
<li>We can do inference by using sampling-based inference algorithms like rejection sampling, which uses logic on top of our generative model to isolate samples from the posterior distribution.</li>
</ul></li>
<li>Interpretation
<ul>
<li>After inference we can use data analysis tools to summarize the samples from the posterior distribution to compute point estimates, intervals, and probabilities of interest.</li>
<li>If we simulate data from our generative model using the posterior rather than the prior, we get samples from the <em>posterior predictive </em>distribution, which predicts future outcomes given observed data.</li>
<li>Again, we can analyze these posterior predictive samples to compute point estimates, intervals, or probabilities of future outcomes.</li>
</ul></li>
</ol>
<p>Phew! Hopefully that’s a helpful introduction to the Bayesian workflow and the major ideas behind it. The techniques we looked at here are mostly for pedagogical purposes; if you want to apply Bayesian methods to practical problems, you’ll want to use a probabilistic programming language like PyMC, pyro, or stan. Maybe we’ll get into some of those tools in future posts. See you then!</p>
<section id="resources" class="level3">
<h3 class="anchored" data-anchor-id="resources">Resources</h3>
<ul>
<li><a href="https://xcelab.net/rm/">Statistical Rethinking</a> - This page links to where you can obtain the book and also to a number of repos where folks have ported the R and Stan code examples to python libraries like PyMC and pyro.</li>
</ul>
</section>
<section id="reader-exercises" class="level3">
<h3 class="anchored" data-anchor-id="reader-exercises">Reader Exercises</h3>
<p>You didn’t think you’d get away without homework did you? Here are a couple suggestions for exercises.</p>
<ul>
<li>compute the posterior predictive distribution <img src="https://latex.codecogs.com/png.latex?p(y_%7B%5Ctext%7Bnew%7D%7D%7Cy_%7B%5Ctext%7Bobs%7D%7D)"> for the RPS example using grid approximation.</li>
<li>Suppose that each RPS match was played as best out of three. Rewrite the generative model to generate both sub-match and match outcomes. Do inference with rejection sampling. Use your model to find the probability that Fritz wins his next match by winning two submatches in a row.</li>
</ul>


</section>
</section>

 ]]></description>
  <category>bayesian</category>
  <category>python</category>
  <guid>https://randomrealizations.com/posts/bayesian-modeling-primer/</guid>
  <pubDate>Wed, 04 Jun 2025 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/bayesian-modeling-primer/hist.png" medium="image" type="image/png" height="107" width="144"/>
</item>
<item>
  <title>Analyzing After Tax Retirement Income: Roth vs. Traditional 401(k)</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/traditional-vs-roth-401k/</link>
  <description><![CDATA[ 





<p>Today we’re taking a break from our typical hard hitting algorithm deep dives for a quick foray into the world of personal finance. We’ll take on a question I recently encountered while setting up my retirement account with my new employer—which is more efficient, the traditional 401(k) or the Roth 401(k)? US-based readers will recognize these as the two main types of employer-sponsored retirement accounts. When I searched for traditional vs Roth 401(k), the articles I found gave only very hand-wavy guidance on which is better in a given situation. So, today I’ll share my quantitative analysis of which account type provides superior performance for a given set of personal circumstances. We’ll implement the analysis in python, so you can run the numbers for your own situation and determine which employer-sponsored account type is better for you.</p>
<section id="traditional-401k-vs-roth-401k" class="level2">
<h2 class="anchored" data-anchor-id="traditional-401k-vs-roth-401k">Traditional 401(k) vs Roth 401(k)</h2>
<p>I’ll let JLCollins explain the <a href="https://jlcollinsnh.com/2015/06/02/stocks-part-viii-the-401k-403b-tsp-ira-roth-buckets/">background on 401(k)s</a>; read that post first if you’re not already familiar with the concepts of taxable accounts, IRAs, 401(k)s, and the basic rules of Roth vs traditional. The key distinction is * In a traditional 401(k), money you contribute now is deducted from your taxable income, meaning you’ll pay less in income tax now. During retirement however, withdrawals from the account will count toward your taxable income, so you’ll pay tax then. * In a Roth 401(k), money you contribute now does count toward your taxable income, meaning you’ll pay income tax on any contributions now. During retirement however, withdrawals do not count toward your taxable income and are therefore tax free.</p>
<p>Essentially you can either pay tax now (Roth) or pay tax later (traditional). The hand-wavy advice points out that which account is better for you depends on your income tax rate now versus your income tax rate during retirement. High tax rate now and low tax rate during retirement could favor traditional, while low tax rate now and high tax rate during retirement could favor Roth. Let’s put some numbers on this advice.</p>
<p>I’ll assume that you’re following the <a href="https://www.mrmoneymustache.com/2011/04/10/post-4-what-am-i-supposed-to-do-with-all-this-money/">sage advice of Mr.&nbsp;Money Mustache</a> and (after paying off any high-interest debt) maxing out your 401(k) contribution for the year. In 2024, the IRS has set a maximum combined contribution of $23,000; i.e.&nbsp;the sum of your Roth and traditional contributions cannot exceed this limit. Also, once you contribute to these accounts, you may not begin withdrawals (without penalty) until the age of 59.5.</p>
</section>
<section id="analysis-formulation" class="level2">
<h2 class="anchored" data-anchor-id="analysis-formulation">Analysis Formulation</h2>
<p>Let’s state the question precisely—which account type will yield me the most money during retirement after withdrawal and after all taxes are paid? Let’s think through the Roth vs traditional scenarios, setting aside the same amount of money today and liquidating the entire account at retirement; we’ll compare how much money we have at retirement after liquidating and settling any tax obligations.</p>
<p><strong>Roth</strong>: I contribute <code>contribution = 23_000</code> now, plus I pay income tax on this contribution in the amount of <code>current_income_tax_rate * contribution</code>. Over the years from now to retirement <code>retirement_age - current_age</code>, my contribution grows at some average long term yearly rate <code>investment_growth_rate</code>. At retirement, I liquidate the entire account, paying no income tax on the proceeds.</p>
<p><strong>Traditional</strong>: I contribute <code>contribution = 23_000</code> now. For fair comparison with the Roth, I invest an additional amount <code>current_income_tax_rate * contribution</code> (the extra income tax I would have paid had I chosen the Roth) in a normal taxable investment account as well. Over the time from now to retirement, the 401(k) and the taxable account both grow at the average long term rate <code>investment_growth_rate</code>. However, in the taxable account, I’ll also need to pay income tax every year on any dividends that I earn; the S&amp;P500 has recently paid out 1.5-2% in dividends each year, let’s call it <code>dividend_rate</code>. At retirement, I liquidate both accounts, paying income tax on the proceeds from the 401(k) at the rate of <code>retirement_income_tax_rate</code> and paying capital gains tax on the proceeds from the taxable account at the rate of <code>retirement_capital_gains_tax_rate</code>.</p>
<p>Let’s code up a function that takes in all our parameters and returns the total liquidation value after taxes of the Roth versus traditional 401(k)s as described above.</p>
<div id="cell-4" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np </span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd </span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt </span></code></pre></div></div>
</div>
<div id="cell-5" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_401k_liquidation_value(</span>
<span id="cb2-2">    current_age <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">37</span>,</span>
<span id="cb2-3">    current_income_tax_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span>,</span>
<span id="cb2-4">    contribution <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">23_000</span>,</span>
<span id="cb2-5">    retirement_age <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">59.5</span>,</span>
<span id="cb2-6">     investment_growth_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.07</span>,</span>
<span id="cb2-7">     dividend_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.02</span>,</span>
<span id="cb2-8">    retirement_income_tax_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.24</span>,</span>
<span id="cb2-9">    retirement_capital_gains_tax_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 0%, 15%, 20%</span></span>
<span id="cb2-10">):</span>
<span id="cb2-11"></span>
<span id="cb2-12">    investment_growth_factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> investment_growth_rate) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> (retirement_age <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> current_age)</span>
<span id="cb2-13">    dividend_income_tax_drag_factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> dividend_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> current_income_tax_rate) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> (retirement_age <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> current_age)</span>
<span id="cb2-14"></span>
<span id="cb2-15">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Roth 401k</span></span>
<span id="cb2-16">    roth_401k_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> contribution </span>
<span id="cb2-17">    roth_401k_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> investment_growth_factor</span>
<span id="cb2-18">    total_roth_401k_liquidation_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> roth_401k_value</span>
<span id="cb2-19">    </span>
<span id="cb2-20">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># traditional  401k</span></span>
<span id="cb2-21">    traditional_401k_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> contribution </span>
<span id="cb2-22">    taxable_account_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> current_income_tax_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> contribution </span>
<span id="cb2-23">    traditional_401k_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> investment_growth_factor</span>
<span id="cb2-24">    taxable_account_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> investment_growth_factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dividend_income_tax_drag_factor</span>
<span id="cb2-25">    traditional_401k_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> retirement_income_tax_rate)</span>
<span id="cb2-26">    taxable_account_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> retirement_capital_gains_tax_rate)</span>
<span id="cb2-27">    total_traditional_401k_liquidation_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> traditional_401k_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> taxable_account_value</span>
<span id="cb2-28"></span>
<span id="cb2-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {</span>
<span id="cb2-30">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'traditional'</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(total_traditional_401k_liquidation_value), </span>
<span id="cb2-31">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'roth'</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(total_roth_401k_liquidation_value)</span>
<span id="cb2-32">    }</span></code></pre></div></div>
</div>
<div id="cell-6" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">get_401k_liquidation_value()</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="3">
<pre><code>{'traditional': 106882, 'roth': 105405}</code></pre>
</div>
</div>
<p>Somehow it’s not surprising that these two options seem to yield very similar after-tax performance—no arbitrage right?</p>
<p>Let’s write a function to perturb some of our parameter values to see under what conditions one option dominates the other.</p>
<div id="cell-8" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_liquidation_value_by_parameter_values(param, grid_values, func<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>get_401k_liquidation_value):</span>
<span id="cb5-2">    y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [func(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>{param: x}) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> grid_values]</span>
<span id="cb5-3">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(y, index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pd.Series(grid_values, name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>param))</span>
<span id="cb5-4">    fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb5-5">    df.plot(ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb5-6">    plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'liquidation value'</span>)</span>
<span id="cb5-7">    plt.title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Liquidation Value at Retirement by </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>param<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb5-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> fig, ax</span></code></pre></div></div>
</div>
<section id="income-tax-rate-at-retirement" class="level3">
<h3 class="anchored" data-anchor-id="income-tax-rate-at-retirement">Income Tax Rate at Retirement</h3>
<p>It seems that income tax rate at retirement is by far the most important determining factor in whether traditional or Roth 401(k) is a better option.</p>
<div id="cell-10" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">plot_liquidation_value_by_parameter_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'retirement_income_tax_rate'</span>, np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.38</span>, num<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/traditional-vs-roth-401k/401k_files/figure-html/cell-6-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>So given the other parameters I’ve set, Roth outperforms traditional when our income tax rate in retirement exceeds about 25%. <a href="https://www.irs.gov/filing/federal-income-tax-rates-and-brackets">According to the IRS</a> in 2023, an individual tax payer is in the 24% bracket if their income is between about $95k and $180k. So, how much income do you expect to pull in retirement? If we’re really building FIRE wealth, the kind indicated by Mr.&nbsp;Money Mustache and JLCollins, our income in retirement could easily exceed $180k, which would push us into the 32% bracket where Roth is more efficient than traditional.</p>
</section>
<section id="capital-gains-tax-rate-at-retirement" class="level3">
<h3 class="anchored" data-anchor-id="capital-gains-tax-rate-at-retirement">Capital Gains Tax Rate at Retirement</h3>
<div id="cell-13" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">plot_liquidation_value_by_parameter_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'retirement_capital_gains_tax_rate'</span>, np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.20</span>, num<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/traditional-vs-roth-401k/401k_files/figure-html/cell-7-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>In 2023, <a href="https://www.irs.gov/filing/federal-income-tax-rates-and-brackets">according to the IRS</a> as a single tax payer, if your income is between $44k and $492k, you’ll pay 15% capital gains. Over $492k you’ll jump up to 20% where Roth dominates traditional.</p>
</section>
<section id="retirement-age" class="level3">
<h3 class="anchored" data-anchor-id="retirement-age">Retirement Age</h3>
<div id="cell-16" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">plot_liquidation_value_by_parameter_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'retirement_age'</span>, np.linspace(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">59.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">75</span>, num<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/traditional-vs-roth-401k/401k_files/figure-html/cell-8-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>For retirement ages beyond 59.5, traditional’s edge over Roth grows slightly.</p>
</section>
</section>
<section id="bottom-line" class="level2">
<h2 class="anchored" data-anchor-id="bottom-line">Bottom Line</h2>
<p>When I plugged in my actual parameters, I found that because I was only employed for 6 months last year, my current income tax rate pushed me into the regime where Roth performs better than traditional. However for this next year, I expect to be in a higher income tax bracket where traditional will be a better deal than Roth.</p>
<p>That said, the most important factor is your income tax rate at the time of withdrawal during retirement, which is based on your taxable income at that time. But how, I hear you asking, am I supposed to know what to plug in for my post-retirement income? That quantity is unknown. This illuminates the fundamental limitation of this kind of analysis—what to do about uncertain inputs to the calculation? That’s a question that we might take on in a future post, so stay tuned!</p>


</section>

 ]]></description>
  <category>personal finance</category>
  <guid>https://randomrealizations.com/posts/traditional-vs-roth-401k/</guid>
  <pubDate>Sat, 14 Dec 2024 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/enso-thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>SHAP from Scratch</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/shap-from-scratch/</link>
  <description><![CDATA[ 





<p>Ahh, SHAP. As you know it’s become one of the leading frameworks for explaining ML model predictions. I’d guess it’s popularity is due to its appealing theoretical basis, its universal applicability to any type of ML model, and its easy-to-use python package. SHAP promises to turn your black box ML model into a nice friendly interpretable model. The hilarious irony is that, when I first started using it in my work, SHAP itself was a complete black box to me. In this post, we’ll change all that by diving into the SHAP paper, illuminating the key theoretical ideas behind its development step by step, and implementing it from scratch in python. If you aren’t already familiar with how to compute and interpret SHAP values in practice, I’d recommend that you go check out the <a href="https://shap.readthedocs.io/en/latest/index.html">documentation for the shap python package</a> before diving into this post.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/shap-from-scratch/shap_from_scratch_main.jpg" class="img-fluid figure-img"></p>
<figcaption>Snow, trees, and mountains overlook Lake Tahoe.</figcaption>
</figure>
</div>
<section id="what-is-shap" class="level2">
<h2 class="anchored" data-anchor-id="what-is-shap">What is SHAP?</h2>
<p>SHAP (SHapley Additive exPlanations) is a conceptual framework for creating explanations of ML model predictions. The term also refers to a set of computational methods for generating these explanations and a python library which implements them. The “SHAP” <a href="https://en.wikipedia.org/wiki/Backronym">backronym</a> was introduced in <a href="https://arxiv.org/abs/1705.07874">Lundberg and Lee 2017</a>, which I call the <em>SHAP paper</em>, that expanded on several previously existing ideas which we’ll build up in the following sections. The key concepts are:</p>
<ul>
<li><em>Shapley values</em>, a concept from cooperative game theory which originally had nothing to do with machine learning</li>
<li><em>Shapley regression values</em>, which showed how to use Shapley values to generate explanations of model predictions</li>
<li><em>Shapley sampling values</em>, which offered a computationally tractable way to compute Shapley regression values for any type of model.</li>
</ul>
<p>The SHAP paper tied Shapley regression values and several other existing model explanation methods together by showing they are all members of a class called “additive feature attribution methods.” Under the right conditions, these additive feature attribution methods can generate Shapley values, and when they do we can call them SHAP values.</p>
<p>After establishing this theoretical framework, the authors go on to discuss various computational methods for computing SHAP values; some are model-agnostic, meaning they work with any type of model, and others are model-specific, meaning they work for specific types of models. It turns out that the previously existing Shapley sampling values method is a model-agnostic approach, but while it’s the most intuitive, computationally speaking it’s relatively inefficient. Thus the authors propose a novel model-agnostic approach called Kernel SHAP, which is really just <a href="https://lime-ml.readthedocs.io/en/latest/">LIME</a> parameterized to yield SHAP values.</p>
<p>Model-specific approaches can be potentially much more efficient than model-agnostic ones by taking advantage of model idiosyncrasies. For example, there is an analytical solution for the SHAP values of linear models, so Linear SHAP is extremely efficient. Similarly, Deep SHAP (proposed in the SHAP paper) and Tree SHAP (proposed later in <a href="https://www.sciencedirect.com/science/article/pii/S2666827022000500#b20">Lundberg et al 2020</a>) take advantage of idiosyncrasies of deep learning and tree-based models to compute SHAP values efficiently.</p>
<p>The important thing about these different methods is that they provide computationally tractable ways to compute SHAP values, but ultimately, they are all based on the Shapley sampling values method—the original method to compute what we now call SHAP values. Thus, for the remainder of this post, we’ll focus on this method, building it up from Shapley values to Shapley regression values to Shapley sampling values and ultimately implementing it from scratch in python.</p>
</section>
<section id="shapley-values" class="level2">
<h2 class="anchored" data-anchor-id="shapley-values">Shapley Values</h2>
<p>The <a href="https://en.wikipedia.org/wiki/Shapley_value">Shapley value</a> is named in honor of Nobel prize winning economist Loyd Shapley who introduced the idea in the field of coalitional game theory in the 1950’s. Shapley proposed a way to determine how a coalition of players can fairly share the payout they receive from a cooperative game. We’ll introduce the mathematical formalism in the next section, so for now let’s just touch on the intuition for the approach. Essentially, the method distributes the payout among the players according to the expected contribution of each player across all possible combinations of the players. The thought experiment works as follows:</p>
<ol type="1">
<li>Draw a random permutation (ordering) of the players.</li>
<li>Have the first player play alone, generating some payout. Then have the first two players play together, generating some payout. Then the first three, and so on.</li>
<li>As each new player is added, attribute the change in the payout to this new player.</li>
<li>Repeat this experiment for all permutations of the players. A player’s Shapley value is the average change in payout (across all permutations) when that player is added to the game.</li>
</ol>
<p>Next we’ll see how this idea can be applied to model explanations.</p>
</section>
<section id="shapley-regression-values" class="level2">
<h2 class="anchored" data-anchor-id="shapley-regression-values">Shapley Regression Values</h2>
<p>The next idea came from <a href="https://onlinelibrary.wiley.com/doi/abs/10.1002/asmb.446">Lipovetsky and Conklin 2001</a>, who proposed a way to use Shapley values to explain the predictions of a linear regression model. <em>Shapley regression values</em> assign an importance value to each feature that represents the effect on the model prediction of including that feature. The basic idea is to train a second model without the feature of interest, and then to compare the predictions from the model with the feature and the model without the feature. This procedure of training two models and comparing their predictions is repeated for all possible subsets of the other features; the average difference in predictions is the Shapley value for the feature of interest.</p>
<p>The Shapley value for feature <img src="https://latex.codecogs.com/png.latex?i"> on instance <img src="https://latex.codecogs.com/png.latex?x"> is given by equation 4 in the SHAP paper:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cphi_i%20=%20%5Csum_%7BS%20%5Csubseteq%20F%20%5Csetminus%20%5C%7Bi%5C%7D%7D%0A%5Cfrac%7B%7CS%7C!(%7CF%7C%20-%20%7CS%7C%20-%201)!%7D%7B%7CF%7C!%7D%0A%5Bf_%7BS%20%5Ccup%20%5C%7Bi%5C%7D%7D(x_%7BS%20%5Ccup%20%5C%7Bi%5C%7D%7D)%20-%20f_S(x_S)%20%5D%0A"></p>
<p>where</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Cphi_i"> is the Shapley value for feature of interest <img src="https://latex.codecogs.com/png.latex?i">,</li>
<li>the <img src="https://latex.codecogs.com/png.latex?%5Csubseteq"> symbol indicates the item on its left is a subset of the object on its right,</li>
<li><img src="https://latex.codecogs.com/png.latex?F"> is the set of all features,</li>
<li>the vertical bars indicate the number of elements in a set, e.g.&nbsp;<img src="https://latex.codecogs.com/png.latex?%7CF%7C"> is the total number of features,</li>
<li><img src="https://latex.codecogs.com/png.latex?F%20%5Csetminus%20%5C%7Bi%5C%7D"> is the set of all features except the feature of interest,</li>
<li><img src="https://latex.codecogs.com/png.latex?S"> is a particular subset of features not including the feature of interest,</li>
<li><img src="https://latex.codecogs.com/png.latex?f_%7BS%7D"> is a “subset model”—a model that uses only the features in <img src="https://latex.codecogs.com/png.latex?S"> for both training and prediction,</li>
<li>and <img src="https://latex.codecogs.com/png.latex?f_%7BS%20%5Ccup%20%5C%7Bi%5C%7D%7D"> is asubset model using features in <img src="https://latex.codecogs.com/png.latex?S"> and the feature of interest.</li>
</ul>
<p>To reiterate, this is the most important equation when it comes to understanding SHAP, as it defines the Shapley value; let’s make sure we understand what’s going on by implementing it in python.</p>
<p>We start with the feature subsets. Notice that the sum is indexed over all subsets of <img src="https://latex.codecogs.com/png.latex?F%20%5Csetminus%20%5C%7Bi%5C%7D">, which is the set of all features except the <img src="https://latex.codecogs.com/png.latex?i">th feature, the one we’re calculating the Shapley value for. Let’s write a function that takes a list of items and returns an iterable that yields all possible subsets of those items.</p>
<div id="cell-7" class="cell" data-execution_count="43">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> itertools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> chain, combinations </span>
<span id="cb1-2"></span>
<span id="cb1-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_all_subsets(items):</span>
<span id="cb1-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> chain.from_iterable(combinations(items, r) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(items)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb1-5"></span>
<span id="cb1-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span>  get_all_subsets([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]):</span>
<span id="cb1-7">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(s)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>()
(0,)
(1,)
(2,)
(0, 1)
(0, 2)
(1, 2)
(0, 1, 2)</code></pre>
</div>
</div>
<p>To get all subsets of features, other than the feature of interest, we could do something like this.</p>
<div id="cell-9" class="cell" data-execution_count="56">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_all_other_feature_subsets(n_features, feature_of_interest):</span>
<span id="cb3-2">    all_other_features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n_features) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> j <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> feature_of_interest]</span>
<span id="cb3-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> get_all_subsets(all_other_features)</span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> get_all_other_feature_subsets(n_features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, feature_of_interest<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>):</span>
<span id="cb3-6">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(s)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>()
(0,)
(1,)
(3,)
(0, 1)
(0, 3)
(1, 3)
(0, 1, 3)</code></pre>
</div>
</div>
<p>So for each of the feature subsets, we’ll need to calculate the summand, which is the product of a quotient with a bunch of factorials and the difference in predicted values between two subset models. Let’s start with those subset models. Subset model <img src="https://latex.codecogs.com/png.latex?f_%7BS%7D"> is a model trained only on the features in subset <img src="https://latex.codecogs.com/png.latex?S">. We can write a function that takes an untrained model, a training dataset, a feature subset to use, and a single instance to predict on; the function will then train a model using only features in the subset, and it will issue a prediction for the single instance we gave it.</p>
<div id="cell-11" class="cell" data-execution_count="44">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> subset_model(model, X_train, y_train, feature_subset, instance):</span>
<span id="cb5-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(instance.shape) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Instance must be a 1D array'</span></span>
<span id="cb5-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(feature_subset) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb5-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y.mean() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a model with no features predicts E[y]</span></span>
<span id="cb5-5">    X_subset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train.take(feature_subset, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-6">    model.fit(X_subset, y_train)</span>
<span id="cb5-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> model.predict(instance.take(feature_subset).reshape(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span></code></pre></div></div>
</div>
<p>Next let’s have a look at <img src="https://latex.codecogs.com/png.latex?%7CS%7C!(%7CF%7C-%7CS%7C-1)!/%7CF%7C!">. The keen reader will notice this factor kind of looks like the answers to those combinatorics questions like how many unique ways can you order the letters in the word MISSISSIPPI. The combinatorics connection is that Shapley values are defined in terms of all permutations of the players , where the included players come first, then the player of interest, followed by the excluded players. In ML models, the order of features doesn’t matter, so we can work with unordered subsets of features, scaling the prediction difference terms by the number of permutations that involve the same sets of included and excluded features. With that in mind, we can see that including the factor in each term of the sum gives us a weighted average over all feature combinations, where the numerator gives the number of permutations in which the included features come first, followed by the feature of interest, followed by the excluded features, and the denominator is the total number of feature permutations.</p>
<div id="cell-13" class="cell" data-execution_count="37">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> math <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> factorial</span>
<span id="cb6-2"></span>
<span id="cb6-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> permutation_factor(n_features, n_subset):</span>
<span id="cb6-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> factorial(n_subset) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> factorial(n_features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_subset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> factorial(n_features)</span></code></pre></div></div>
</div>
<p>Now we can put these pieces together to compute equation 4—a single Shapley regression value for a single instance and feature of interest.</p>
<div id="cell-15" class="cell" data-execution_count="59">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compute_single_shap_value(untrained_model,</span>
<span id="cb7-2">                              X_train,</span>
<span id="cb7-3">                              y_train,</span>
<span id="cb7-4">                              feature_of_interest,</span>
<span id="cb7-5">                              instance):</span>
<span id="cb7-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"Compute a single SHAP value (equation 4)"</span></span>
<span id="cb7-7">    n_features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb7-8">    shap_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb7-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> subset <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> get_all_other_feature_subsets(n_features, feature_of_interest):</span>
<span id="cb7-10">        n_subset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(subset)</span>
<span id="cb7-11">        prediction_without_feature <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> subset_model(</span>
<span id="cb7-12">            untrained_model,</span>
<span id="cb7-13">            X_train, y_train,</span>
<span id="cb7-14">            subset,</span>
<span id="cb7-15">            instance</span>
<span id="cb7-16">        )</span>
<span id="cb7-17">        prediction_with_feature <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> subset_model(</span>
<span id="cb7-18">            untrained_model,</span>
<span id="cb7-19">            X_train, y_train,</span>
<span id="cb7-20">            subset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (feature_of_interest,),</span>
<span id="cb7-21">            instance</span>
<span id="cb7-22">        )</span>
<span id="cb7-23">        factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> permutation_factor(n_features, n_subset)</span>
<span id="cb7-24">        shap_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (prediction_with_feature <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> prediction_without_feature)</span>
<span id="cb7-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> shap_value</span></code></pre></div></div>
</div>
<p>Let’s use this function to compute a single Shapley regression value for a linear model and a small training dataset with 3 features.</p>
<div id="cell-17" class="cell" data-execution_count="60">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_regression </span>
<span id="cb8-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.linear_model <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LinearRegression </span>
<span id="cb8-3"></span>
<span id="cb8-4">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_regression(n_samples<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, n_features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb8-5"></span>
<span id="cb8-6">compute_single_shap_value(untrained_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>LinearRegression(),</span>
<span id="cb8-7">                          X_train<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X, y_train<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y,</span>
<span id="cb8-8">                          feature_of_interest<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb8-9">                          instance<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, :])</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="60">
<pre><code>-0.07477140629329351</code></pre>
</div>
</div>
<p>That gives us a single Shapley value corresponding to a single feature value in a single instance. To get useful model explanations, we’d need to compute Shapley values for each feature of each instance in some dataset of instances. You might notice there’s a big problem with the formulation above. Namely, we are going to have to train a whole bunch of new subset models—one for each subset of the features. If our model has <img src="https://latex.codecogs.com/png.latex?M"> features, we’ll have to train <img src="https://latex.codecogs.com/png.latex?2%5EM"> models, so this will get impractical in a hurry, especially if we’re trying to train anything other than linear models.</p>
</section>
<section id="shapley-sampling-values" class="level2">
<h2 class="anchored" data-anchor-id="shapley-sampling-values">Shapley Sampling Values</h2>
<p>Next, <a href="https://link.springer.com/article/10.1007/s10115-013-0679-x">Štrumbelj and Kononenko 2014</a> proposed <em>Shapley sampling values</em>, a method which provides a much more efficient way to approximate the subset models used to calculate Shapley regression values. In this approach, the effect of removing some features from the model is approximated by the conditional expectation of the model given the known features.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20f_S(x_S)%20%20:=%20E%5Bf(x)%20%7C%20x_S%5D%20%20"></p>
<p>This means we’re approximating the output of a subset model by averaging over outputs of the full model. That’s great because now we don’t have to train all those new subset models, we can just query our full model over some set of inputs and average over the outputs to compute these conditional expectation subset models.</p>
<p>Now how exactly do we compute that conditional expectation? First we rewrite the above conditional expectation (equation 10 in the SHAP paper)</p>
<p><img src="https://latex.codecogs.com/png.latex?%20E%5Bf(x)%20%7C%20x_S%5D%20%20=%20E_%7Bx_%7B%5Cbar%7BS%7D%7D%7Cx_S%7D%20%5Bf(x)%5D"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cbar%7BS%7D"> is the set of excluded or missing features. Beside this equation in the paper they give the note “expectation over <img src="https://latex.codecogs.com/png.latex?x_%7B%5Cbar%7BS%7D%7D%20%7C%20x_S">, which means we’re taking the expectation over the missing features given the known features. Then we get another step (equation 11)</p>
<p><img src="https://latex.codecogs.com/png.latex?E_%7Bx_%7B%5Cbar%7BS%7D%7D%7Cx_S%7D%20%5Bf(x)%5D%20%5Capprox%20E_%7Bx_%7B%5Cbar%7BS%7D%7D%7D%20%5Bf(x)%5D"></p>
<p>Now it’s not an equality but an approximation. The authors give the note “assume feature independence”. The intuition here is that if the missing features are correlated with the known features, then their distribution depends on the particular values taken by the known features. But here the authors make the simplifying assumption that known and missing features are independent, which allows us to replace the conditional expectation with an unconditional expectation over the missing features.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>So is this assumption that features in <img src="https://latex.codecogs.com/png.latex?S"> are independent from features in <img src="https://latex.codecogs.com/png.latex?%5Cbar%7BS%7D"> a problem? The short answer is… maybe 🤷‍♀️? It’s potentially problematic enough that people have worked out some ways to relax this assumption, e.g.&nbsp;<a href="https://shap-lrjball.readthedocs.io/en/latest/generated/shap.PartitionExplainer.html">partition masking</a>, but that makes <em>Owen values</em> instead of Shapley values, so we’ll save it for another post.</p>
</div>
</div>
<p>Anyway, how do we compute this unconditional expectation over the missing features in practice? We’ll need to use a so-called <em>background dataset</em>, which is just some set of observations of our feature variables that represents their distribution. A good candidate is the training data we used to train our model. Štrumbelj and Kononenko 2014 propose a way to estimate this conditional expectation using resampling of the background dataset.</p>
<p>The idea is to notice that the instance of interest <img src="https://latex.codecogs.com/png.latex?x"> is a feature vector comprised of the set of “known” features <img src="https://latex.codecogs.com/png.latex?x_S"> and the set of excluded features <img src="https://latex.codecogs.com/png.latex?x_%7B%5Cbar%7BS%7D%7D"> such that <img src="https://latex.codecogs.com/png.latex?x=%5C%7Bx_S,x_%7B%5Cbar%7BS%7D%7D%20%5C%7D">. Our resampling scheme will be based on constructing “masked” samples <img src="https://latex.codecogs.com/png.latex?x%5E*=%5C%7Bx_S,z_%7B%5Cbar%7BS%7D%7D%20%5C%7D"> where <img src="https://latex.codecogs.com/png.latex?z_%7B%5Cbar%7BS%7D%7D"> are values of the missing features drawn from some random observation in the background dataset. We can then compute an estimate <img src="https://latex.codecogs.com/png.latex?%5Chat%7Bf%7D_S(x)"> of the conditional expectation <img src="https://latex.codecogs.com/png.latex?E_%7Bx_%7B%5Cbar%7BS%7D%7D%7D%5Bf(x)%5D"> as</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7Bf%7D_S(x)%20=%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bk=1%7D%5En%20f(%5C%7Bx_S,%20z_%7B%5Cbar%7BS%7D%7D%5E%7B(k)%7D%20%5C%7D)%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?z_%7B%5Cbar%7BS%7D%7D%5E%7B(k)%7D"> is the vector of values of the excluded features from the <img src="https://latex.codecogs.com/png.latex?k">-th row of the background dataset. Algorithmically, we can view this as first drawing a sample of observations from the background dataset, second “masking” features in <img src="https://latex.codecogs.com/png.latex?S"> in the sampled background dataset by replacing the observed values <img src="https://latex.codecogs.com/png.latex?z_S"> on each row with the values in the instance <img src="https://latex.codecogs.com/png.latex?x_S">, third using the full model <img src="https://latex.codecogs.com/png.latex?f"> to predict on each of these masked samples in the background dataset, and finally averaging over these predictions. We can implement a new subset model function that takes a fully trained model, a background dataset,a feature subset, and an instance for explanation and returns an approximation of the subset model prediction.</p>
<div id="cell-21" class="cell" data-execution_count="62">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb10-2"></span>
<span id="cb10-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> subset_model_approximation(trained_model, </span>
<span id="cb10-4">                               background_dataset,</span>
<span id="cb10-5">                               feature_subset,  </span>
<span id="cb10-6">                               instance):</span>
<span id="cb10-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">""" </span></span>
<span id="cb10-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Approximate subset model prediction  (Equation 11)</span></span>
<span id="cb10-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    </span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">hat{f}_S(x) = E_{x_{</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">hat{S</span><span class="re">}}}</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[f_S(x)]</span></span>
<span id="cb10-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    for feature subset S on single instance x</span></span>
<span id="cb10-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb10-12">    masked_background_dataset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> background_dataset.copy()</span>
<span id="cb10-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(masked_background_dataset.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]):</span>
<span id="cb10-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> feature_subset:</span>
<span id="cb10-15">            masked_background_dataset[:, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> instance[j]</span>
<span id="cb10-16">    conditional_expectation_of_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.mean(</span>
<span id="cb10-17">        trained_model.predict(masked_background_dataset)</span>
<span id="cb10-18">    )</span>
<span id="cb10-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> conditional_expectation_of_model          </span></code></pre></div></div>
</div>
<p>If we replace our <code>subset_model</code> function with this new <code>subset_model_approximation</code> function in our <code>compute_single_shap_value</code> function from earlier, then we’ll be computing Shapley sampling values. And according to the SHAP paper: “if we assume feature independence when approximating conditional expectations (using Equation 11 to estimate subset model output) … then SHAP values can be estimated directly using the Shapley sampling values method.” That means we’ll be computing SHAP values!</p>
</section>
<section id="how-to-implement-shap-from-scratch" class="level2">
<h2 class="anchored" data-anchor-id="how-to-implement-shap-from-scratch">How to Implement SHAP from Scratch</h2>
<p>Let’s put the pieces together and implement a class for a model explainer that computes SHAP values via the Shapley sampling values method. We’ll talk through a couple of points after the code.</p>
<div id="cell-24" class="cell" data-execution_count="80">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np </span>
<span id="cb11-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Any, Callable, Iterable</span>
<span id="cb11-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> math <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> factorial</span>
<span id="cb11-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> itertools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> chain, combinations</span>
<span id="cb11-5"></span>
<span id="cb11-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ShapFromScratchExplainer():</span>
<span id="cb11-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>,</span>
<span id="cb11-8">                 model: Callable[[np.ndarray], <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>], </span>
<span id="cb11-9">                 background_dataset: np.ndarray,</span>
<span id="cb11-10">                 max_samples: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb11-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model</span>
<span id="cb11-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> max_samples:</span>
<span id="cb11-13">            max_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(max_samples, background_dataset.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]) </span>
<span id="cb11-14">            rng <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.default_rng()</span>
<span id="cb11-15">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.background_dataset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rng.choice(background_dataset, </span>
<span id="cb11-16">                                                 size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_samples, </span>
<span id="cb11-17">                                                 replace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb11-19">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.background_dataset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> background_dataset</span>
<span id="cb11-20"></span>
<span id="cb11-21">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> shap_values(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X: np.ndarray) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> np.ndarray:</span>
<span id="cb11-22">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"SHAP Values for instances in DataFrame or 2D array"</span></span>
<span id="cb11-23">        shap_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.empty(X.shape)</span>
<span id="cb11-24">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]):</span>
<span id="cb11-25">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]):</span>
<span id="cb11-26">                shap_values[i, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._compute_single_shap_value(j, X[i, :])</span>
<span id="cb11-27">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> shap_values</span>
<span id="cb11-28">       </span>
<span id="cb11-29">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _compute_single_shap_value(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, </span>
<span id="cb11-30">                                   feature: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb11-31">                                   instance: np.array) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>:</span>
<span id="cb11-32">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"Compute a single SHAP value (equation 4)"</span></span>
<span id="cb11-33">        n_features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(instance)</span>
<span id="cb11-34">        shap_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> subset <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._get_all_other_feature_subsets(n_features, feature):</span>
<span id="cb11-36">            n_subset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(subset)</span>
<span id="cb11-37">            prediction_without_feature <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._subset_model_approximation(</span>
<span id="cb11-38">                subset, </span>
<span id="cb11-39">                instance</span>
<span id="cb11-40">            )</span>
<span id="cb11-41">            prediction_with_feature <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._subset_model_approximation(</span>
<span id="cb11-42">                subset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (feature,), </span>
<span id="cb11-43">                instance</span>
<span id="cb11-44">            )</span>
<span id="cb11-45">            factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._permutation_factor(n_features, n_subset)</span>
<span id="cb11-46">            shap_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> factor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (prediction_with_feature <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> prediction_without_feature)</span>
<span id="cb11-47">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> shap_value</span>
<span id="cb11-48">    </span>
<span id="cb11-49">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _get_all_subsets(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, items: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Iterable:</span>
<span id="cb11-50">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> chain.from_iterable(combinations(items, r) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(items)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb11-51">    </span>
<span id="cb11-52">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _get_all_other_feature_subsets(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, n_features, feature_of_interest):</span>
<span id="cb11-53">        all_other_features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n_features) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> j <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> feature_of_interest]</span>
<span id="cb11-54">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._get_all_subsets(all_other_features)</span>
<span id="cb11-55"></span>
<span id="cb11-56">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _permutation_factor(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, n_features, n_subset):</span>
<span id="cb11-57">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (</span>
<span id="cb11-58">            factorial(n_subset) </span>
<span id="cb11-59">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> factorial(n_features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_subset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) </span>
<span id="cb11-60">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> factorial(n_features) </span>
<span id="cb11-61">        )</span>
<span id="cb11-62">    </span>
<span id="cb11-63">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _subset_model_approximation(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, </span>
<span id="cb11-64">                                    feature_subset: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, ...], </span>
<span id="cb11-65">                                    instance: np.array) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>:</span>
<span id="cb11-66">        masked_background_dataset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.background_dataset.copy()</span>
<span id="cb11-67">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(masked_background_dataset.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]):</span>
<span id="cb11-68">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> feature_subset:</span>
<span id="cb11-69">                masked_background_dataset[:, j] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> instance[j]</span>
<span id="cb11-70">        conditional_expectation_of_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.mean(</span>
<span id="cb11-71">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.model(masked_background_dataset)</span>
<span id="cb11-72">        )</span>
<span id="cb11-73">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> conditional_expectation_of_model          </span></code></pre></div></div>
</div>
<p>The <code>SHAPExplainerFromScratch</code> API is similar to that of the <a href="https://shap-lrjball.readthedocs.io/en/latest/generated/shap.KernelExplainer.html"><code>KernelExplainer</code></a> from the python library, taking two required arguments during instantiation:</p>
<ul>
<li><code>model</code>: “User supplied function that takes a matrix of samples (# samples x # features) and computes the output of the model for those samples.” That means if our model is a scikit-learn model, we’ll need to pass in its predict method, not the model object itself.</li>
<li><code>background_dataset</code>: “The background dataset to use for integrating out features.” We know about this idea from the Shapley sampling values section above; a good choice for this data could be the training dataset we used to fit the model. By default, we’ll use all the rows of this background dataset, but we’ll also implement the ability to sample down to the desired number of rows with an argument called <code>max_samples</code>.</li>
</ul>
<p>Like the <code>KernelExplainer</code>, this class has a method called <code>shap_values</code> which estimates the SHAP values for a set of instances. It takes an argument <code>X</code> which is “a matrix of samples (# samples x # features) on which to explain the model’s output.” This <code>shap_values</code> method just loops through each feature value of each instance of the input samples <code>X</code> and calls an internal method named <code>_compute_single_shap_value</code> to compute each SHAP value. The <code>_compute_single_shap_value</code> method is the real workhorse of the class. It implements equation 4 from the SHAP paper as described in the Shapley regression values section above by calling a few other internal helper methods corresponding to functions that we’ve already written.</p>
</section>
<section id="testing-the-implementation" class="level2">
<h2 class="anchored" data-anchor-id="testing-the-implementation">Testing the Implementation</h2>
<p>Let’s check our work by comparing SHAP values computed by our implementation with those from the SHAP python library. We’ll use our old friend the diabetes dataset, training a linear model, a random forest, and a gradient boosting machine.</p>
<div id="cell-27" class="cell" data-execution_count="73">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> load_diabetes</span>
<span id="cb12-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split</span>
<span id="cb12-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.linear_model <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LinearRegression</span>
<span id="cb12-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.ensemble <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> GradientBoostingRegressor, RandomForestRegressor</span>
<span id="cb12-5"></span>
<span id="cb12-6">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_diabetes(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, return_X_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb12-7">X_train, X_test, y_train, y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(X, y, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, </span>
<span id="cb12-8">                                                    random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb12-9"></span>
<span id="cb12-10">lin_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LinearRegression().fit(X_train, y_train)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb12-11">rfr_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RandomForestRegressor().fit(X_train, y_train)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb12-12">gbt_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingRegressor().fit(X_train, y_train)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</div>
<p>Here’s a little function to compare the SHAP values generated by our implementation and those from the library <code>KernelExplainer</code>.</p>
<div id="cell-29" class="cell" data-execution_count="81">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> shap</span>
<span id="cb13-2"></span>
<span id="cb13-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compare_methods(model, X_background, X_instances):</span>
<span id="cb13-4">        </span>
<span id="cb13-5">    library_explainer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> shap.KernelExplainer(model.predict, X_background)</span>
<span id="cb13-6">    library_shap_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> library_explainer.shap_values(X_instances)</span>
<span id="cb13-7"></span>
<span id="cb13-8">    from_scratch_explainer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ShapFromScratchExplainer(model.predict, X_background)</span>
<span id="cb13-9">    from_scratch_shap_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> from_scratch_explainer.shap_values(X_instances)</span>
<span id="cb13-10"></span>
<span id="cb13-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.allclose(library_shap_values, from_scratch_shap_values)</span></code></pre></div></div>
</div>
<div id="cell-30" class="cell" data-execution_count="82">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">compare_methods(lin_model, </span>
<span id="cb14-2">                X_background<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_train[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, :], </span>
<span id="cb14-3">                X_instances<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_test[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, :])</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<script type="application/vnd.jupyter.widget-view+json">
{"model_id":"995f763174824efebecb5c2522c3f6f5","version_major":2,"version_minor":0,"quarto_mimetype":"application/vnd.jupyter.widget-view+json"}
</script>
</div>
<div class="cell-output cell-output-display" data-execution_count="82">
<pre><code>True</code></pre>
</div>
</div>
<div id="cell-31" class="cell" data-execution_count="77">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1">compare_methods(rfr_model, </span>
<span id="cb16-2">                X_background<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_train[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, :], </span>
<span id="cb16-3">                X_instances<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_test[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, :])</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<script type="application/vnd.jupyter.widget-view+json">
{"model_id":"f9468451774b4c758a7696ff10fabc74","version_major":2,"version_minor":0,"quarto_mimetype":"application/vnd.jupyter.widget-view+json"}
</script>
</div>
<div class="cell-output cell-output-display" data-execution_count="77">
<pre><code>True</code></pre>
</div>
</div>
<div id="cell-32" class="cell" data-execution_count="83">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">compare_methods(gbt_model, </span>
<span id="cb18-2">                X_background<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_train[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, :], </span>
<span id="cb18-3">                X_instances<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_test[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, :])</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<script type="application/vnd.jupyter.widget-view+json">
{"model_id":"8bdea22fab86440db68c4a669beaf7df","version_major":2,"version_minor":0,"quarto_mimetype":"application/vnd.jupyter.widget-view+json"}
</script>
</div>
<div class="cell-output cell-output-display" data-execution_count="83">
<pre><code>True</code></pre>
</div>
</div>
<p>Beautiful! Our Implementation is consistent with the SHAP library explainer!</p>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Well I hope this one was helpful to you. The research phase actually took me a lot longer than I expected; it just took me a while to figure out what SHAP really is and how those different ideas and papers fit together. I thought the implementation itself was pretty fun and relatively easy. What do you think?</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li><a href="https://arxiv.org/abs/1705.07874">The SHAP Paper (Lundberg and Lee, 2017)</a></li>
<li><a href="https://christophm.github.io/interpretable-ml-book/">Interpretable Machine Learning by Christoph Molnar</a></li>
</ul>


</section>

 ]]></description>
  <category>python</category>
  <category>from scratch</category>
  <guid>https://randomrealizations.com/posts/shap-from-scratch/</guid>
  <pubDate>Sun, 04 Aug 2024 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/shap-from-scratch/shap_from_scratch_thumb.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>The Ultimate Guide to XGBoost Parameter Tuning</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/xgboost-parameter-tuning-with-optuna/</link>
  <description><![CDATA[ 





<p>Ahh, the dark art of hyperparameter tuning. It’s a key step in the machine learning workflow, and it’s an activity that can easily be overlooked or be overkill. Therefore, dear reader, it is an art that requires the application of both skill and wisdom to realize its full potential while avoiding its perils. Today I’ll show you my approach for hyperparameter tuning XGBoost, although the principles apply to any GBT framework. I’ll give you some intuition for how to think about the key parameters in XGBoost, and I’ll show you an efficient strategy for parameter tuning GBTs. I’ll be using the optuna python library to tune parameters with bayesian optimization, but you can implement my strategy with whatever hyperparameter tuning utility you like. You can download a notebook with this tuning workflow from my <a href="https://github.com/mcb00/ds-templates">data science templates repository</a>. Finally we’ll wrap up with the kind of cautionary tale data scientists tell their colleagues around the campfire about when all this fancy hyperparameter tuning can backfire catastrophically—ignore at your own peril.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-parameter-tuning-with-optuna/optuna_main.jpg" class="img-fluid figure-img"></p>
<figcaption>Lunar halo on a frosty night in Johnson City, TN</figcaption>
</figure>
</div>
<section id="xgboost-parameters" class="level2">
<h2 class="anchored" data-anchor-id="xgboost-parameters">XGBoost Parameters</h2>
<p>Gradient boosting algorithms like XGBoost have two main types of hyperparameters: <em>tree parameters</em> which control the decision tree trained at each boosting round and <em>boosting parameters</em> which control the boosting procedure itself. Below I’ll highlight my favorite parameters, but you can see the full list in the <a href="https://xgboost.readthedocs.io/en/stable/parameter.html">documentation</a>.</p>
<section id="tree-parameters" class="level3">
<h3 class="anchored" data-anchor-id="tree-parameters">Tree Parameters</h3>
<p>In theory you can use any kind of model as a base learner in a gradient boosting algorithm, but for reasons we discussed before, <a href="../../posts/consider-the-decision-tree/">decision trees</a> are typically the best choice. In XGBoost, we can choose the tree construction algorithm, and we get three types of parameters to control its behavior: tree complexity parameters, sampling parameters, and regularization parameters.</p>
<section id="tree-construction-algorithm" class="level4">
<h4 class="anchored" data-anchor-id="tree-construction-algorithm">Tree construction algorithm</h4>
<p>The tree construction algorithm boils down to split finding, and different algorithms have different ways of generating candidate splits to consider. In XGBoost we have the parameter:</p>
<ul>
<li><code>tree_method</code> - select tree construction algorithm: <code>exact</code>, <code>hist</code>, <code>approx</code>, or the horrifying default—<code>auto</code>—which outsources your choice of tree construction algo to XGBoost and which you should never ever use. I’ve been burned by this hidden <code>tree_method=auto</code> default multiple times before learning my lesson. Why is the online model worse than the offline model? Why is this model suddenly taking so much longer to train? Avoid these debugging nightmares and set <code>tree_method</code> explicitly; the exact method tends to be slow and ironically less accurate, so I use either approx or hist.</li>
</ul>
</section>
<section id="tree-complexity-parameters" class="level4">
<h4 class="anchored" data-anchor-id="tree-complexity-parameters">Tree complexity parameters</h4>
<p>Tree complexity just means how many leaf nodes the trees have, and therefore how expressive they can be. I use these two parameters:</p>
<ul>
<li><code>max_depth</code> - maximum number of split levels allowed. Reasonable values are usually from 3-12.</li>
<li><code>min_child_weight</code> - minimum allowable sum of hessian values over data in a node. When using the default squared error objective, this is the minimum number of samples allowed in a leaf node (see <a href="https://stats.stackexchange.com/questions/317073/explanation-of-min-child-weight-in-xgboost-algorithm">this explanation</a> of why that’s true). For a squared error objective, values in [1, 200] usually work well.</li>
</ul>
<p>These two parameters oppose each other; increasing max depth allows for more expressive trees, while increasing min child weight makes trees less expressive and therefore is a powerful way to counter overfitting. Note that <code>gamma</code> (a.k.a. <code>min_split_loss</code>) also limits node splitting, but I usually don’t use it because <code>min_child_weight</code> seems to work well enough on its own.</p>
</section>
<section id="sampling-parameters" class="level4">
<h4 class="anchored" data-anchor-id="sampling-parameters">Sampling parameters</h4>
<p>XGBoost can randomly sample rows and columns to be used for training each tree; you might think of this as <em>bagging</em>. We have a few parameters:</p>
<ul>
<li><code>subsample</code> - proportion of rows to use in each tree. Setting this less than 1.0 results in stochastic gradient descent, because each tree is trained on only a subset of the entire training dataset. Any value in (0,1] is valid, but it seems like values in [0.7, 1] are usually the best.</li>
<li><code>colsample_bytree</code>, <code>colsample_bylevel</code>, <code>colsample_bynode</code> - control the fraction of columns available to each tree, at each split level, or at each split, respectively. I usually use either by level or by node because I like the idea that trees might be forced to learn interactions by having different features available at each subsequent split. Again, values in (0,1] are valid, but values in [0.5,1] usually seem to work best.</li>
</ul>
</section>
<section id="regularization-parameters" class="level4">
<h4 class="anchored" data-anchor-id="regularization-parameters">Regularization parameters</h4>
<p>In XGBoost, regularization penalizes the actual values predicted by the individual trees, pushing values toward zero. I usually use:</p>
<ul>
<li><code>reg_lambda</code> - L2 regularization of tree predicted values. Increasing this parameter decreases tree expressiveness and therefore counters overfitting. Valid values are in [0,<img src="https://latex.codecogs.com/png.latex?%5Cinfty">), but good values typically fall in [0,10].</li>
</ul>
<p>There is also an L1 regularization parameter called <code>reg_alpha</code>; feel free to use it instead. It seems that using one or the other is usually sufficient.</p>
</section>
</section>
<section id="boosting-parameters-and-early-stopping" class="level3">
<h3 class="anchored" data-anchor-id="boosting-parameters-and-early-stopping">Boosting Parameters and Early Stopping</h3>
<p>Trained gradient boosting models take the form:</p>
<p><img src="https://latex.codecogs.com/png.latex?%20F(%5Cmathbf%7Bx%7D)%20=%20b%20+%20%5Ceta%20%5Csum_%7Bk=1%7D%5E%7BK%7D%20f_k(%5Cmathbf%7Bx%7D)%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?b"> is the constant base predicted value, <img src="https://latex.codecogs.com/png.latex?f_k(%5Ccdot)"> is the base learner for round <img src="https://latex.codecogs.com/png.latex?k">, parameter <img src="https://latex.codecogs.com/png.latex?K"> is the number of boosting rounds, and parameter <img src="https://latex.codecogs.com/png.latex?%5Ceta"> is the learning rate. In XGBoost these parameters correspond with:</p>
<ul>
<li><code>num_boost_round</code> (<img src="https://latex.codecogs.com/png.latex?K">) - the number of boosting iterations</li>
<li><code>learning_rate</code> (<img src="https://latex.codecogs.com/png.latex?%5Ceta">) - the scaling or “shrinkage” factor applied to the predicted value of each base learner. Valid values are in (0,1]; the default is 0.3. Fun fact: the <img src="https://latex.codecogs.com/png.latex?%5Ceta"> character is called “eta”, and <code>learning_rate</code> is aliased to <code>eta</code> in xgboost, so you can use parameter <code>eta</code> instead of <code>learning_rate</code> if you like.</li>
</ul>
<p>These two parameters are very closely linked; the optimal value of one depends on the value of the other. To illustrate their relationship, we can train two different XGBoost models on the same training dataset, where one model has a lower learning rate than the other.</p>
<div id="cell-4" class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> xgboost <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> xgb </span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_regression </span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt </span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split </span>
<span id="cb1-5"></span>
<span id="cb1-6">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_regression(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5000</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-7">X_train, X_valid, y_train, y_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(X, y, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-8"></span>
<span id="cb1-9">eta1, eta2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span></span>
<span id="cb1-10">reg1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.XGBRegressor(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>eta1, early_stopping_rounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>)</span>
<span id="cb1-11">reg1.fit(X_train, y_train, </span>
<span id="cb1-12">        eval_set<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(X_train, y_train), (X_valid, y_valid)], </span>
<span id="cb1-13">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-14">reg2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.XGBRegressor(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>eta2, early_stopping_rounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>)</span>
<span id="cb1-15">reg2.fit(X_train, y_train, </span>
<span id="cb1-16">        eval_set<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(X_train, y_train), (X_valid, y_valid)], </span>
<span id="cb1-17">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-18"></span>
<span id="cb1-19">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb1-20"></span>
<span id="cb1-21">best_round1, best_round2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> reg1.best_iteration, reg2.best_iteration</span>
<span id="cb1-22">obj1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> reg1.evals_result()[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'validation_1'</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rmse'</span>]</span>
<span id="cb1-23">obj2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> reg2.evals_result()[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'validation_1'</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rmse'</span>]</span>
<span id="cb1-24">best_obj1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> obj1[best_round1]</span>
<span id="cb1-25">best_obj2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> obj2[best_round1]</span>
<span id="cb1-26"></span>
<span id="cb1-27">plt.plot(reg1.evals_result()[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'validation_1'</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rmse'</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-b'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'learning_rate=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>eta1<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb1-28">plt.plot(reg2.evals_result()[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'validation_1'</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rmse'</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-r'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'learning_rate=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>eta2<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb1-29">ax.annotate(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'learning_rate=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>eta1<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">best_iteration=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>best_round1<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, </span>
<span id="cb1-30">            xy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(best_round1, best_obj1), </span>
<span id="cb1-31">            xytext<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(best_round1, best_obj1<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>),</span>
<span id="cb1-32">            horizontalalignment<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'right'</span>,</span>
<span id="cb1-33">            arrowprops<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'black'</span>, shrink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>))</span>
<span id="cb1-34">ax.annotate(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'learning_rate=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>eta2<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">best_iteration=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>best_round2<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, </span>
<span id="cb1-35">            xy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(best_round2, best_obj2), </span>
<span id="cb1-36">            xytext<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(best_round2, best_obj2<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>),</span>
<span id="cb1-37">            horizontalalignment<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'right'</span>,</span>
<span id="cb1-38">            arrowprops<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(facecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'black'</span>, shrink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>))</span>
<span id="cb1-39">plt.legend()</span>
<span id="cb1-40">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'RMSE'</span>) </span>
<span id="cb1-41">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'boosting round'</span>) </span>
<span id="cb1-42">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Validation Scores by Boosting Round'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-parameter-tuning-with-optuna/index_files/figure-html/cell-2-output-1.png" class="img-fluid figure-img" alt="XGBoost objective curves for two models"></p>
<figcaption>Hold-out validation score (RMSE) by boosting round for two XGBoost models differing only by learning rate.</figcaption>
</figure>
</div>
</div>
</div>
<p>The above figure shows root mean squared error measured on a held-out validation dataset for two different XGBoost models: one with a higher learning rate and one with a lower learning rate. The figure demonstrates two key properties of the boosting parameters:</p>
<ol type="1">
<li>While training a model with a given learning rate, the evaluation score (computed on a hold-out set) tends to improve with additional boosting rounds up to a certain point, but beyond that point it flattens out or even gets worse.</li>
<li>All else constant, a smaller learning rate leads to a model with more boosting rounds and better evaluation score.</li>
</ol>
<p>We can leverage the first property to make our tuning more efficient by using XGBoost’s <code>early_stopping_rounds: int</code> argument, which terminates training after observing the specified number of boosting rounds <a href="https://github.com/dmlc/xgboost/pull/6942">without sufficient improvement</a> to the evaluation metric. The models above were trained using <code>early_stopping_rounds=50</code>, which terminates training after 50 boosting rounds without improvement in RMSE on the validation data. For each model, the arrow indicates the boosting round with the best score.</p>
<p>The figure also exemplifies the second property, where the model with lower learning rate attains a better validation score but requires more boosting rounds to trigger early stopping. Note that smaller and smaller learning rates will provide diminishing improvements to the validation score.</p>
</section>
</section>
<section id="an-efficient-parameter-search-strategy-for-xgboost" class="level2">
<h2 class="anchored" data-anchor-id="an-efficient-parameter-search-strategy-for-xgboost">An Efficient Parameter Search Strategy for XGBoost</h2>
<p>Efficiency is the key to effective parameter tuning, because wasting less time means searching more parameter values and finding better models in a given amount of time. But as we just saw, there is a tradeoff between accuracy and training time via the learning rate. Given infinite time and compute resources, we would just choose an arbitrarily tiny learning rate and search through tree parameter values while using early stopping to choose the number of boosting rounds. The problem is that tiny learning rates require tons of boosting rounds, which will make our ideal search prohibitively slow when confronted with the reality of finite time and resources. So what can we do?</p>
<p>My approach is based on the claim that <em>good tree parameters at one learning rate are also good tree parameters at other learning rates</em>. The intuition is that given two models—one with good tree parameters and one with bad tree parameters—the model with good tree parameters will score better, regardless of the learning rate. Thus, tree parameters are “independent” of boosting parameters—See <a href="https://colab.research.google.com/drive/1feyrtDphFizVI1VmctrNgpJzonsmWiHx?usp=sharing">this notebook</a> for justification of this claim.</p>
<p>Independence between tree parameters and boosting parameters suggests a two-stage procedure where we first find optimal tree parameters, then we maximize performance by pushing boosting parameters to the extreme. The procedure is:</p>
<ol type="1">
<li><strong>Tune tree parameters.</strong> Fix the learning rate at a relatively high value (like 0.3ish) and enable early stopping so that each model trains within a few seconds. Use your favorite hyperparameter tuning technique to find the optimal tree parameters.</li>
<li><strong>Tune boosting parameters.</strong> Using these optimal tree parameter values, fix the learning rate as low as you want and train your model, using early stopping to identify the optimal number of boosting rounds.</li>
</ol>
<p>Why is this a good idea? Because by starting with a high learning rate and early stopping enabled, you can burn through hundreds of model training trials and find some really good tree parameters in a few minutes. Then, with the confidence that your tree parameters are actually quite good, you can set a really low learning rate and boost a few thousand rounds to get a model with the best of both tree parameter and boosting parameter worlds.</p>
<blockquote class="blockquote">
<p>You can check out <a href="https://colab.research.google.com/drive/1feyrtDphFizVI1VmctrNgpJzonsmWiHx?usp=sharing">this notebook</a> where I justify this approach by running two parameter searches—one with high learning rate and one with low learning rate—showing that they recover the same optimal tree parameters.</p>
</blockquote>
</section>
<section id="tuning-xgboost-parameters-with-optuna" class="level2">
<h2 class="anchored" data-anchor-id="tuning-xgboost-parameters-with-optuna">Tuning XGBoost Parameters with Optuna</h2>
<p><a href="https://optuna.readthedocs.io/en/stable/">Optuna</a> is a model-agnostic python library for hyperparameter tuning. I like it because it has a flexible API that abstracts away the details of the search algorithm being used. That means you can use this one library to tune all kinds of different models, and you can easily switch the parameter sampling approach among grid search, random search, the very sensible default bayesian optimization, and more. Another massive benefit is that optuna provides a specific <a href="https://optuna.readthedocs.io/en/stable/reference/generated/optuna.integration.XGBoostPruningCallback.html">XGBoost integration</a> which terminates training early on lousy parameter combinations.</p>
<p>You can install optuna with anaconda, e.g.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode .zsh code-with-copy"><code class="sourceCode zsh"><span id="cb2-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">$</span> conda install <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-c</span> conda-forge optuna</span></code></pre></div></div>
</section>
<section id="example-tuning-the-bluebook-for-bulldozers-regression-model" class="level2">
<h2 class="anchored" data-anchor-id="example-tuning-the-bluebook-for-bulldozers-regression-model">Example: Tuning the Bluebook for Bulldozers Regression Model</h2>
<p>To illustrate the procedure, we’ll tune the parameters for the regression model we built back in the <a href="../../posts/xgboost-for-regression-in-python/">XGBoost for regression</a> post. First we’ll load up the bulldozer data and prepare the features and target just like we did before.</p>
<div id="cell-9" class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time </span>
<span id="cb3-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb3-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb3-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb3-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> mean_squared_error</span>
<span id="cb3-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> xgboost <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> xgb</span>
<span id="cb3-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> optuna </span>
<span id="cb3-8"></span>
<span id="cb3-9">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_csv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'../xgboost-for-regression-in-python/Train.csv'</span>, parse_dates<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate'</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-10"></span>
<span id="cb3-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> encode_string_features(df):</span>
<span id="cb3-12">    out_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.copy()</span>
<span id="cb3-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> feature, feature_type <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df.dtypes.items():</span>
<span id="cb3-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> feature_type <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'object'</span>:</span>
<span id="cb3-15">            out_df[feature] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> out_df[feature].astype(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'category'</span>)</span>
<span id="cb3-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out_df</span>
<span id="cb3-17"></span>
<span id="cb3-18">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> encode_string_features(df)</span>
<span id="cb3-19"></span>
<span id="cb3-20">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate_days_since_epoch'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb3-21">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pd.Timestamp(year<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1970</span>, month<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, day<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-22">    ).dt.days</span>
<span id="cb3-23"></span>
<span id="cb3-24">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'logSalePrice'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.log1p(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'SalePrice'</span>])</span>
<span id="cb3-25"></span>
<span id="cb3-26"></span>
<span id="cb3-27">features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb3-28">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'SalesID'</span>,</span>
<span id="cb3-29">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MachineID'</span>,</span>
<span id="cb3-30">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ModelID'</span>,</span>
<span id="cb3-31">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'datasource'</span>,</span>
<span id="cb3-32">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'auctioneerID'</span>,</span>
<span id="cb3-33">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'YearMade'</span>,</span>
<span id="cb3-34">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MachineHoursCurrentMeter'</span>,</span>
<span id="cb3-35">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'UsageBand'</span>,</span>
<span id="cb3-36">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiModelDesc'</span>,</span>
<span id="cb3-37">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiBaseModel'</span>,</span>
<span id="cb3-38">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiSecondaryDesc'</span>,</span>
<span id="cb3-39">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiModelSeries'</span>,</span>
<span id="cb3-40">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiModelDescriptor'</span>,</span>
<span id="cb3-41">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ProductSize'</span>,</span>
<span id="cb3-42">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiProductClassDesc'</span>,</span>
<span id="cb3-43">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'state'</span>,</span>
<span id="cb3-44">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ProductGroup'</span>,</span>
<span id="cb3-45">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ProductGroupDesc'</span>,</span>
<span id="cb3-46">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Drive_System'</span>,</span>
<span id="cb3-47">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Enclosure'</span>,</span>
<span id="cb3-48">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Forks'</span>,</span>
<span id="cb3-49">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Pad_Type'</span>,</span>
<span id="cb3-50">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Ride_Control'</span>,</span>
<span id="cb3-51">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Stick'</span>,</span>
<span id="cb3-52">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Transmission'</span>,</span>
<span id="cb3-53">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Turbocharged'</span>,</span>
<span id="cb3-54">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Blade_Extension'</span>,</span>
<span id="cb3-55">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Blade_Width'</span>,</span>
<span id="cb3-56">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Enclosure_Type'</span>,</span>
<span id="cb3-57">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Engine_Horsepower'</span>,</span>
<span id="cb3-58">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Hydraulics'</span>,</span>
<span id="cb3-59">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Pushblock'</span>,</span>
<span id="cb3-60">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Ripper'</span>,</span>
<span id="cb3-61">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Scarifier'</span>,</span>
<span id="cb3-62">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Tip_Control'</span>,</span>
<span id="cb3-63">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Tire_Size'</span>,</span>
<span id="cb3-64">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Coupler'</span>,</span>
<span id="cb3-65">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Coupler_System'</span>,</span>
<span id="cb3-66">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Grouser_Tracks'</span>,</span>
<span id="cb3-67">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Hydraulics_Flow'</span>,</span>
<span id="cb3-68">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Track_Type'</span>,</span>
<span id="cb3-69">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Undercarriage_Pad_Width'</span>,</span>
<span id="cb3-70">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Stick_Length'</span>,</span>
<span id="cb3-71">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Thumb'</span>,</span>
<span id="cb3-72">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Pattern_Changer'</span>,</span>
<span id="cb3-73">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Grouser_Type'</span>,</span>
<span id="cb3-74">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Backhoe_Mounting'</span>,</span>
<span id="cb3-75">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Blade_Type'</span>,</span>
<span id="cb3-76">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Travel_Controls'</span>,</span>
<span id="cb3-77">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Differential_Type'</span>,</span>
<span id="cb3-78">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Steering_Controls'</span>,</span>
<span id="cb3-79">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate_days_since_epoch'</span></span>
<span id="cb3-80"> ]</span>
<span id="cb3-81"></span>
<span id="cb3-82">target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'logSalePrice'</span></span></code></pre></div></div>
</details>
</div>
<p>But this time, since we’re going to slam our validation set over and over during hyperparameter search, we want to reserve an actual test set to check how the final model generalizes. We make four different <code>xgboost.DMatrix</code> datasets for this process: training, validation, training+validation, and test. Training and validation are for the parameter search, and training+validation and test are for the final model.</p>
<div id="cell-11" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">n_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12000</span></span>
<span id="cb4-2">n_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12000</span></span>
<span id="cb4-3"></span>
<span id="cb4-4">sorted_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.sort_values(by<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate'</span>)</span>
<span id="cb4-5">train_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sorted_df[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(n_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> n_test)] </span>
<span id="cb4-6">valid_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sorted_df[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(n_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> n_test):<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n_test] </span>
<span id="cb4-7">test_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sorted_df[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n_test:]</span>
<span id="cb4-8"></span>
<span id="cb4-9">dtrain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[features], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[target], </span>
<span id="cb4-10">                     enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb4-11">dvalid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[features], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[target], </span>
<span id="cb4-12">                     enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb4-13">dtest <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>test_df[features], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>test_df[target], </span>
<span id="cb4-14">                    enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb4-15">dtrainvalid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pd.concat([train_df, valid_df])[features], </span>
<span id="cb4-16">                          label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pd.concat([train_df, valid_df])[target], </span>
<span id="cb4-17">                          enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
</div>
</section>
<section id="preliminaries-base-parameters-and-scoring-function" class="level2">
<h2 class="anchored" data-anchor-id="preliminaries-base-parameters-and-scoring-function">Preliminaries: base parameters and scoring function</h2>
<p>We’ll go ahead and set a couple of parameters that we usually want to keep fixed across all trials in a parameter search, including the XGBoost objective for training and the evaluation metric to be used for early stopping. We’ll also want to implement a model scoring function that takes a trained model and a dataset and returns the score, in our case, RMSE.</p>
<div id="cell-13" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">metric <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rmse'</span></span>
<span id="cb5-2">base_params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb5-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'objective'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg:squarederror'</span>,</span>
<span id="cb5-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'eval_metric'</span>: metric,</span>
<span id="cb5-5">}</span></code></pre></div></div>
</div>
<div id="cell-14" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> score_model(model: xgb.core.Booster, dmat: xgb.core.DMatrix) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>:</span>
<span id="cb6-2">    y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dmat.get_label() </span>
<span id="cb6-3">    y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.predict(dmat) </span>
<span id="cb6-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> mean_squared_error(y_true, y_pred, squared<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span></code></pre></div></div>
</div>
</section>
<section id="stage-1-tune-tree-parameters-with-optuna" class="level2">
<h2 class="anchored" data-anchor-id="stage-1-tune-tree-parameters-with-optuna">Stage 1: Tune Tree Parameters with Optuna</h2>
<p>Next we need to choose a fixed learning rate and tune the tree parameters. We want a learning rate that allows us to train within a few seconds, so we need to time model training. Start with a high learning rate (like 0.8) and work down until you find a rate that takes a few seconds. Below I end up landing at 0.3, which takes about 4 seconds to train on my little laptop.</p>
<div id="cell-16" class="cell" data-execution_count="22">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span></span>
<span id="cb7-2"></span>
<span id="cb7-3">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb7-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'approx'</span>,</span>
<span id="cb7-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>: learning_rate</span>
<span id="cb7-6">}</span>
<span id="cb7-7">params.update(base_params)</span>
<span id="cb7-8">tic <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.time()</span>
<span id="cb7-9">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrain,</span>
<span id="cb7-10">                  evals<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(dtrain, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>), (dvalid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>)],</span>
<span id="cb7-11">                  num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>,</span>
<span id="cb7-12">                  early_stopping_rounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>,</span>
<span id="cb7-13">                  verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb7-14"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>time<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>time() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tic<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.1f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> seconds'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>4.5 seconds</code></pre>
</div>
</div>
<p>Then we implement our optuna objective, a function taking an optuna study <a href="https://optuna.readthedocs.io/en/stable/reference/generated/optuna.trial.Trial.html"><code>Trial</code></a> object and returning the score we want to optimize. We use the <code>suggest_categorical</code>, <code>suggest_float</code>, and <code>suggest_int</code> methods of the <code>Trial</code> object to define the search space for each parameter. Note the use of the pruning callback function which we pass into the <code>callback</code> argument of the XGBoost <code>train</code> function; this is a must, since it allows optuna to terminate training on lousy models after a few boosting rounds. After training a model with the selected parameter values, we stash the optimal number of boosting rounds from early stopping into an optuna user attribute using the <a href="https://optuna.readthedocs.io/en/stable/tutorial/20_recipes/003_attributes.html"><code>trial.user_attrs()</code></a> method. Finally we return the score computed by our <code>model_score</code> function.</p>
<div id="cell-18" class="cell" data-execution_count="23">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> objective(trial):</span>
<span id="cb9-2">    params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb9-3">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: trial.suggest_categorical(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>, [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'approx'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'hist'</span>]),</span>
<span id="cb9-4">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>: trial.suggest_int(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>),</span>
<span id="cb9-5">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>: trial.suggest_int(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">250</span>),</span>
<span id="cb9-6">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>: trial.suggest_float(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>),</span>
<span id="cb9-7">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'colsample_bynode'</span>: trial.suggest_float(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'colsample_bynode'</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>),</span>
<span id="cb9-8">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg_lambda'</span>: trial.suggest_float(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg_lambda'</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, log<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>),</span>
<span id="cb9-9">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>: learning_rate,</span>
<span id="cb9-10">    }</span>
<span id="cb9-11">    num_boost_round <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span></span>
<span id="cb9-12">    params.update(base_params)</span>
<span id="cb9-13">    pruning_callback <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optuna.integration.XGBoostPruningCallback(trial, <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'valid-</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>metric<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb9-14">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrain, num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round,</span>
<span id="cb9-15">                      evals<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(dtrain, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>), (dvalid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>)],</span>
<span id="cb9-16">                      early_stopping_rounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>,</span>
<span id="cb9-17">                      verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb9-18">                      callbacks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[pruning_callback])</span>
<span id="cb9-19">    trial.set_user_attr(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'best_iteration'</span>, model.best_iteration)</span>
<span id="cb9-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> model.best_score</span></code></pre></div></div>
</div>
<p>To create a new optuna study and search through 50 parameter combinations, you could just run these two lines.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">study <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optuna.create_study(direction<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'minimize'</span>)</span>
<span id="cb10-2">study.optimize(objective, n_trials<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)</span></code></pre></div></div>
<p>But, in practice, I prefer to run these potentially long running tasks for a pre-specified amount of clock time, rather than a specified number of trials—who knows how long 50 trials will take. I also want the results to be reproducible. So, to set the random seed and run the optimization for around 300 seconds (long enough to go make a nice cup of tea, stretch, and come back), I do something like this:</p>
<div id="cell-20" class="cell" data-execution_count="24">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">sampler <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optuna.samplers.TPESampler(seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb11-2">study <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> optuna.create_study(direction<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'minimize'</span>, sampler<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sampler)</span>
<span id="cb11-3">tic <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.time()</span>
<span id="cb11-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> time.time() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tic <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>:</span>
<span id="cb11-5">    study.optimize(objective, n_trials<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</div>
<div id="cell-21" class="cell" data-execution_count="26">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Stage 1 =============================='</span>)</span>
<span id="cb12-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'best score = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>study<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>best_trial<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>value<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb12-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'boosting params ---------------------------'</span>)</span>
<span id="cb12-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'fixed learning rate: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>learning_rate<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb12-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'best boosting round: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>study<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>best_trial<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>user_attrs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"best_iteration"</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb12-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'best tree params --------------------------'</span>)</span>
<span id="cb12-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k, v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> study.best_trial.params.items():</span>
<span id="cb12-8">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(k, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">':'</span>, v)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>Stage 1 ==============================
best score = 0.23107522766919256
boosting params ---------------------------
fixed learning rate: 0.3
best boosting round: 23
best tree params --------------------------
tree_method : approx
max_depth : 10
min_child_weight : 6
subsample : 0.9729188669457949
colsample_bynode : 0.8491983767203796
reg_lambda : 0.008587261143813469</code></pre>
</div>
</div>
<p>If we decide we want to tune the tree parameters a little more, we can just call <code>study.optimize(...)</code> again, adding as many trials as we want to the study. Once we’re happy with the tree parameters, we can proceed to stage 2.</p>
</section>
<section id="stage-2-intensify-the-boosting-parameters" class="level2">
<h2 class="anchored" data-anchor-id="stage-2-intensify-the-boosting-parameters">Stage 2: Intensify the Boosting Parameters</h2>
<p>Now we take the optimal tree parameters that we found in stage 1, and we train a new model with a fixed low learning rate; here I use 0.01, but you could go lower. The lower your learning rate, the better your performance (with diminishing returns) and the more boosting rounds you’ll need to max out the evaluation metric on the validation data.</p>
<div id="cell-23" class="cell" data-execution_count="27">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">low_learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span></span>
<span id="cb14-2"></span>
<span id="cb14-3">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb14-4">params.update(base_params)</span>
<span id="cb14-5">params.update(study.best_trial.params)</span>
<span id="cb14-6">params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> low_learning_rate</span>
<span id="cb14-7">model_stage2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrain, </span>
<span id="cb14-8">                         num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>,</span>
<span id="cb14-9">                         evals<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(dtrain, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>), (dvalid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>)],</span>
<span id="cb14-10">                         early_stopping_rounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>,</span>
<span id="cb14-11">                         verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
</div>
<div id="cell-24" class="cell" data-execution_count="28">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Stage 2 =============================='</span>)</span>
<span id="cb15-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'best score = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>score_model(model_stage2, dvalid)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb15-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'boosting params ---------------------------'</span>)</span>
<span id="cb15-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'fixed learning rate: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"learning_rate"</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb15-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'best boosting round: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>model_stage2<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>best_iteration<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>Stage 2 ==============================
best score = 0.22172991931438446
boosting params ---------------------------
fixed learning rate: 0.01
best boosting round: 1446</code></pre>
</div>
</div>
</section>
<section id="train-and-evaluate-the-final-model" class="level2">
<h2 class="anchored" data-anchor-id="train-and-evaluate-the-final-model">Train and Evaluate the Final Model</h2>
<p>Now we can train our final model on the combined training and validation datasets using the optimal tree parameters from stage 1 and the fixed learning rate and optimal boosting rounds from stage 2. Then we evaluate on the held out test data.</p>
<div id="cell-26" class="cell" data-execution_count="29">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">model_final <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrainvalid, </span>
<span id="cb17-2">                        num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_stage2.best_iteration,</span>
<span id="cb17-3">                        verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
</div>
<div id="cell-27" class="cell" data-execution_count="30">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Final Model =========================='</span>)</span>
<span id="cb18-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'test score = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>score_model(model_final, dtest)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb18-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'parameters ---------------------------'</span>)</span>
<span id="cb18-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k, v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> params.items():</span>
<span id="cb18-5">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(k, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">':'</span>, v)</span>
<span id="cb18-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'num_boost_round: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>model_stage2<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>best_iteration<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>Final Model ==========================
test score = 0.21621863543987274
parameters ---------------------------
objective : reg:squarederror
eval_metric : rmse
tree_method : approx
max_depth : 10
min_child_weight : 6
subsample : 0.9729188669457949
colsample_bynode : 0.8491983767203796
reg_lambda : 0.008587261143813469
learning_rate : 0.01
num_boost_round: 1446</code></pre>
</div>
</div>
<p>Back in the <a href="../../posts/xgboost-for-regression-in-python/">regression post</a> we got an RMSE of about 0.231 just using default parameter values, which put us in 5th place on the <a href="https://www.kaggle.com/competitions/bluebook-for-bulldozers/leaderboard">leaderboard for the Kagle dozers competition</a>. Now with about 10 minutes of hyperparameter tuning, our RMSE is down to 0.216 which puts us in 1st place by a huge margin. 🙌</p>
</section>
<section id="what-could-possibly-go-wrong" class="level2">
<h2 class="anchored" data-anchor-id="what-could-possibly-go-wrong">What could possibly go wrong?</h2>
<p>Hyperparameter tuning can easily be overlooked in the move-fast-and-break-everything hustle of building an ML product, but it can also easily become overkill or even downright harmful, depending on the application. There are three key questions to ask:</p>
<ol type="1">
<li>How much value is created by an incremental gain in model prediction accuracy?</li>
<li>What is the cost of increasing model prediction accuracy?</li>
<li>Is my model answering the right question?</li>
</ol>
<p>Sometimes a small gain in model prediction performance translates into millions of dollars of impact. The dream scenario is that you swoop in on some key model in your organization, markedly improve its accuracy with an easy afternoon of hyperparameter tuning, realize massive improvements in your org’s KPIs, and get mad respect, bonuses, and promoted. But the reality is that often additional model accuracy doesn’t really change business KPIs by very much. Try to figure out the actual value of improved model accuracy and proceed accordingly.</p>
<p>Remember too that hyperparameter tuning has its costs, most obviously the developer time and compute resources for the search itself. It can also lead us to larger and deeper models which take longer to train, occupy larger memory footprints, and have higher prediction latency.</p>
<p>Worst of all and quite counterintuitively, it’s possible that improving a model’s prediction accuracy can compromise overall business KPIs. I’ve seen this with my own eyes at work; offline testing shows that hyperparameter tuning significantly improves a model’s prediction accuracy, but when the model goes into production, an AB test shows that the business KPIs are actually worse. What happened? In this case, the model’s prediction was being used indirectly to infer the relationship between one of the features and the prediction target to inform automatic business decisions. Answering questions about how changing an input will affect an output requires causal reasoning, and <a href="https://arxiv.org/abs/1608.00060">traditional ML models are not the right tool for the job</a>. I’ll have a lot more to say about that soon; let this story foreshadow an epic new epoch on Random Realizations….</p>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>There it is, an efficient and ridiculously easy hyperparameter tuning strategy for XGBoost using optuna. If you found this helpful, if you have questions, or if you have your own preferred method for parameter search, let me know about it down in the comments!</p>


</section>

 ]]></description>
  <category>python</category>
  <category>tutorial</category>
  <category>gradient boosting</category>
  <category>xgboost</category>
  <guid>https://randomrealizations.com/posts/xgboost-parameter-tuning-with-optuna/</guid>
  <pubDate>Tue, 26 Dec 2023 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/xgboost-parameter-tuning-with-optuna/optuna_thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>XGBoost for Binary and Multi-Class Classification in Python</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/xgboost-for-classification-in-python/</link>
  <description><![CDATA[ 





<p>Today we continue the <a href="../../gradient-boosting-series.qmd">saga on gradient boosting</a> with a down-to-Earth tutorial on the essentials of solving classification problems with XGBoost. We’ll run through two examples: one for binary classification and another for multi-class classification. In both cases I’ll show you how to train XGBoost models using either the scikit-learn interface or the native xgboost training API. Once trained, we’ll evaluate the models with validation data then inspect them with feature importance and partial dependence plots. You can use the XGBoost classification notebook in my <a href="https://github.com/mcb00/ds-templates">ds-templates repository</a> to follow along with your own dataset.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-classification-main.jpg" class="img-fluid figure-img"></p>
<figcaption>Afternoon in the Mara</figcaption>
</figure>
</div>
<section id="preparing-data-for-xgboost-classifier" class="level2">
<h2 class="anchored" data-anchor-id="preparing-data-for-xgboost-classifier">Preparing Data for XGBoost Classifier</h2>
<p>Our dataset must satisfy two requirements to be used in an XGBoost classifier. First all feature data must be numeric—no strings and no datetimes; if you have non-numeric features, you need to <a href="../../posts/xgboost-for-regression-in-python/#prepare-raw-data-for-xgboost">transform your feature data</a>. Second, the target must be integer encoded using <img src="https://latex.codecogs.com/png.latex?%5C%7B0,1%5C%7D"> for binary targets and <img src="https://latex.codecogs.com/png.latex?%5C%7B0,1,%5Cdots,K%5C%7D"> for multiclass targets. Note that if your data is encoded to positive integers (no 0 class) XGBoost will throw potentially cryptic errors. You can use the scikit-learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html"><code>LabelEncoder</code></a> (which we’ll do below) to generate a valid target encoding.</p>
</section>
<section id="xgboost-training-apis" class="level2">
<h2 class="anchored" data-anchor-id="xgboost-training-apis">XGBoost Training APIs</h2>
<p>The <code>xgboost</code> python library offers two API’s for training classification models: the native <a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training"><code>train</code></a> function and a wrapper class called <a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn"><code>XGBClassifier</code></a>, which offers an API consistent with the scikit-learn universe. I’ll show you how to use both approaches in the examples below, but if you’re planning to use other utilities from scikit-learn, you might find the <code>XGBClassifier</code> approach to be more convenient, since the trained model object will generally play nice with sklearn functionality.</p>
</section>
<section id="binary-classification-example" class="level2">
<h2 class="anchored" data-anchor-id="binary-classification-example">Binary Classification Example</h2>
<section id="breast-cancer-wisconsin-dataset" class="level3">
<h3 class="anchored" data-anchor-id="breast-cancer-wisconsin-dataset">Breast Cancer Wisconsin Dataset</h3>
<p>We’ll demonstrate binary classification in XGBoost using the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html#sklearn.datasets.load_breast_cancer">breast cancer wisconsin data</a>, one of scikit-learn’s built-in toy datasets. This is a tiny dataset with 569 observations of 30 features and a binary target representing whether samples are malignant or benign..</p>
<div id="cell-6" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np </span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd </span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt </span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> datasets</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> xgboost <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> xgb </span>
<span id="cb1-6"></span>
<span id="cb1-7">dbunch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> datasets.load_breast_cancer(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-8">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dbunch.frame</span>
<span id="cb1-9">features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dbunch.feature_names </span>
<span id="cb1-10">target_names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dbunch.target_names </span>
<span id="cb1-11">target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'target'</span> </span>
<span id="cb1-12">df.info()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt;
RangeIndex: 569 entries, 0 to 568
Data columns (total 31 columns):
 #   Column                   Non-Null Count  Dtype  
---  ------                   --------------  -----  
 0   mean radius              569 non-null    float64
 1   mean texture             569 non-null    float64
 2   mean perimeter           569 non-null    float64
 3   mean area                569 non-null    float64
 4   mean smoothness          569 non-null    float64
 5   mean compactness         569 non-null    float64
 6   mean concavity           569 non-null    float64
 7   mean concave points      569 non-null    float64
 8   mean symmetry            569 non-null    float64
 9   mean fractal dimension   569 non-null    float64
 10  radius error             569 non-null    float64
 11  texture error            569 non-null    float64
 12  perimeter error          569 non-null    float64
 13  area error               569 non-null    float64
 14  smoothness error         569 non-null    float64
 15  compactness error        569 non-null    float64
 16  concavity error          569 non-null    float64
 17  concave points error     569 non-null    float64
 18  symmetry error           569 non-null    float64
 19  fractal dimension error  569 non-null    float64
 20  worst radius             569 non-null    float64
 21  worst texture            569 non-null    float64
 22  worst perimeter          569 non-null    float64
 23  worst area               569 non-null    float64
 24  worst smoothness         569 non-null    float64
 25  worst compactness        569 non-null    float64
 26  worst concavity          569 non-null    float64
 27  worst concave points     569 non-null    float64
 28  worst symmetry           569 non-null    float64
 29  worst fractal dimension  569 non-null    float64
 30  target                   569 non-null    int64  
dtypes: float64(30), int64(1)
memory usage: 137.9 KB</code></pre>
</div>
</div>
<p>In this dataset, the features are all numeric, so no need to do preprocessing before passing to XGBoost. Below we’ll have a look at the target to ensure it’s encoded in <img src="https://latex.codecogs.com/png.latex?%5C%7B0,1%5C%7D"> and to check the class balance.</p>
<div id="cell-8" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(df[target].unique())</span>
<span id="cb3-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(target_names)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0 1]
['malignant' 'benign']</code></pre>
</div>
</div>
<div id="cell-9" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">df.target.value_counts().sort_index().plot.bar()</span>
<span id="cb5-2">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'target'</span>) </span>
<span id="cb5-3">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'count'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-for-classification-in-python_files/figure-html/cell-4-output-1.png" class="img-fluid figure-img" alt="bar plot showing the count of observations in each class"></p>
<figcaption>class counts for the breast cancer dataset</figcaption>
</figure>
</div>
</div>
</div>
<p>Next We randomly split data into train and validation sets.</p>
<div id="cell-11" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split</span>
<span id="cb6-2"></span>
<span id="cb6-3">n_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span> </span>
<span id="cb6-4"></span>
<span id="cb6-5">train_df, valid_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(df, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_valid, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb6-6">train_df.shape, valid_df.shape</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="4">
<pre><code>((519, 31), (50, 31))</code></pre>
</div>
</div>
</section>
<section id="training-with-the-train-function" class="level3">
<h3 class="anchored" data-anchor-id="training-with-the-train-function">Training with the <code>train</code> function</h3>
<p>We need to set a couple of <a href="https://xgboost.readthedocs.io/en/stable/parameter.html">model parameters</a>, most notably <code>objective</code>, which should be set to <code>binary:logistic</code> for binary classification. I also prefer to explicitly set <code>tree_method</code> to something other than its default of <code>auto</code>; usually I’ll start with <code>exact</code> on small datasets or <code>approx</code> on larger ones. Note also that The <code>train</code> function expects to receive data as <code>DMatrix</code> objects, not pandas dataframes, so we need to create dense matrix objects as well.</p>
<div id="cell-13" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb8-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'exact'</span>,</span>
<span id="cb8-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'objective'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'binary:logistic'</span>,</span>
<span id="cb8-4">}</span>
<span id="cb8-5">num_boost_round <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span></span>
<span id="cb8-6"></span>
<span id="cb8-7">dtrain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[target], data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[features])</span>
<span id="cb8-8">dvalid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[target], data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[features])</span>
<span id="cb8-9">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrain, num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round,</span>
<span id="cb8-10">                  evals<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(dtrain, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>), (dvalid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>)],</span>
<span id="cb8-11">                  verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0] train-logloss:0.46232   valid-logloss:0.49033
[10]    train-logloss:0.04394   valid-logloss:0.13434
[20]    train-logloss:0.01515   valid-logloss:0.12193
[30]    train-logloss:0.00995   valid-logloss:0.11988
[40]    train-logloss:0.00766   valid-logloss:0.12416
[49]    train-logloss:0.00657   valid-logloss:0.12799</code></pre>
</div>
</div>
</section>
<section id="training-with-xgbclassifier" class="level3">
<h3 class="anchored" data-anchor-id="training-with-xgbclassifier">Training with <code>XGBClassifier</code></h3>
<p>The <code>XGBClassifier</code> takes dataframes or numpy arrays as input, so this time we don’t need to create those dense matrix objects.</p>
<div id="cell-15" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb10-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'exact'</span>,</span>
<span id="cb10-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'objective'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'binary:logistic'</span>,</span>
<span id="cb10-4">}</span>
<span id="cb10-5">num_boost_round <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span></span>
<span id="cb10-6"></span>
<span id="cb10-7">clf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.XGBClassifier(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>params)</span>
<span id="cb10-8">clf.fit(train_df[features], train_df[target], </span>
<span id="cb10-9">        eval_set<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(train_df[features], train_df[target]), (valid_df[features], valid_df[target])], </span>
<span id="cb10-10">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0] validation_0-logloss:0.46232    validation_1-logloss:0.49033
[10]    validation_0-logloss:0.04394    validation_1-logloss:0.13434
[20]    validation_0-logloss:0.01515    validation_1-logloss:0.12193
[30]    validation_0-logloss:0.00995    validation_1-logloss:0.11988
[40]    validation_0-logloss:0.00766    validation_1-logloss:0.12416
[49]    validation_0-logloss:0.00657    validation_1-logloss:0.12799</code></pre>
</div>
</div>
</section>
<section id="evaluating-the-model" class="level3">
<h3 class="anchored" data-anchor-id="evaluating-the-model">Evaluating the Model</h3>
<p>We’ll use the <code>sklearn.metrics</code> module to evaluate model performance on the held-out validation set. Have a look at the <a href="https://scikit-learn.org/stable/modules/model_evaluation.html#classification-metrics">scikit-learn metrics for classification</a> for examples of other metrics to use.</p>
<p>One thing to watch out for when computing metrics is the difference between the actual labels (usually called <code>y_true</code>), the model’s predicted labels (usually called <code>y_pred</code>), and the models predicted probabilities (usually called <code>y_score</code>). If you’re using the <code>XGBClassifier</code> wrapper, you can get predicted labels with the <code>predict</code> method and predicted probabilities with the <code>predict_proba</code> method. Also note that whereas <code>predict</code> returns a vector of size (num data), <code>predict_proba</code> returns a vector of size (num data, num classes); thus for binary classification, we’ll take just the second column of the array which gives the probability of class 1.</p>
<div id="cell-17" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> valid_df[target]</span>
<span id="cb12-2">y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clf.predict(valid_df[features])</span>
<span id="cb12-3">y_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clf.predict_proba(valid_df[features])[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span></code></pre></div></div>
</div>
<p>Probably the simplest classification metric is accuracy, the proportion of labels we predicted correctly.</p>
<div id="cell-19" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> metrics </span>
<span id="cb13-2"></span>
<span id="cb13-3">metrics.accuracy_score(y_true, y_pred)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="8">
<pre><code>0.96</code></pre>
</div>
</div>
<p>We can generate a classification report with several different metrics at once.</p>
<div id="cell-21" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(metrics.classification_report(y_true, y_pred, target_names<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>target_names))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>              precision    recall  f1-score   support

   malignant       0.93      0.93      0.93        15
      benign       0.97      0.97      0.97        35

    accuracy                           0.96        50
   macro avg       0.95      0.95      0.95        50
weighted avg       0.96      0.96      0.96        50
</code></pre>
</div>
</div>
<p>And we can compute the AUC, a popular classification metric based on the ROC curve, which depends on the predicted probability rather than the predicted labels.</p>
<div id="cell-23" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">metrics.roc_auc_score(y_true, y_score)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="10">
<pre><code>0.9885714285714287</code></pre>
</div>
</div>
</section>
<section id="feature-importance" class="level3">
<h3 class="anchored" data-anchor-id="feature-importance">Feature Importance</h3>
<p>Because of the <a href="../../posts/xgboost-for-regression-in-python/#feature-importance-for-xgboost">limitations of the built-in XGBoost feature importance metrics</a> I recommend that you use either <a href="https://scikit-learn.org/stable/modules/permutation_importance.html">permutation feature importance</a> or perhaps <a href="https://shap.readthedocs.io/en/latest/index.html">SHAP feature importance</a>.</p>
<p>Here we’ll compute the permutation feature importance, which tells us by how much the model’s performance changes when we scramble a particular feature’s values at prediction time. This reflects how much the model relies on each feature when making predictions.</p>
<div id="cell-25" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.inspection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> permutation_importance</span>
<span id="cb19-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_scorer</span>
<span id="cb19-3"></span>
<span id="cb19-4">scorer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_scorer(metrics.log_loss, greater_is_better<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, needs_proba<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb19-5">permu_imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> permutation_importance(clf, valid_df[features], valid_df[target], </span>
<span id="cb19-6">                                   n_repeats<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, scoring<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>scorer)</span></code></pre></div></div>
</div>
<div id="cell-26" class="cell" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1">importances_permutation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.Series(permu_imp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'importances_mean'</span>], index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>features)</span>
<span id="cb20-2">importances_permutation.sort_values(ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>:].plot.barh()</span>
<span id="cb20-3">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Permutation Importance on Out-of-Sample Set'</span>)</span>
<span id="cb20-4">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'change in log likelihood'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-for-classification-in-python_files/figure-html/cell-13-output-1.png" class="img-fluid figure-img" alt="horizontal bar plot showing permutation feature importance"></p>
<figcaption>top 10 features by permutation importance on validation set</figcaption>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="partial-dependence" class="level2">
<h2 class="anchored" data-anchor-id="partial-dependence">Partial Dependence</h2>
<p>A <a href="https://scikit-learn.org/stable/modules/partial_dependence.html">partial dependence plot (PDP)</a> is a representation of the dependence between the model output and one or more feature variables. In binary classification, the model output is the probability of the so-called positive class, i.e.&nbsp;the class with encoded label 1, which corresponds to probability of “benign” in this example.. We can loosely interpret the partial dependence as showing how the expected value of the target changes across values of a particular feature, marginalizing over other features. I say “loosely” because it comes with caveats, a particularly serious one being that correlation among features tends to invalidate the above interpretation. Anyway, we can treat PDPs as useful heuristics for getting a sense of how a model thinks the target changes with feature values.</p>
<div id="cell-28" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.inspection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> PartialDependenceDisplay</span>
<span id="cb21-2"></span>
<span id="cb21-3">PartialDependenceDisplay.from_estimator(clf, </span>
<span id="cb21-4">                                        valid_df[features], </span>
<span id="cb21-5">                                        [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'worst area'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'area error'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mean area'</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-for-classification-in-python_files/figure-html/cell-14-output-1.png" class="img-fluid figure-img" alt="line plots showing partial dependence of probability of benign"></p>
<figcaption>PDP of target probability of benign vs three features</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="multi-class-classification-example" class="level2">
<h2 class="anchored" data-anchor-id="multi-class-classification-example">Multi-Class Classification Example</h2>
<section id="forest-cover-type-dataset" class="level3">
<h3 class="anchored" data-anchor-id="forest-cover-type-dataset">Forest Cover Type Dataset</h3>
<p>We’ll illustrate multi-class classification using the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_covtype.html#sklearn.datasets.fetch_covtype">scikit-learn forest cover type dataset</a>, which has around 580k observations of 54 features and a target with 7 classes.</p>
<div id="cell-30" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1">dbunch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> datasets.fetch_covtype(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb22-2">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dbunch.frame</span>
<span id="cb22-3">features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dbunch.feature_names </span>
<span id="cb22-4">df.info()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt;
RangeIndex: 581012 entries, 0 to 581011
Data columns (total 55 columns):
 #   Column                              Non-Null Count   Dtype  
---  ------                              --------------   -----  
 0   Elevation                           581012 non-null  float64
 1   Aspect                              581012 non-null  float64
 2   Slope                               581012 non-null  float64
 3   Horizontal_Distance_To_Hydrology    581012 non-null  float64
 4   Vertical_Distance_To_Hydrology      581012 non-null  float64
 5   Horizontal_Distance_To_Roadways     581012 non-null  float64
 6   Hillshade_9am                       581012 non-null  float64
 7   Hillshade_Noon                      581012 non-null  float64
 8   Hillshade_3pm                       581012 non-null  float64
 9   Horizontal_Distance_To_Fire_Points  581012 non-null  float64
 10  Wilderness_Area_0                   581012 non-null  float64
 11  Wilderness_Area_1                   581012 non-null  float64
 12  Wilderness_Area_2                   581012 non-null  float64
 13  Wilderness_Area_3                   581012 non-null  float64
 14  Soil_Type_0                         581012 non-null  float64
 15  Soil_Type_1                         581012 non-null  float64
 16  Soil_Type_2                         581012 non-null  float64
 17  Soil_Type_3                         581012 non-null  float64
 18  Soil_Type_4                         581012 non-null  float64
 19  Soil_Type_5                         581012 non-null  float64
 20  Soil_Type_6                         581012 non-null  float64
 21  Soil_Type_7                         581012 non-null  float64
 22  Soil_Type_8                         581012 non-null  float64
 23  Soil_Type_9                         581012 non-null  float64
 24  Soil_Type_10                        581012 non-null  float64
 25  Soil_Type_11                        581012 non-null  float64
 26  Soil_Type_12                        581012 non-null  float64
 27  Soil_Type_13                        581012 non-null  float64
 28  Soil_Type_14                        581012 non-null  float64
 29  Soil_Type_15                        581012 non-null  float64
 30  Soil_Type_16                        581012 non-null  float64
 31  Soil_Type_17                        581012 non-null  float64
 32  Soil_Type_18                        581012 non-null  float64
 33  Soil_Type_19                        581012 non-null  float64
 34  Soil_Type_20                        581012 non-null  float64
 35  Soil_Type_21                        581012 non-null  float64
 36  Soil_Type_22                        581012 non-null  float64
 37  Soil_Type_23                        581012 non-null  float64
 38  Soil_Type_24                        581012 non-null  float64
 39  Soil_Type_25                        581012 non-null  float64
 40  Soil_Type_26                        581012 non-null  float64
 41  Soil_Type_27                        581012 non-null  float64
 42  Soil_Type_28                        581012 non-null  float64
 43  Soil_Type_29                        581012 non-null  float64
 44  Soil_Type_30                        581012 non-null  float64
 45  Soil_Type_31                        581012 non-null  float64
 46  Soil_Type_32                        581012 non-null  float64
 47  Soil_Type_33                        581012 non-null  float64
 48  Soil_Type_34                        581012 non-null  float64
 49  Soil_Type_35                        581012 non-null  float64
 50  Soil_Type_36                        581012 non-null  float64
 51  Soil_Type_37                        581012 non-null  float64
 52  Soil_Type_38                        581012 non-null  float64
 53  Soil_Type_39                        581012 non-null  float64
 54  Cover_Type                          581012 non-null  int32  
dtypes: float64(54), int32(1)
memory usage: 241.6 MB</code></pre>
</div>
</div>
<p>Here again the features are all numeric, so we don’t need to further preprocess them. Let’s have a look at the target.</p>
<div id="cell-32" class="cell" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cover_Type'</span>].value_counts().sort_index().plot.bar()</span>
<span id="cb24-2">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cover type'</span>) </span>
<span id="cb24-3">plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'count'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-for-classification-in-python_files/figure-html/cell-16-output-1.png" class="img-fluid figure-img" alt="bar plot showing the count of observations in each class"></p>
<figcaption>class counts for the forest cover type dataset</figcaption>
</figure>
</div>
</div>
</div>
<p>For multi-class classification, our target variable must take values in <img src="https://latex.codecogs.com/png.latex?%5C%7B0,1,%5Cdots,K%5C%7D">. However, from the histogram of the cover type above, we see that it takes values in <img src="https://latex.codecogs.com/png.latex?%5C%7B1,2,%5Cdots,7%5C%7D">. To fix this we can use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html">scikit-learn label encoder</a> to create a valid target column.</p>
<div id="cell-34" class="cell" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LabelEncoder </span>
<span id="cb25-2"></span>
<span id="cb25-3">target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'encoded'</span></span>
<span id="cb25-4">enc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LabelEncoder()</span>
<span id="cb25-5">df[target] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> enc.fit_transform(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cover_Type'</span>])</span>
<span id="cb25-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(np.sort(df[target].unique()))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0 1 2 3 4 5 6]</code></pre>
</div>
</div>
<p>Then we can create training and validation sets.</p>
<div id="cell-36" class="cell" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1">n_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20000</span></span>
<span id="cb27-2"></span>
<span id="cb27-3">train_df, valid_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(df, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_valid, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb27-4">train_df.shape, valid_df.shape</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="17">
<pre><code>((561012, 56), (20000, 56))</code></pre>
</div>
</div>
</section>
<section id="training-with-the-train-function-1" class="level3">
<h3 class="anchored" data-anchor-id="training-with-the-train-function-1">Training with the <code>train</code> function</h3>
<p>If you’re training with the <code>train</code> function, multi-class classification can be done with two objectives: <code>multi:softmax</code> and <code>multi:softprob</code>. Both use the same loss function—negative multinomial log likelihood—but the softmax option produces a trained <code>Booster</code> object whose predict method returns a 1d array of predicted labels, whereas the softprob option produces a trained <code>Booster</code> object whose predict method returns a 2d array of predicted probabilities. In either case, you also need to explicitly tell XGBoost how many classes the target has with the <code>num_class</code> parameter.</p>
<div id="cell-38" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb29-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'approx'</span>,</span>
<span id="cb29-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'objective'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'multi:softprob'</span>,</span>
<span id="cb29-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'num_class'</span>: df[target].nunique()</span>
<span id="cb29-5">}</span>
<span id="cb29-6">num_boost_round <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb29-7"></span>
<span id="cb29-8">dtrain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[target], data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[features])</span>
<span id="cb29-9">dvalid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[target], data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[features])</span>
<span id="cb29-10">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrain, num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round,</span>
<span id="cb29-11">                  evals<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(dtrain, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>), (dvalid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>)],</span>
<span id="cb29-12">                  verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0] train-mlogloss:1.42032  valid-mlogloss:1.42366
[2] train-mlogloss:1.00541  valid-mlogloss:1.00963
[4] train-mlogloss:0.80557  valid-mlogloss:0.81109
[6] train-mlogloss:0.69432  valid-mlogloss:0.70085
[8] train-mlogloss:0.62653  valid-mlogloss:0.63350
[9] train-mlogloss:0.60111  valid-mlogloss:0.60794</code></pre>
</div>
</div>
</section>
<section id="training-with-xgbclassifier-1" class="level3">
<h3 class="anchored" data-anchor-id="training-with-xgbclassifier-1">Training with <code>XGBClassifier</code></h3>
<p>In multi-class classification, I think the scikit-learn <code>XGBClassifier</code> wrapper is quite a bit more convenient than the native <code>train</code> function. You can set the <code>objective</code> parameter to <code>multi:softprob</code>, and <code>XGBClassifier.fit</code> will produce a model having both <code>predict</code> and <code>predict_proba</code> methods. Also there is no need to explicitly set the number of classes in the target and no need to create the <code>DMatrix</code> objects.</p>
<div id="cell-40" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb31-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'approx'</span>,</span>
<span id="cb31-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'objective'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'multi:softprob'</span>,</span>
<span id="cb31-4">}</span>
<span id="cb31-5">num_boost_round <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb31-6"></span>
<span id="cb31-7">clf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.XGBClassifier(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>params)</span>
<span id="cb31-8">clf.fit(train_df[features], train_df[target], </span>
<span id="cb31-9">        eval_set<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(train_df[features], train_df[target]), (valid_df[features], valid_df[target])], </span>
<span id="cb31-10">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0] validation_0-mlogloss:1.42032   validation_1-mlogloss:1.42366
[2] validation_0-mlogloss:1.00541   validation_1-mlogloss:1.00963
[4] validation_0-mlogloss:0.80557   validation_1-mlogloss:0.81109
[6] validation_0-mlogloss:0.69432   validation_1-mlogloss:0.70085
[8] validation_0-mlogloss:0.62653   validation_1-mlogloss:0.63350
[9] validation_0-mlogloss:0.60111   validation_1-mlogloss:0.60794</code></pre>
</div>
</div>
</section>
<section id="evaluating-the-model-1" class="level3">
<h3 class="anchored" data-anchor-id="evaluating-the-model-1">Evaluating the Model</h3>
<p>This time, we’ll keep the entire 2d array of predicted probabilities in <code>y_score</code>.</p>
<div id="cell-42" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1">y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> valid_df[target]</span>
<span id="cb33-2">y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clf.predict(valid_df[features])</span>
<span id="cb33-3">y_score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clf.predict_proba(valid_df[features])</span>
<span id="cb33-4">y_true.shape, y_pred.shape, y_score.shape</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="20">
<pre><code>((20000,), (20000,), (20000, 7))</code></pre>
</div>
</div>
<div id="cell-43" class="cell" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1">metrics.accuracy_score(y_true, y_pred)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="21">
<pre><code>0.77425</code></pre>
</div>
</div>
<div id="cell-44" class="cell" data-execution_count="22">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(metrics.classification_report(y_true, y_pred))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>              precision    recall  f1-score   support

           0       0.77      0.74      0.75      7365
           1       0.78      0.84      0.81      9725
           2       0.75      0.85      0.80      1207
           3       0.82      0.78      0.80        85
           4       0.93      0.26      0.40       317
           5       0.76      0.31      0.44       627
           6       0.88      0.68      0.77       674

    accuracy                           0.77     20000
   macro avg       0.81      0.64      0.68     20000
weighted avg       0.78      0.77      0.77     20000
</code></pre>
</div>
</div>
<p>Some binary classification metrics, like AUC, can be extended to the multi-class setting by computing the metric for each class, then averaging in some way to get an overall score. The details are controlled by the <code>average</code> and <code>multi_class</code> parameters, which are described in the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score">documentation</a>.</p>
<div id="cell-46" class="cell" data-execution_count="23">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb39-1">metrics.roc_auc_score(y_true, y_score, average<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'weighted'</span>, multi_class<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ovr'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="23">
<pre><code>0.9129422094408693</code></pre>
</div>
</div>
</section>
<section id="feature-importance-1" class="level3">
<h3 class="anchored" data-anchor-id="feature-importance-1">Feature Importance</h3>
<p>We can compute permutation feature importance with exactly the same code that we used for the binary classifier.</p>
<div id="cell-48" class="cell" data-execution_count="24">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb41-1">scorer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_scorer(metrics.log_loss, greater_is_better<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, needs_proba<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb41-2">permu_imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> permutation_importance(clf, valid_df[features], valid_df[target], </span>
<span id="cb41-3">                                   n_repeats<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, scoring<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>scorer)</span></code></pre></div></div>
</div>
<div id="cell-49" class="cell" data-execution_count="25">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb42-1">importances_permutation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.Series(permu_imp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'importances_mean'</span>], index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>features)</span>
<span id="cb42-2">importances_permutation.sort_values(ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>:].plot.barh()</span>
<span id="cb42-3">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Permutation Importance on Out-of-Sample Set'</span>)</span>
<span id="cb42-4">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'change in multivariate log likelihood'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-for-classification-in-python_files/figure-html/cell-26-output-1.png" class="img-fluid figure-img" alt="horizontal bar plot showing permutation feature importance"></p>
<figcaption>top 10 features by permutation importance on validation set</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="partial-dependence-1" class="level3">
<h3 class="anchored" data-anchor-id="partial-dependence-1">Partial Dependence</h3>
<p>Recall that partial dependence reflects how the expected model output changes with a particular feature. In the multi-class setting, the model has multiple outputs—one probability for each class—so we need to choose which class probability to show in the plots. We choose the target class with the <code>target</code> parameter; be sure to pass in the encoded value, e.g.&nbsp;we need to use the label encoder to transform a raw class label back into the encoded value. Here we’ll examine partial dependence for the probability of cover type 3.</p>
<div id="cell-51" class="cell" data-execution_count="26">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1">PartialDependenceDisplay.from_estimator(clf, </span>
<span id="cb43-2">                                        X<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[features], </span>
<span id="cb43-3">                                        features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Elevation'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Horizontal_Distance_To_Roadways'</span>], </span>
<span id="cb43-4">                                        target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>enc.transform([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-for-classification-in-python_files/figure-html/cell-27-output-1.png" class="img-fluid figure-img" alt="line plots showing partial dependence of probability of cover type 3 vs two features"></p>
<figcaption>PDP of target probability of cover type == 3 vs elevation and distance to roadway</figcaption>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Well, for me, those are really the minimal nuts and bolts one needs to get XGBoost models working on classification problems. If you dig this tutorial, or if you have additional insights into using XGBoost to solve classification problems, let me know about it down in the comments!</p>
</section>
<section id="go-deeper" class="level2">
<h2 class="anchored" data-anchor-id="go-deeper">Go Deeper</h2>
<p>If you’re feeling like Alice, and you want to go tumbling down the rabbit hole, might I recommend checking out some of the following:</p>
<ul>
<li><a href="../../posts/xgboost-explained/">XGBoost Explained</a> - for a deep dive into the math</li>
<li><a href="../../posts/xgboost-from-scratch/">XGBoost from Scratch</a> - to see how to implement all those equations in code</li>
<li><a href="../../posts/gradient-boosting-multi-class-classification-from-scratch/">Multi-Class Gradient Boosting from Scratch</a> - to fully grok the multi-class gradient boosting algorithm</li>
</ul>


</section>

 ]]></description>
  <category>python</category>
  <category>tutorial</category>
  <category>gradient boosting</category>
  <category>xgboost</category>
  <guid>https://randomrealizations.com/posts/xgboost-for-classification-in-python/</guid>
  <pubDate>Tue, 28 Nov 2023 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/xgboost-for-classification-in-python/xgboost-classification-thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Gradient Boosting Multi-Class Classification from Scratch</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/gradient-boosting-multi-class-classification-from-scratch/</link>
  <description><![CDATA[ 





<p>Tell me dear reader, who among us, while gazing in wonder at the improbably verdant aloe vera clinging to the windswept rock at Cape Point near the southern tip of Africa, hasn’t wondered: how the heck do gradient boosting trees implement multi-class classification? Today, we’ll unravel this mystery by reviewing the theory and implementing the algorithm for ourselves in python. Specifically, we’ll review the multi-class gradient boosting model originally described in <a href="https://statweb.stanford.edu/~jhf/ftp/trebst.pdf">Friedman’s classic Greedy Function Approximation paper</a>, and we’ll implement components of the algorithm as we go along. Once we have all the pieces, we’ll write a python class for multi-class gradient boosting with a similar API to the scikit-learn <code>GradientBoostingClassifier</code>.</p>
<p>If you need a refresher on gradient boosting before diving in here, then start with my original <a href="../../posts/gradient-boosting-machine-from-scratch/">gradient boosting from scratch post</a>, which is the first installment in my ongoing <a href="../../gradient-boosting-series/">series on gradient boosting</a>.</p>
<section id="the-multi-class-gradient-boosting-classification-algorithm" class="level2">
<h2 class="anchored" data-anchor-id="the-multi-class-gradient-boosting-classification-algorithm">The multi-class gradient boosting classification algorithm</h2>
<p>Friedman describes the algorithm for training a multi-class classification gradient boosting model in Algorithm 6 of the <a href="(https://statweb.stanford.edu/~jhf/ftp/trebst.pdf)">classic Greedy Function Approximation paper</a>. If you want a step-by-step walkthrough of the ideas in the paper, have a look at my post on <a href="../../posts/gradient-boosting-machine-with-any-loss-function/">the generalized gradient boosting algorithm</a>. In high-level terms, the algorithm for multi-class gradient boosting is:</p>
<ol type="1">
<li><p>Set the initial model predictions.</p></li>
<li><p>Repeat the following for each boosting round.</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; Repeat the following for each class.</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; Compute the pseudo residuals.</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; Train a regression tree to predict the pseudo residuals.</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; Adjust the tree’s predicted values to optimize the objective function.</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; Add the new tree to the current composite model.</p></li>
</ol>
<p>Let’s take a look at the details for each of these steps.</p>
</section>
<section id="target-variable-encoding" class="level2">
<h2 class="anchored" data-anchor-id="target-variable-encoding">Target variable encoding</h2>
<p>Following the convention in scikit-learn, when training a multi-class classifier, the target variable in the training dataset should be integer encoded so that the <img src="https://latex.codecogs.com/png.latex?K"> distinct classes are mapped to the integers <img src="https://latex.codecogs.com/png.latex?0,1,%5Cdots,K-1">. In the code for model training, however, it’s going to be more convenient to work with a one hot encoded representation of the target. Therefore we’ll start by writing an internal method to transform the target variable from integer encoding to one hot encoding. Remember that eventually we’ll write a class for our multi-class gradient boosting model, so I’ll write this function like a class method with a leading argument called <code>self</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd </span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> OneHotEncoder</span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _one_hot_encode_labels(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y):</span>
<span id="cb1-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(y, pd.Series): y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.values</span>
<span id="cb1-7">    ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> OneHotEncoder()</span>
<span id="cb1-8">    y_ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ohe.fit_transform(y.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)).toarray()</span>
<span id="cb1-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y_ohe</span></code></pre></div></div>
<p>This code takes the integer-encoded target variable, makes sure it’s a numpy array, then uses cikit-learn’s one hot encoder to encode it as a 2D array with observations along the first axis and classes along the second axis. I tend to think of the one hot encoded output as a matrix with <img src="https://latex.codecogs.com/png.latex?n"> rows (the number of observations in the training data) and <img src="https://latex.codecogs.com/png.latex?K"> columns (the number of classes), although it’s technically not a matrix but rather a 2D array.</p>
</section>
<section id="model-predictions-in-raw-space-and-probability-space" class="level2">
<h2 class="anchored" data-anchor-id="model-predictions-in-raw-space-and-probability-space">Model predictions in raw space and probability space</h2>
<p>In amulti-class classification problem with <img src="https://latex.codecogs.com/png.latex?K"> classes, the model prediction for a particular observation returns a list of <img src="https://latex.codecogs.com/png.latex?K"> probabilities, one for each class. Essentially the model prediction is a conditional probability mass function for the discrete target variable, conditioned on the feature values.</p>
<p>So, we need a way to ensure that the model output is a valid probability mass function, i.e.&nbsp;each probability is in (0, 1) and the <img src="https://latex.codecogs.com/png.latex?K"> class probabilities sum to 1. Analogous to logistic regression, we can accomplish this by using the model to first make a raw prediction which can be any real number, then using something like the inverse logit function to transform the raw model prediction into a number between 0 and 1 that can be interpreted as a probability. Again analogous to logistic regression, in the multi-class setting we use <img src="https://latex.codecogs.com/png.latex?K"> different models, one for each class, to generate the raw predictions, then we transform the raw model predictions into probabilities using the softmax function,, which takes a length-<img src="https://latex.codecogs.com/png.latex?K"> vector of real numbers as input and returns a probability mass function over <img src="https://latex.codecogs.com/png.latex?K"> discrete classes.</p>
<p>Let <img src="https://latex.codecogs.com/png.latex?%5C%7BF_1(%5Cmathbf%7Bx%7D),%5Cdots,F_K(%5Cmathbf%7Bx%7D)%5C%7D=%5C%7BF_k(%5Cmathbf%7Bx%7D)%5C%7D_1%5EK"> be the list of <img src="https://latex.codecogs.com/png.latex?K"> raw model outputs, and let <img src="https://latex.codecogs.com/png.latex?%5C%7Bp_1(%5Cmathbf%7Bx%7D),%5Cdots,p_K(%5Cmathbf%7Bx%7D)%5C%7D=%5C%7Bp_k(%5Cmathbf%7Bx%7D)%5C%7D_1%5EK"> be the corresponding probability mass function over the <img src="https://latex.codecogs.com/png.latex?K"> classes, then the softmax function is defined as</p>
<p><img src="https://latex.codecogs.com/png.latex?%20p_k(%5Cmathbf%7Bx%7D)%20=%20%5Ctext%7Bsoftmax%7D_k(%5C%7BF_k(%5Cmathbf%7Bx%7D)%5C%7D_1%5EK)%0A%20%20%20%20=%20%5Cfrac%7Be%5E%7BF_k(%5Cmathbf%7Bx%7D)%7D%7D%7B%5Csum_%7Bl=1%7D%5EK%20e%5E%7BF_l(%5Cmathbf%7Bx%7D)%7D%7D"></p>
<pre><code>Let's implement an internal softmax method that transforms the raw predictions into probabilities.</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _softmax(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, raw_predictions):</span>
<span id="cb3-2">    numerator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(raw_predictions) </span>
<span id="cb3-3">    denominator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(np.exp(raw_predictions), axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> numerator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> denominator</span></code></pre></div></div>
</section>
<section id="initial-model-predictions" class="level2">
<h2 class="anchored" data-anchor-id="initial-model-predictions">Initial model predictions</h2>
<p>We’re now ready to implement model training, starting with line 1 of the algorithm which sets the initial model predictions. In our code, we’ll keep the raw model predictions <img src="https://latex.codecogs.com/png.latex?%5C%7BF_k(%5Cmathbf%7Bx%7D)%5C%7D_1%5EK"> for the <img src="https://latex.codecogs.com/png.latex?n"> observations in the training dataset in a size <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20K"> array called <code>raw_predictions</code>, and we’ll keep the corresponding probabilities <img src="https://latex.codecogs.com/png.latex?%5C%7Bp_k(%5Cmathbf%7Bx%7D)%5C%7D_1%5EK"> in another <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20K"> array called <code>probabilities</code>. Perhaps the simplest reasonable initialization is to set the probabilities to <img src="https://latex.codecogs.com/png.latex?1/K">, i.e.&nbsp;<img src="https://latex.codecogs.com/png.latex?p_k(%5Cmathbf%7Bx%7D)=1/K">, which implies <img src="https://latex.codecogs.com/png.latex?F_k(%5Cmathbf%7Bx%7D)=0">.</p>
<p>We’ll go ahead and create that one hot encoded representation of the target, then use it to set the right size for the model prediction arrays.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">y_ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._one_hot_encode_labels(y)</span>
<span id="cb4-2">raw_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_ohe.shape)</span>
<span id="cb4-3">probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._softmax(raw_predictions)</span></code></pre></div></div>
</section>
<section id="boosting" class="level2">
<h2 class="anchored" data-anchor-id="boosting">Boosting</h2>
<p>Line 2 of the algorithm kicks off a loop to iteratively perform boosting rounds. Within each round, line 3 specifies that we iterate through each of the <img src="https://latex.codecogs.com/png.latex?K"> classes, adding a new booster model for each class at each boosting round. We’ll keep all the boosters in a list called <code>boosters</code>, where each element is itself a list which we’ll call <code>class_trees</code> that contains the <img src="https://latex.codecogs.com/png.latex?K"> trees we trained in a given boosting round. For each round and each class, we compute the pseudo residuals (negative gradients), train a decision tree to predict them, update the tree’s predicted values to optimize the overall objective function, then update the current raw and probability predictions before storing the new tree in that round’s list of class trees.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb5-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> m <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_estimators):</span>
<span id="cb5-3">    class_trees <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb5-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_classes):</span>
<span id="cb5-5">        negative_gradients <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._negative_gradients(y_ohe[:, k], probabilities[:, k])</span>
<span id="cb5-6">        hessians <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._hessians(probabilities[:, k])</span>
<span id="cb5-7">        tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTreeRegressor(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth)</span>
<span id="cb5-8">        tree.fit(X, negative_gradients)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._update_terminal_nodes(tree, X, negative_gradients, hessians)</span>
<span id="cb5-10">        raw_predictions[:, k] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tree.predict(X)</span>
<span id="cb5-11">        probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._softmax(raw_predictions)</span>
<span id="cb5-12">        class_trees.append(tree)</span>
<span id="cb5-13">    <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters.append(class_trees)</span></code></pre></div></div>
<p>Next we’ll dive into the details of the pseudo residual computation and the adjustment to the tree booster predicted values.</p>
</section>
<section id="pseudo-residuals" class="level2">
<h2 class="anchored" data-anchor-id="pseudo-residuals">Pseudo Residuals</h2>
<p>For each observation in the training dataset, the pseudo residual is the negative gradient of the objective function with respect to the corresponding model prediction. The objective function for multi-class classification is the Multinomial Negative Log Likelihood. For a single observation, the objective is</p>
<p><img src="https://latex.codecogs.com/png.latex?%20J(%5C%7B%20y_k,%20p_k(%5Cmathbf%7Bx%7D)%20%5C%7D_1%5EK)%20=%20-%5Csum_%7Bk=1%7D%5EK%20y_k%20%5Clog%20p_k(%5Cmathbf%7Bx%7D)%20"></p>
<p>We can rewrite the objective in terms of our raw model output <img src="https://latex.codecogs.com/png.latex?F"> like this.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20J(%5C%7B%20y_k,%20F_k(%5Cmathbf%7Bx%7D)%20%5C%7D_1%5EK)%20=%20-%5Csum_%7Bk=1%7D%5EK%20y_k%20%5Clog%20%5Cfrac%7Be%5E%7BF_k(%5Cmathbf%7Bx%7D)%7D%7D%7B%5Csum_%7Bl=1%7D%5EK%20e%5E%7BF_l(%5Cmathbf%7Bx%7D)%7D%7D"></p>
<p>The negative gradient of the objective with respect to raw model prediction <img src="https://latex.codecogs.com/png.latex?F_k(%5Cmathbf%7Bx%7D_i)"> for training example <img src="https://latex.codecogs.com/png.latex?i"> is given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%20r_%7Bik%7D%20=%20-J'(F_k(%5Cmathbf%7Bx%7D_i))%20=%20-%5Cleft%5B%20%5Cfrac%7B%5Cpartial%20J(%5C%7B%20y_%7Bil%7D,%20F_l(%5Cmathbf%7Bx_i%7D)%5C%7D_%7Bl=1%7D%5EK)%7D%7B%5Cpartial%20F_k(%5Cmathbf%7Bx%7D_i)%20%7D%20%5Cright%5D%0A=y_%7Bik%7D%20-%20p_%7Bk%7D(%5Cmathbf%7Bx%7D_i)"></p>
<p>You can take a look at the <a href="https://towardsdatascience.com/derivative-of-the-softmax-function-and-the-categorical-cross-entropy-loss-ffceefc081d1">derivation</a> if you’re curious how to work it out yourself. Note that this formula has a nice intuition. When <img src="https://latex.codecogs.com/png.latex?y_%7Bik%7D=1">, if predicted probability <img src="https://latex.codecogs.com/png.latex?p_k(%5Cmathbf%7Bx%7D_i)"> is terrible and close to 0, then the pseudo residual will be positive, and the next boosting round will try to increase the predicted probability. Otherwise if the predicted probability is already good and close to 1, the pseudo residual will be close to 0 and the next boosting round won’t change the predicted probability very much.</p>
<p>We can easily implement an internal method to compute the negative gradients over the training dataset as follows.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _negative_gradients(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y_ohe, probabilities):</span>
<span id="cb6-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y_ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> probabilities</span></code></pre></div></div>
</section>
<section id="adjusting-the-trees-predicted-values" class="level2">
<h2 class="anchored" data-anchor-id="adjusting-the-trees-predicted-values">Adjusting the trees’ predicted values</h2>
<p>After training a regression tree to predict the pseudo residuals, we need to adjust the predicted values in its terminal nodes to optimize the overall objective function. In the Greedy Function Approximation paper, Friedman actually specifies finding the optimal value using a numerical optimization routine like line search. We could express that like</p>
<p><img src="https://latex.codecogs.com/png.latex?%20v%20=%20%5Ctext%7Bargmin%7D_v%20%5Csum_%7Bi%20%5Cin%20t%7D%20J(y_%7Bi%7D,%20F(%5Cmathbf%7Bx%7D_i)%20+%20v)%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?t"> is the set of samples falling into this terminal node.</p>
<p>In the scikit-learn implementation of gradient boosting classification, the authors instead use the approach from <a href="https://www.researchgate.net/publication/228776646_Additive_Logistic_Regression_A_Statistical_View_of_Boosting">FHT00</a> which uses a single Newton descent step to approximate the optimal predicted value for each terminal node. See code and comments for the function <code>_update_terminal_regions</code> in the scikit-learn gradient boosting module. The updated value is computed like</p>
<p><img src="https://latex.codecogs.com/png.latex?%20v%20=%20-%5Cfrac%7B%5Csum_%7Bi%20%5Cin%20t%7D%20J'(F(%5Cmathbf%7Bx%7D_i))%7D%7B%5Csum_%7Bi%20%5Cin%20t%7D%20J''(F(%5Cmathbf%7Bx%7D_i))%7D%20"></p>
<p>We already found the first derivative of the objective, so we just need to calculate the second derivative.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20J''(F_k(%5Cmathbf%7Bx%7D_i))%20=%0A%5Cleft%5B%20%5Cfrac%7B%5Cpartial%20J(%5C%7B%20y_%7Bil%7D,%20F_l(%5Cmathbf%7Bx_i%7D)%5C%7D_%7Bl=1%7D%5EK)%7D%7B%5Cpartial%20%5E2%20F_k(%5Cmathbf%7Bx%7D_i)%20%7D%20%5Cright%5D%0A=%20p_k(%5Cmathbf%7Bx%7D_i)%20(1%20-%20p_k(%5Cmathbf%7Bx%7D_i))%0A"></p>
<p>Here’s the internal method to compute the second derivative .</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _hessians(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, probabilities): </span>
<span id="cb7-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> probabilities)</span></code></pre></div></div>
<p>Then we can implement the internal method for updating the tree predicted values. I give more details about how to manually set scikit-learn’s decision tree predicted values in <a href="../../posts/gradient-boosting-machine-with-any-loss-function/">the post on gradient boosting with any loss function</a>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _update_terminal_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, tree, X, negative_gradients, hessians):</span>
<span id="cb8-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Update the terminal node predicted values'''</span></span>
<span id="cb8-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># terminal node id's</span></span>
<span id="cb8-4">    leaf_nodes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(tree.tree_.children_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb8-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># compute leaf for each sample in ``X``.</span></span>
<span id="cb8-6">    leaf_node_for_each_sample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tree.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">apply</span>(X)</span>
<span id="cb8-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> leaf <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> leaf_nodes:</span>
<span id="cb8-8">        samples_in_this_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.where(leaf_node_for_each_sample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> leaf)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb8-9">        negative_gradients_in_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> negative_gradients.take(samples_in_this_leaf, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb8-10">        hessians_in_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> hessians.take(samples_in_this_leaf, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb8-11">        val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(negative_gradients_in_leaf) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(hessians_in_leaf)</span>
<span id="cb8-12">        tree.tree_.value[leaf, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> val</span></code></pre></div></div>
</section>
<section id="prediction" class="level2">
<h2 class="anchored" data-anchor-id="prediction">Prediction</h2>
<p>At inference time, the user supplies an <code>X</code> with multiple observations of the feature variables, and our model needs to issue a prediction for each observation. We’ll start by implementing the <code>predict_proba</code> method, which takes <code>X</code> as input and returns a length-<img src="https://latex.codecogs.com/png.latex?K"> probability mass function for each observation in <code>X</code>. To do this, we’ll initialize the raw predictions with zeros, just as we did in training, and then for each class, we’ll loop through all the boosters, collecting their predictions on <code>X</code>, scaling by the learning rate, and summing them up. Finally, we use the softmax to transform raw predictions into the probabilities.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict_proba(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb9-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Generate probability predictions for the given input data.'''</span></span>
<span id="cb9-3">    raw_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>  np.zeros(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_classes))</span>
<span id="cb9-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_classes):</span>
<span id="cb9-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> booster <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters:</span>
<span id="cb9-6">            raw_predictions[:, k] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> booster[k].predict(X)</span>
<span id="cb9-7">    probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._softmax(raw_predictions)</span>
<span id="cb9-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> probabilities</span></code></pre></div></div>
<p>Then to get the predicted labels, we can use the <code>predict_proba</code> method to generate probabilities, simply returning the integer-encoded class label of the largest probability for each observation in <code>X</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb10-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Generate predicted labels (as integer-encoded array)'''</span></span>
<span id="cb10-3">    probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.predict_proba(X)</span>
<span id="cb10-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.argmax(probabilities, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</section>
<section id="the-complete-multi-class-gradient-boosting-classification-model-implementation" class="level2">
<h2 class="anchored" data-anchor-id="the-complete-multi-class-gradient-boosting-classification-model-implementation">The complete multi-class gradient boosting classification model implementation</h2>
<p>Now we’re ready to implement a multi-class classification gradient boosting model class with public <code>fit</code>, <code>predict_proba</code>, and <code>predict</code> methods. We combine the components above into a <code>fit</code> method for model training, and we add the two prediction methods to complete the model’s functionality.</p>
<div id="cell-11" class="cell" data-execution_count="29">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb11-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd </span>
<span id="cb11-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.tree <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> DecisionTreeRegressor </span>
<span id="cb11-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> OneHotEncoder</span>
<span id="cb11-5"></span>
<span id="cb11-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> GradientBoostingClassifierFromScratch():</span>
<span id="cb11-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Gradient Boosting Classifier from Scratch.</span></span>
<span id="cb11-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    </span></span>
<span id="cb11-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb11-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb11-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    n_estimators : int</span></span>
<span id="cb11-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        number of boosting rounds</span></span>
<span id="cb11-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        </span></span>
<span id="cb11-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    learning_rate : float</span></span>
<span id="cb11-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        learning rate hyperparameter</span></span>
<span id="cb11-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        </span></span>
<span id="cb11-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    max_depth : int</span></span>
<span id="cb11-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        maximum tree depth</span></span>
<span id="cb11-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb11-20">    </span>
<span id="cb11-21">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, n_estimators, learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb11-22">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> </span>
<span id="cb11-23">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>learning_rate</span>
<span id="cb11-24">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb11-25">    </span>
<span id="cb11-26">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fit(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, y):</span>
<span id="cb11-27">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Fit the GBM</span></span>
<span id="cb11-28"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        </span></span>
<span id="cb11-29"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Parameters</span></span>
<span id="cb11-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        ----------</span></span>
<span id="cb11-31"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        X : ndarray of size (number observations, number features)</span></span>
<span id="cb11-32"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            design matrix</span></span>
<span id="cb11-33"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            </span></span>
<span id="cb11-34"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        y : ndarray of size (number observations,)</span></span>
<span id="cb11-35"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            integer-encoded target labels in {0,1,...,k-1}</span></span>
<span id="cb11-36"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        '''</span></span>
<span id="cb11-37">        </span>
<span id="cb11-38">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_classes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.Series(y).nunique()</span>
<span id="cb11-39">        y_ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._one_hot_encode_labels(y)</span>
<span id="cb11-40"></span>
<span id="cb11-41">        raw_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_ohe.shape)</span>
<span id="cb11-42">        probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._softmax(raw_predictions)</span>
<span id="cb11-43">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb11-44">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> m <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_estimators):</span>
<span id="cb11-45">            class_trees <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb11-46">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_classes):</span>
<span id="cb11-47">                negative_gradients <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._negative_gradients(y_ohe[:, k], probabilities[:, k])</span>
<span id="cb11-48">                hessians <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._hessians(probabilities[:, k])</span>
<span id="cb11-49">                tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTreeRegressor(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth)</span>
<span id="cb11-50">                tree.fit(X, negative_gradients)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb11-51">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._update_terminal_nodes(tree, X, negative_gradients, hessians)</span>
<span id="cb11-52">                raw_predictions[:, k] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tree.predict(X)</span>
<span id="cb11-53">                probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._softmax(raw_predictions)</span>
<span id="cb11-54">                class_trees.append(tree)</span>
<span id="cb11-55">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters.append(class_trees)</span>
<span id="cb11-56">    </span>
<span id="cb11-57">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _one_hot_encode_labels(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y):</span>
<span id="cb11-58">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(y, pd.Series): y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.values</span>
<span id="cb11-59">        ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> OneHotEncoder()</span>
<span id="cb11-60">        y_ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ohe.fit_transform(y.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)).toarray()</span>
<span id="cb11-61">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y_ohe</span>
<span id="cb11-62">        </span>
<span id="cb11-63">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _negative_gradients(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y_ohe, probabilities):</span>
<span id="cb11-64">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y_ohe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> probabilities</span>
<span id="cb11-65">    </span>
<span id="cb11-66">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _hessians(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, probabilities): </span>
<span id="cb11-67">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> probabilities)</span>
<span id="cb11-68"></span>
<span id="cb11-69">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _softmax(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, raw_predictions):</span>
<span id="cb11-70">        numerator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(raw_predictions) </span>
<span id="cb11-71">        denominator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(np.exp(raw_predictions), axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb11-72">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> numerator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> denominator</span>
<span id="cb11-73">        </span>
<span id="cb11-74">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _update_terminal_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, tree, X, negative_gradients, hessians):</span>
<span id="cb11-75">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Update the terminal node predicted values'''</span></span>
<span id="cb11-76">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># terminal node id's</span></span>
<span id="cb11-77">        leaf_nodes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(tree.tree_.children_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb11-78">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># compute leaf for each sample in ``X``.</span></span>
<span id="cb11-79">        leaf_node_for_each_sample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tree.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">apply</span>(X)</span>
<span id="cb11-80">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> leaf <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> leaf_nodes:</span>
<span id="cb11-81">            samples_in_this_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.where(leaf_node_for_each_sample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> leaf)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb11-82">            negative_gradients_in_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> negative_gradients.take(samples_in_this_leaf, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-83">            hessians_in_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> hessians.take(samples_in_this_leaf, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-84">            val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(negative_gradients_in_leaf) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(hessians_in_leaf)</span>
<span id="cb11-85">            tree.tree_.value[leaf, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> val</span>
<span id="cb11-86">          </span>
<span id="cb11-87">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict_proba(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb11-88">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Generate probability predictions for the given input data.'''</span></span>
<span id="cb11-89">        raw_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>  np.zeros(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_classes))</span>
<span id="cb11-90">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_classes):</span>
<span id="cb11-91">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> booster <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters:</span>
<span id="cb11-92">                raw_predictions[:, k] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> booster[k].predict(X)</span>
<span id="cb11-93">        probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._softmax(raw_predictions)</span>
<span id="cb11-94">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> probabilities</span>
<span id="cb11-95">        </span>
<span id="cb11-96">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb11-97">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Generate predicted labels (as 1-d array)'''</span></span>
<span id="cb11-98">        probabilities <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.predict_proba(X)</span>
<span id="cb11-99">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.argmax(probabilities, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</div>
</section>
<section id="testing-our-implementation" class="level2">
<h2 class="anchored" data-anchor-id="testing-our-implementation">Testing our implementation</h2>
<p>Let’s test our implementation alongside the scikit-learn <code>GradientBoostingClassifier</code> to ensure it works as expected.</p>
<div id="cell-13" class="cell" data-execution_count="24">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_classification</span>
<span id="cb12-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split</span>
<span id="cb12-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> accuracy_score</span>
<span id="cb12-4"></span>
<span id="cb12-5">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_classification(n_samples<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>, </span>
<span id="cb12-6">                           n_classes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, </span>
<span id="cb12-7">                           n_features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb12-8">                           n_informative<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb12-9">                           random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb12-10"></span>
<span id="cb12-11">X_train, X_test, y_train, y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(X, y, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
</div>
<div id="cell-14" class="cell" data-execution_count="35">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.ensemble <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> GradientBoostingClassifier</span>
<span id="cb13-2"></span>
<span id="cb13-3">gbc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingClassifier(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, </span>
<span id="cb13-4">                                 learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, </span>
<span id="cb13-5">                                 max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)</span>
<span id="cb13-6">gbc.fit(X_train, y_train)</span>
<span id="cb13-7">accuracy_score(y_test, gbc.predict(X_test))</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="35">
<pre><code>0.7756</code></pre>
</div>
</div>
<div id="cell-15" class="cell" data-execution_count="36">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1">gbcfs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingClassifierFromScratch(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, </span>
<span id="cb15-2">                                              learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, </span>
<span id="cb15-3">                                              max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)</span>
<span id="cb15-4">gbcfs.fit(X_train, y_train)</span>
<span id="cb15-5">accuracy_score(y_test, gbcfs.predict(X_test))</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="36">
<pre><code>0.7768</code></pre>
</div>
</div>
<p>Beautiful. Our implementation is performing comparably to the sklearn gradient boosting classifier!</p>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Well, there you have it, another epic scratch build for the books. I think the most interesting thing about the multi-class gradient boosting algorithm is that it generates multi-dimensional predictions based on a single objective function by training multiple decision trees in each boosting round. That’s a very interesting extension of the classic gradient boosting machine! If you have questions about the implementation, or if you found this post helpful, please leave a comment below to tell me about it.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li><a href="(https://statweb.stanford.edu/~jhf/ftp/trebst.pdf)">Friedman’s Greedy Function Approximation paper</a></li>
<li><a href="https://www.researchgate.net/publication/228776646_Additive_Logistic_Regression_A_Statistical_View_of_Boosting">Friedman, Hastie, and Tibshirani 2000: paper on additive logistic regression</a></li>
</ul>


</section>

 ]]></description>
  <category>python</category>
  <category>gradient boosting</category>
  <category>from scratch</category>
  <guid>https://randomrealizations.com/posts/gradient-boosting-multi-class-classification-from-scratch/</guid>
  <pubDate>Sun, 15 Oct 2023 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/gradient-boosting-multi-class-classification-from-scratch/multi-class-classification-from-scratch.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>XGBoost for Regression in Python</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/xgboost-for-regression-in-python/</link>
  <description><![CDATA[ 





<p>In this post I’m going to show you my process for solving regression problems with XGBoost in python, using either the native <code>xgboost</code> API or the scikit-learn interface. This is a powerful methodology that can produce world class results in a short time with minimal thought or effort. While we’ll be working on an old Kagle competition for predicting the sale prices of bulldozers and other heavy machinery, you can use this flow to solve whatever tabular data regression problem you’re working on.</p>
<p>This post serves as the explanation and documentation for the XGBoost regression jupyter notebook from my <a href="https://github.com/mcb00/ds-templates">ds-templates repo</a> on GitHub, so go ahead and download the notebook and follow along with your own data.</p>
<p>If you’re not already comfortable with the ideas behind gradient boosting and XGBoost, you’ll find it helpful to read some of my previous posts to get up to speed. I’d start with this <a href="../../posts/gradient-boosting-machine-from-scratch/">introduction to gradient boosting</a>, and then read this <a href="../../posts/xgboost-explained/">explanation of how XGBoost works</a>.</p>
<p>Let’s get into it! 🚀</p>
<section id="install-and-import-the-xgboost-library" class="level2">
<h2 class="anchored" data-anchor-id="install-and-import-the-xgboost-library">Install and import the <code>xgboost</code> library</h2>
<p>If you don’t already have it, go ahead and <a href="https://anaconda.org/conda-forge/xgboost">use conda to install the xgboost library</a>, e.g.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode .zsh code-with-copy"><code class="sourceCode zsh"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">$</span> conda install <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-c</span> conda-forge xgboost</span></code></pre></div></div>
<p>Then import it along with the usual suspects.</p>
<div id="cell-3" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb2-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb2-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb2-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> xgboost <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> xgb</span></code></pre></div></div>
</div>
</section>
<section id="read-dataset-into-python" class="level2">
<h2 class="anchored" data-anchor-id="read-dataset-into-python">Read dataset into python</h2>
<p>In this example we’ll work on the <a href="https://www.kaggle.com/competitions/bluebook-for-bulldozers/overview">Kagle Bluebook for Bulldozers</a> competition, which asks us to build a regression model to predict the sale price of heavy equipment. Amazingly, you can solve your own regression problem by swapping this data out with your organization’s data before proceeding with the tutorial.</p>
<p>Go ahead and download the <code>Train.zip</code> file from Kagle and extract it into <code>Train.csv</code>. Then read the data into a pandas dataframe.</p>
<div id="cell-5" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_csv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Train.csv'</span>, parse_dates<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate'</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</div>
<p>Notice I cheated a little bit, checking the columns ahead of time and telling pandas to treat the <code>saledate</code> column as a date. In general it will make life easier to read in any date-like columns as dates.</p>
<div id="cell-7" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">df.info()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt;
RangeIndex: 401125 entries, 0 to 401124
Data columns (total 53 columns):
 #   Column                    Non-Null Count   Dtype         
---  ------                    --------------   -----         
 0   SalesID                   401125 non-null  int64         
 1   SalePrice                 401125 non-null  int64         
 2   MachineID                 401125 non-null  int64         
 3   ModelID                   401125 non-null  int64         
 4   datasource                401125 non-null  int64         
 5   auctioneerID              380989 non-null  float64       
 6   YearMade                  401125 non-null  int64         
 7   MachineHoursCurrentMeter  142765 non-null  float64       
 8   UsageBand                 69639 non-null   object        
 9   saledate                  401125 non-null  datetime64[ns]
 10  fiModelDesc               401125 non-null  object        
 11  fiBaseModel               401125 non-null  object        
 12  fiSecondaryDesc           263934 non-null  object        
 13  fiModelSeries             56908 non-null   object        
 14  fiModelDescriptor         71919 non-null   object        
 15  ProductSize               190350 non-null  object        
 16  fiProductClassDesc        401125 non-null  object        
 17  state                     401125 non-null  object        
 18  ProductGroup              401125 non-null  object        
 19  ProductGroupDesc          401125 non-null  object        
 20  Drive_System              104361 non-null  object        
 21  Enclosure                 400800 non-null  object        
 22  Forks                     192077 non-null  object        
 23  Pad_Type                  79134 non-null   object        
 24  Ride_Control              148606 non-null  object        
 25  Stick                     79134 non-null   object        
 26  Transmission              183230 non-null  object        
 27  Turbocharged              79134 non-null   object        
 28  Blade_Extension           25219 non-null   object        
 29  Blade_Width               25219 non-null   object        
 30  Enclosure_Type            25219 non-null   object        
 31  Engine_Horsepower         25219 non-null   object        
 32  Hydraulics                320570 non-null  object        
 33  Pushblock                 25219 non-null   object        
 34  Ripper                    104137 non-null  object        
 35  Scarifier                 25230 non-null   object        
 36  Tip_Control               25219 non-null   object        
 37  Tire_Size                 94718 non-null   object        
 38  Coupler                   213952 non-null  object        
 39  Coupler_System            43458 non-null   object        
 40  Grouser_Tracks            43362 non-null   object        
 41  Hydraulics_Flow           43362 non-null   object        
 42  Track_Type                99153 non-null   object        
 43  Undercarriage_Pad_Width   99872 non-null   object        
 44  Stick_Length              99218 non-null   object        
 45  Thumb                     99288 non-null   object        
 46  Pattern_Changer           99218 non-null   object        
 47  Grouser_Type              99153 non-null   object        
 48  Backhoe_Mounting          78672 non-null   object        
 49  Blade_Type                79833 non-null   object        
 50  Travel_Controls           79834 non-null   object        
 51  Differential_Type         69411 non-null   object        
 52  Steering_Controls         69369 non-null   object        
dtypes: datetime64[ns](1), float64(2), int64(6), object(44)
memory usage: 162.2+ MB</code></pre>
</div>
</div>
</section>
<section id="prepare-raw-data-for-xgboost" class="level2">
<h2 class="anchored" data-anchor-id="prepare-raw-data-for-xgboost">Prepare raw data for XGBoost</h2>
<p>When faced with a new tabular dataset for modeling, we have two format considerations: data types and missingness. From the call to <code>df.info()</code> above, we can see we have both mixed types and missing values.</p>
<p>When it comes to missing values, some models like the gradient booster or random forest in scikit-learn require purely non-missing inputs. One of the great strengths of XGBoost is that it relaxes this requirement, allowing us to pass in missing feature values, so we don’t have to worry about them.</p>
<p>Regarding data types, all ML models for tabular data require inputs to be numeric, either integers or floats, so we’re going to have to deal with those <code>object</code> columns.</p>
<section id="encode-string-features" class="level3">
<h3 class="anchored" data-anchor-id="encode-string-features">Encode string features</h3>
<p>The simplest way to encode string variables is to map each unique string value to an integer; this is called <em>integer encoding</em>.</p>
<p>We can easily accomplish this by using the <a href="https://pandas.pydata.org/docs/user_guide/categorical.html">categorical data type in pandas</a>. The category type is a bit like the factor type in R; pandas stores the underlying data as integers, and it keeps a mapping from the integers back to the original string values. XGBoost is able to access the numeric data underlying the categorical features for model training and prediction. This is a nice way to encode string features because it’s easy to implement and it preserves the original category levels in the data frame. If you prefer to generate your own integer mappings, you can also do it with the scikit-learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html">OrdinalEncoder</a>.</p>
<div id="cell-10" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> encode_string_features(df):</span>
<span id="cb6-2">    out_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.copy()</span>
<span id="cb6-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> feature, feature_type <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> df.dtypes.items():</span>
<span id="cb6-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> feature_type <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'object'</span>:</span>
<span id="cb6-5">            out_df[feature] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> out_df[feature].astype(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'category'</span>)</span>
<span id="cb6-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out_df</span>
<span id="cb6-7"></span>
<span id="cb6-8">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> encode_string_features(df)</span></code></pre></div></div>
</div>
</section>
<section id="encode-date-and-timestamp-features" class="level3">
<h3 class="anchored" data-anchor-id="encode-date-and-timestamp-features">Encode date and timestamp features</h3>
<p>While dates feel sort of numeric, they are not quite numbers, so we need to transform them into numeric columns that XGBoost can understand. Unfortunately, encoding timestamps isn’t as straightforward as encoding strings, so we actually might need to engage in a little bit of feature engineering. A single date has many different attributes, e.g.&nbsp;days since epoch, year, quarter, month, day, day of year, day of week, is holiday, etc. Often a simple time index is the most useful information in a date column, so here we’ll just start by adding a feature that gives the number of days since some epoch date.</p>
<div id="cell-12" class="cell" data-execution_count="77">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate_days_since_epoch'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb7-2">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pd.Timestamp(year<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1970</span>, month<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, day<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb7-3">    ).dt.days</span></code></pre></div></div>
</div>
</section>
<section id="transform-the-target-if-necessary" class="level3">
<h3 class="anchored" data-anchor-id="transform-the-target-if-necessary">Transform the target if necessary</h3>
<p>In the interest of speed and efficiency, we didn’t bother doing any EDA with the feature data. Part of my justification for this is that trees are incredibly robust to outliers, colinearity, missingness, and other assorted nonsense in the feature data. However, they are not necessarily robust to nonsense in the target variable, so it’s worth having a look at it before proceeding any further.</p>
<div id="cell-14" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">df.SalePrice.hist()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'SalePrice'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-regression-in-python/index_files/figure-html/cell-7-output-1.png" class="img-fluid figure-img" alt="histogram of sale price showing right-skewed data"></p>
</figure>
</div>
</div>
</div>
<p>Often when predicting prices it makes sense to use log price, especially when they span multiple orders of magnitude or have a strong right skew. These data look pretty friendly, lacking outliers and exhibiting only a mild positive skew; we could probably get away without doing any transformation. But checking the evaluation metric used to score the Kagle competition, we see they’re using root mean squared log error. That’s equivalent to using RMSE on log-transformed target data, so let’s go ahead and work with log prices.</p>
<div id="cell-16" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'logSalePrice'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.log1p(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'SalePrice'</span>])</span>
<span id="cb9-2">df.logSalePrice.hist()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'logSalePrice'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-regression-in-python/index_files/figure-html/cell-8-output-1.png" class="img-fluid figure-img" alt="histogram of log sale price showing a more symetric distribution"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="train-and-evaluate-the-xgboost-regression-model" class="level2">
<h2 class="anchored" data-anchor-id="train-and-evaluate-the-xgboost-regression-model">Train and Evaluate the XGBoost regression model</h2>
<p>Having prepared our dataset, we are now ready to train an XGBoost model. Let’s walk through the flow step-by-step.</p>
<section id="split-the-data-into-training-and-validation-sets" class="level3">
<h3 class="anchored" data-anchor-id="split-the-data-into-training-and-validation-sets">Split the data into training and validation sets</h3>
<p>First we split the dataset into a training set and a validation set. Of course since we’re going to evaluate against the validation set a number of times as we iterate, it’s best practice to keep a separate test set reserved to check our final model to ensure it generalizes well. Assuming that final test set is hidden away, we can use the rest of the data for training and validation.</p>
<p>There are two main ways we might want to select the validation set. If there isn’t a temporal ordering of the observations, we might be able to randomly sample. In practice, it’s common that observations have a temporal ordering, and that models are trained on observations up to a certain time and used to predict on observations occuring after that time. Since this data is temporal, we don’t want to split randomly; instead we’ll split on observation date, reserving the latest observations for the validation set.</p>
<div id="cell-19" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Temporal Validation Set</span></span>
<span id="cb10-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> train_test_split_temporal(df, datetime_column, n_test):</span>
<span id="cb10-3">    idx_sort <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(df[datetime_column])</span>
<span id="cb10-4">    idx_train, idx_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> idx_sort[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n_valid], idx_sort[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n_valid:]</span>
<span id="cb10-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df.iloc[idx_train, :], df.iloc[idx_test, :]</span></code></pre></div></div>
</div>
<div id="cell-20" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">n_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12000</span></span>
<span id="cb11-2"></span>
<span id="cb11-3">train_df, valid_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split_temporal(df, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate'</span>, n_valid)</span>
<span id="cb11-4">train_df.shape, valid_df.shape</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="9">
<pre><code>((389125, 55), (12000, 55))</code></pre>
</div>
</div>
</section>
<section id="specify-target-and-feature-columns" class="level3">
<h3 class="anchored" data-anchor-id="specify-target-and-feature-columns">Specify target and feature columns</h3>
<p>Next we’ll put together a list of our features and define the target column. I like to have an actual list defined in the code so it’s easy to explicitly see everything we’re puting into the model and easier to add or remove features as we iterate. Just run something like <code>list(df.columns)</code> in a cel to get a copy-pasteable list of columns, then edit it down to the full list of features, i.e.&nbsp;remove the target, date columns, and other non-feature columns..</p>
<div id="cell-22" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#  list(df.columns)</span></span></code></pre></div></div>
</div>
<div id="cell-23" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb14-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'SalesID'</span>,</span>
<span id="cb14-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MachineID'</span>,</span>
<span id="cb14-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ModelID'</span>,</span>
<span id="cb14-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'datasource'</span>,</span>
<span id="cb14-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'auctioneerID'</span>,</span>
<span id="cb14-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'YearMade'</span>,</span>
<span id="cb14-8">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MachineHoursCurrentMeter'</span>,</span>
<span id="cb14-9">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'UsageBand'</span>,</span>
<span id="cb14-10">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiModelDesc'</span>,</span>
<span id="cb14-11">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiBaseModel'</span>,</span>
<span id="cb14-12">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiSecondaryDesc'</span>,</span>
<span id="cb14-13">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiModelSeries'</span>,</span>
<span id="cb14-14">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiModelDescriptor'</span>,</span>
<span id="cb14-15">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ProductSize'</span>,</span>
<span id="cb14-16">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fiProductClassDesc'</span>,</span>
<span id="cb14-17">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'state'</span>,</span>
<span id="cb14-18">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ProductGroup'</span>,</span>
<span id="cb14-19">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ProductGroupDesc'</span>,</span>
<span id="cb14-20">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Drive_System'</span>,</span>
<span id="cb14-21">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Enclosure'</span>,</span>
<span id="cb14-22">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Forks'</span>,</span>
<span id="cb14-23">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Pad_Type'</span>,</span>
<span id="cb14-24">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Ride_Control'</span>,</span>
<span id="cb14-25">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Stick'</span>,</span>
<span id="cb14-26">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Transmission'</span>,</span>
<span id="cb14-27">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Turbocharged'</span>,</span>
<span id="cb14-28">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Blade_Extension'</span>,</span>
<span id="cb14-29">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Blade_Width'</span>,</span>
<span id="cb14-30">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Enclosure_Type'</span>,</span>
<span id="cb14-31">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Engine_Horsepower'</span>,</span>
<span id="cb14-32">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Hydraulics'</span>,</span>
<span id="cb14-33">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Pushblock'</span>,</span>
<span id="cb14-34">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Ripper'</span>,</span>
<span id="cb14-35">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Scarifier'</span>,</span>
<span id="cb14-36">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Tip_Control'</span>,</span>
<span id="cb14-37">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Tire_Size'</span>,</span>
<span id="cb14-38">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Coupler'</span>,</span>
<span id="cb14-39">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Coupler_System'</span>,</span>
<span id="cb14-40">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Grouser_Tracks'</span>,</span>
<span id="cb14-41">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Hydraulics_Flow'</span>,</span>
<span id="cb14-42">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Track_Type'</span>,</span>
<span id="cb14-43">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Undercarriage_Pad_Width'</span>,</span>
<span id="cb14-44">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Stick_Length'</span>,</span>
<span id="cb14-45">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Thumb'</span>,</span>
<span id="cb14-46">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Pattern_Changer'</span>,</span>
<span id="cb14-47">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Grouser_Type'</span>,</span>
<span id="cb14-48">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Backhoe_Mounting'</span>,</span>
<span id="cb14-49">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Blade_Type'</span>,</span>
<span id="cb14-50">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Travel_Controls'</span>,</span>
<span id="cb14-51">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Differential_Type'</span>,</span>
<span id="cb14-52">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Steering_Controls'</span>,</span>
<span id="cb14-53">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate_days_since_epoch'</span></span>
<span id="cb14-54"> ]</span>
<span id="cb14-55"></span>
<span id="cb14-56">target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'logSalePrice'</span></span></code></pre></div></div>
</div>
</section>
<section id="create-dmatrix-data-objects" class="level3">
<h3 class="anchored" data-anchor-id="create-dmatrix-data-objects">Create <code>DMatrix</code> data objects</h3>
<p>XGBoost uses a data type called dense matrix for efficient training and prediction, so next we need to create <code>DMatrix</code> objects for our training and validation datasets. Remember how we decided to encode our string columns by casting them as pandas categorical types? For this to work, we need to set the <code>enable_categoricals</code> argument to <code>True</code>.</p>
<div id="cell-25" class="cell" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1">dtrain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[features], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>train_df[target], </span>
<span id="cb15-2">                     enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb15-3">dvalid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[features], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>valid_df[target], </span>
<span id="cb15-4">                     enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
</div>
</section>
<section id="set-the-xgboost-parameters" class="level3">
<h3 class="anchored" data-anchor-id="set-the-xgboost-parameters">Set the XGBoost parameters</h3>
<p>XGBoost has <a href="https://xgboost.readthedocs.io/en/latest/parameter.html">numerous hyperparameters</a>. Fortunately, just a handful of them tend to be the most influential; furthermore, the default values are not bad in most situations. I like to start out with a dictionary containing the default values for the parameters I’m most likely to adjust later, with one exception. I dislike the default value of <code>auto</code> for the <code>tree_method</code> parameter, which tells XGBoost to choose a tree method on it’s own. I’ve been burned by this ambiguity in the past, so now I prefer to set it to <code>approx</code>. For training there is one required boosting parameter called <code>num_boost_round</code> which I set to 50 as a starting point.</p>
<div id="cell-27" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># default values for important parameters</span></span>
<span id="cb16-2">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb16-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'approx'</span>,</span>
<span id="cb16-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>,</span>
<span id="cb16-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>,</span>
<span id="cb16-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb16-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb16-8">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'colsample_bynode'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb16-9">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'objective'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg:squarederror'</span>,</span>
<span id="cb16-10">}</span>
<span id="cb16-11">num_boost_round <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span></span></code></pre></div></div>
</div>
</section>
<section id="train-the-xgboost-model" class="level3">
<h3 class="anchored" data-anchor-id="train-the-xgboost-model">Train the XGBoost model</h3>
<p>The <code>xgb.train()</code> function takes our training dataset and parameters, and it returns a trained XGBoost model, which is an object of class <code>xgb.core.Booster</code>. Check out the <a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training">documentation on the learning API</a> to see all the training options. During training, I like to have XGBoost print out the evaluation metric on the train and validation set after every few boosting rounds and again at the end of training; that can be done by setting <code>evals</code> and <code>verbose_eval</code>.</p>
<div id="cell-29" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrain, num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round,</span>
<span id="cb17-2">                  evals<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(dtrain, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>), (dvalid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>)],</span>
<span id="cb17-3">                  verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0] train-rmse:6.74240  valid-rmse:6.80825
[10]    train-rmse:0.31071  valid-rmse:0.34532
[20]    train-rmse:0.21950  valid-rmse:0.24364
[30]    train-rmse:0.20878  valid-rmse:0.23669
[40]    train-rmse:0.20164  valid-rmse:0.23254
[49]    train-rmse:0.19705  valid-rmse:0.23125</code></pre>
</div>
</div>
</section>
<section id="train-the-xgboost-model-using-the-sklearn-interface" class="level3">
<h3 class="anchored" data-anchor-id="train-the-xgboost-model-using-the-sklearn-interface">Train the XGBoost model using the sklearn interface</h3>
<p>If you prefer scikit-learn-like syntax, you can use the <a href="https://xgboost.readthedocs.io/en/latest/python/sklearn_estimator.html">sklearn estimator interface</a> to create and train XGBoost models. The <code>XGBRegressor</code> class, which is available in the <code>xgboost</code> library that we already imported, constructs an <code>XGBRegressor</code> object with <code>fit</code> and <code>predict</code> methods like you’re used to using in scikit-learn. The <code>fit</code> and <code>predict</code> methods take pandas dataframes, so you don’t need to create <code>DMatrix</code> data objects yourself; however, since these methods still have to transform input data into <code>DMatrix</code> objects internally, training and prediction seem to be slower via the sklearn interface.</p>
<div id="cell-31" class="cell" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># scikit-learn interface</span></span>
<span id="cb19-2">reg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.XGBRegressor(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round, enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>params)</span>
<span id="cb19-3">reg.fit(train_df[features], train_df[target], </span>
<span id="cb19-4">        eval_set<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(train_df[features], train_df[target]), (valid_df[features], valid_df[target])], </span>
<span id="cb19-5">        verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0] validation_0-rmse:6.74240   validation_1-rmse:6.80825
[10]    validation_0-rmse:0.31071   validation_1-rmse:0.34532
[20]    validation_0-rmse:0.21950   validation_1-rmse:0.24364
[30]    validation_0-rmse:0.20878   validation_1-rmse:0.23669
[40]    validation_0-rmse:0.20164   validation_1-rmse:0.23254
[49]    validation_0-rmse:0.19705   validation_1-rmse:0.23125</code></pre>
</div>
</div>
<p>Since not all features of XGBoost are available through the scikit-learn estimator interface, you might want to get the native <code>xgb.core.Booster</code> object back out of the sklearn wrapper.</p>
<div id="cell-33" class="cell" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1">booster <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> reg.get_booster()</span></code></pre></div></div>
</div>
</section>
<section id="evaluate-the-xgboost-model-and-check-for-overfitting" class="level3">
<h3 class="anchored" data-anchor-id="evaluate-the-xgboost-model-and-check-for-overfitting">Evaluate the XGBoost model and check for overfitting</h3>
<p>We get the model evaluation metrics on the training and validation sets printed to stdout when we use the <code>evals</code> argument to the training API. Typically I just look at those printed metrics, but sometimes it’s helpful to retain them in a variable for further inspection via, e.g.&nbsp;plotting. To do that we need to train again, passing an empty dictionary to the <code>evals_result</code> argument. In the objective curves, I’m looking for signs of overfitting, which could include validation scores staying the same or getting worse over later iterations or huge gaps between training and validation scores.</p>
<div id="cell-35" class="cell" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1">evals_result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb22-2">model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>params, dtrain<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dtrain, num_boost_round<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round,</span>
<span id="cb22-3">                  evals<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(dtrain, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>), (dvalid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>)],</span>
<span id="cb22-4">                  verbose_eval<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb22-5">                  evals_result<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>evals_result)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[0] train-rmse:6.74240  valid-rmse:6.80825
[10]    train-rmse:0.31071  valid-rmse:0.34532
[20]    train-rmse:0.21950  valid-rmse:0.24364
[30]    train-rmse:0.20878  valid-rmse:0.23669
[40]    train-rmse:0.20164  valid-rmse:0.23254
[49]    train-rmse:0.19705  valid-rmse:0.23125</code></pre>
</div>
</div>
<div id="cell-36" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1">pd.DataFrame({</span>
<span id="cb24-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>: evals_result[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'train'</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rmse'</span>],</span>
<span id="cb24-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>: evals_result[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'valid'</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rmse'</span>]</span>
<span id="cb24-4">}).plot()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'boosting round'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'objective'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-regression-in-python/index_files/figure-html/cell-19-output-1.png" class="img-fluid figure-img" alt="line plot showing objective function versus training iteration for training and validation sets"></p>
<figcaption>These objective curves look pretty good–no obvious signs of trouble.</figcaption>
</figure>
</div>
</div>
</div>
<p>While we could just look at the validation RMSE in the printed output from model training, let’s go ahead and compute it by hand, just to be sure.</p>
<div id="cell-38" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> mean_squared_error</span>
<span id="cb25-2"></span>
<span id="cb25-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># squared=False returns RMSE</span></span>
<span id="cb25-4">mean_squared_error(y_true<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dvalid.get_label(), </span>
<span id="cb25-5">                   y_pred<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model.predict(dvalid), </span>
<span id="cb25-6">                   squared<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="19">
<pre><code>0.23124987</code></pre>
</div>
</div>
<p>So, how good is that RMSLE of 0.231? Well, checking the <a href="https://www.kaggle.com/competitions/bluebook-for-bulldozers/leaderboard">Kagle leaderboard</a> for this competition, we would have come in around 5th out of 474. That’s not bad for 10 minutes of work doing the bare minimum necessary to transform the raw data into a format consumable by XGBoost and then training a model using default hyperparameter values. To improve our model from here we would want to explore some feature engineering and some hyperparameter tuning, which we’ll save for another post.</p>
<blockquote class="blockquote">
<p>Wait, why was that so easy? Since XGBoost made it’s big Kagle debut in the <a href="https://www.kaggle.com/c/higgs-boson">2014 Higgs Boson competition</a>, presumably no one in this 2013 competition was using it yet. A second potential reason is that we’re using a different validation set from that used for the final leaderboard (which is long closed), but our score is likely still a decent approximation for how we would have done in the competition.</p>
</blockquote>
</section>
</section>
<section id="xgboost-model-interpretation" class="level2">
<h2 class="anchored" data-anchor-id="xgboost-model-interpretation">XGBoost Model Interpretation</h2>
<p>Next let’s have a look at how to apply a couple of the most common model interpretation techniques, feature importance and partial dependence, to XGBoost.</p>
<blockquote class="blockquote">
<p>Remember we have two trained models floating around: one called <code>model</code> of class <code>xgb.core.Booster</code> which is compatible with xgboost library utilities and another called <code>reg</code> of class <code>XGBRegressor</code> which is compatible with scikit-learn utilities. We need to be sure to use the model that’s compatible with whatever utility we’re using.</p>
</blockquote>
<blockquote class="blockquote">
<p>While these interpretation tools are still very common, there’s a newer, more comprehensive, and self-consistent model interpretation framework called <a href="https://shap.readthedocs.io/en/latest/">SHAP</a> that’s worth checking out.</p>
</blockquote>
<section id="feature-importance-for-xgboost" class="level3">
<h3 class="anchored" data-anchor-id="feature-importance-for-xgboost">Feature Importance for XGBoost</h3>
<p>While XGBoost automatically computes feature importance by three different metrics during training, you should only use them with great care and skepticism. The three metrics are</p>
<ul>
<li><strong>weight</strong>: the number of splits that use the feature</li>
<li><strong>gain</strong>: the average gain in the objective function from splits which use the feature</li>
<li><strong>cover</strong>: the average number of training samples affected by splits that use the feature</li>
</ul>
<p>The first problem with these metrics is that they are computed using only the training dataset, which means they don’t reflect how useful a feature is when predicting on out-of-sample data. If your model is overfit on some nonsense feature, it will still have a high importance. Secondly, I think they are difficult to interpret; all three are specific to decision trees and reflect domain-irrelevant idiosyncrasies like whether a feature is used nearer the root or the leaves of a tree. Anyway let’s see what these metrics have to say about our features.</p>
<div id="cell-42" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1">fig, (ax1, ax2, ax3) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>))</span>
<span id="cb27-2">xgb.plot_importance(model, importance_type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'weight'</span>, title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'importance_type=weight'</span>, </span>
<span id="cb27-3">                    max_num_features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, show_values<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax1, )</span>
<span id="cb27-4">xgb.plot_importance(model, importance_type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cover'</span>, title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'importance_type=cover'</span>, </span>
<span id="cb27-5">                    max_num_features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, show_values<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax2)</span>
<span id="cb27-6">xgb.plot_importance(model, importance_type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'gain'</span>, title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'importance_type=gain'</span>, </span>
<span id="cb27-7">                    max_num_features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, show_values<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax3)</span>
<span id="cb27-8">plt.tight_layout()</span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-regression-in-python/index_files/figure-html/cell-21-output-1.png" class="img-fluid figure-img" alt="three horizontal bar plots showing feature importance for weight, cover, and gain metrics"></p>
<figcaption>top 10 features according to each built-in XGBoost feature importance metric</figcaption>
</figure>
</div>
</div>
</div>
<p>Wow, notice that the top 10 features by weight and by cover are completely different. This should forever cause you to feel skeptical whenever you see a feature importance plot.</p>
<p>Luckily, there is a better way. IMHO, <a href="https://scikit-learn.org/stable/modules/permutation_importance.html">permutation feature importance</a> is better aligned with our intuition about what feature importance should mean. It tells us by how much the model performance decreases when the values of a particular feature are randomly shuffled during prediction. This effectively breaks the relationship between the feature and the target, thus revealing how much the model relies on that feature for prediction. It also has the benefit that it can be computed using either training data or out-of-sample data.</p>
<div id="cell-46" class="cell" data-execution_count="75">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.inspection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> permutation_importance</span>
<span id="cb28-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_scorer</span>
<span id="cb28-3"></span>
<span id="cb28-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># make a scorer for RMSE</span></span>
<span id="cb28-5">scorer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_scorer(mean_squared_error, squared<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb28-6">permu_imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> permutation_importance(reg, valid_df[features], valid_df[target], </span>
<span id="cb28-7">                                   n_repeats<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, scoring<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>scorer)</span></code></pre></div></div>
</div>
<div id="cell-47" class="cell" data-execution_count="76">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1">importances_permutation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.Series(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> permu_imp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'importances_mean'</span>], index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>features)</span>
<span id="cb29-2">importances_permutation.sort_values(ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>:].plot.barh()</span>
<span id="cb29-3">plt.title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Permutation Importance on Out-of-Sample Set'</span>)</span>
<span id="cb29-4">plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'drop in RMSE'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-regression-in-python/index_files/figure-html/cell-24-output-1.png" class="img-fluid figure-img" alt="horizontal bar plot showing permutation feature importance"></p>
<figcaption>top 10 features by permutation importance on validation set</figcaption>
</figure>
</div>
</div>
</div>
<p>Now we can see which features the model relies on most for out-of-sample predictions. These are good candidate features to dig into with some EDA and conversations with any domain expert collaborators.</p>
</section>
</section>
<section id="partial-dependence-plots-for-xgboost" class="level2">
<h2 class="anchored" data-anchor-id="partial-dependence-plots-for-xgboost">Partial Dependence Plots for XGBoost</h2>
<p>A <a href="https://scikit-learn.org/stable/modules/partial_dependence.html">partial dependence plot (PDP)</a> is a representation of the dependence between the target variable and one or more feature variables. We can loosely interpret it as showing how the expected value of the target changes across values of a particular feature, marginalizing over other features. I say “loosely” because it comes with caveats, a particularly serious one being that correlation among features tends to invalidate the above interpretation. Anyway, we can treat PDPs as useful heuristics for getting a sense of how a model thinks the target changes with feature values.</p>
<div id="cell-50" class="cell" data-execution_count="73">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.inspection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> PartialDependenceDisplay</span>
<span id="cb30-2"></span>
<span id="cb30-3">PartialDependenceDisplay.from_estimator(reg, </span>
<span id="cb30-4">                                        valid_df[features].query(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'YearMade &gt;= 1960'</span>), </span>
<span id="cb30-5">                                        [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'YearMade'</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-regression-in-python/index_files/figure-html/cell-25-output-1.png" class="img-fluid figure-img" alt="line plot showing partial dependence of logSalePrice on YearMade"></p>
<figcaption>PDP of target logSalePrice on feature YearMade</figcaption>
</figure>
</div>
</div>
</div>
<p>It looks like the log sale price tends to increase in a non-linear way with year made.</p>
<div id="cell-52" class="cell" data-execution_count="71">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># The PDPs for categorical features expect numeric data, not pandas categorical types,</span></span>
<span id="cb31-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># so the sklearn API for partial dependence won't work directly with the dataframe we've been using.</span></span>
<span id="cb31-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># The workaround is to create a new dataframe where categorical columns are encoded numerically,</span></span>
<span id="cb31-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># retrain the XGBoost model using the sklearn interface, create the PDPs,</span></span>
<span id="cb31-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># then add the category levels as the tick labels for the PDP.</span></span>
<span id="cb31-6"></span>
<span id="cb31-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cat_pdp():</span>
<span id="cb31-8">    cat_feature <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Enclosure'</span></span>
<span id="cb31-9">    modified_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.copy()</span>
<span id="cb31-10">    cat_codes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modified_df[cat_feature].cat.codes</span>
<span id="cb31-11">    cat_labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(modified_df[cat_feature].cat.categories)</span>
<span id="cb31-12">    cat_labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NaN'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> cat_labels <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cat_codes.unique() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> cat_labels</span>
<span id="cb31-13">    modified_df[cat_feature] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cat_codes</span>
<span id="cb31-14"></span>
<span id="cb31-15">    n_valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12000</span></span>
<span id="cb31-16">    train_df, valid_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split_temporal(modified_df, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'saledate'</span>, n_valid)</span>
<span id="cb31-17">    train_df.shape, valid_df.shape</span>
<span id="cb31-18"></span>
<span id="cb31-19">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># scikit-learn interface</span></span>
<span id="cb31-20">    reg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.XGBRegressor(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_boost_round, enable_categorical<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>params)</span>
<span id="cb31-21">    reg.fit(train_df[features], train_df[target], </span>
<span id="cb31-22">            eval_set<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[(train_df[features], train_df[target]), (valid_df[features], valid_df[target])], </span>
<span id="cb31-23">            verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb31-24">    PartialDependenceDisplay.from_estimator(reg, valid_df[features], [cat_feature], categorical_features<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[cat_feature])</span>
<span id="cb31-25">    plt.xticks(ticks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cat_codes.unique(), labels<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cat_labels)</span>
<span id="cb31-26">cat_pdp()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-for-regression-in-python/index_files/figure-html/cell-26-output-1.png" class="img-fluid figure-img" alt="bar plot showing partial dependence of logSalePrice on Enclosure"></p>
<figcaption>PDP of target logSalePrice on categorical feature Enclosure</figcaption>
</figure>
</div>
</div>
</div>
<p>You can imagine how useful these model interpretation tools can be, both for understanding data and for improving your models.</p>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>There you have it, a simple flow for solving regression problems with XGBoost in python. Remember you can use the XGBoost regression notebook from my <a href="https://github.com/mcb00/ds-templates">ds-templates repo</a> to make it easy to follow this flow on your own problems. If you found this helpful, or if you have additional ideas about solving regression problems with XGBoost, let me know down in the comments.</p>


</section>

 ]]></description>
  <category>python</category>
  <category>tutorial</category>
  <category>gradient boosting</category>
  <category>xgboost</category>
  <guid>https://randomrealizations.com/posts/xgboost-for-regression-in-python/</guid>
  <pubDate>Mon, 18 Sep 2023 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/xgboost-for-regression-in-python/kigali-branches.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Blogging with Quarto and Jupyter: The Complete Guide</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/</link>
  <description><![CDATA[ 





<!-- 
![](thumbnail.png "quarto, jupyter, and python logos in hexagons")
-->
<p>Ahh, blogging. I think we can all agree it’s probably one of the greatest forms of written communication to have ever existed.</p>
<p>Whats that you say? You’d like to set up your own blog? And you say you want to use a dead simple, data science friendly tech stack? And you wouldn’t be caught dead handing over your painstakingly crafted content to Medium? No worries, friend, I know exactly what you need.</p>
<p>Enter <a href="https://quarto.org">Quarto</a>.</p>
<p>In this post we’ll set up a blog using a lightweight tech stack consisting of a terminal running quarto, git, and jupyter, and we’ll use Github Pages to host our website for free. Optionally, for a few dollars a year, we can even host our website at our own custom domain.</p>
<p>A quick note on how to use this post. <a href="https://quarto.org/docs/websites/website-blog.html">Quarto’s documentation on blogging</a> provides a nice high-level overview of the blogging workflow, and I refer to it and many other bits of Quarto documentation here. At the time of writing, the handful of other blog posts about setting up quarto blogs are aimed at the RStudio user. This post exists to provide a jupyter and python-centric path for you to follow through the entire setup of your new quarto blog, and to impart my opinionated recommendations about best practices.</p>
<p>Let’s get into it!</p>
<section id="what-is-quarto" class="level2">
<h2 class="anchored" data-anchor-id="what-is-quarto">What is Quarto?</h2>
<p>Quarto is a way to render plain text source files containing markdown and code in python, R, and other languages into published formats like websites, books, slides, journal articles, etc. There is clearly a lot that we can do with it, but Today, we’ll use it to make a nice looking blog out of some jupyter notebook files.</p>
<p>Quarto follows the familiar convention of using a project directory to house all material for a given project. The directory will include source files like jupyter notebooks or Rmarkdown files, as well as configuration files that control how output files are rendered. We can then use the quarto command line utility to perform actions like previewing and rendering within the project directory.</p>
</section>
<section id="instantiate-your-blog" class="level2">
<h2 class="anchored" data-anchor-id="instantiate-your-blog">Instantiate your blog</h2>
<section id="create-a-new-quarto-project" class="level3">
<h3 class="anchored" data-anchor-id="create-a-new-quarto-project">Create a new Quarto project</h3>
<p>After <a href="https://quarto.org/docs/get-started/">installing quarto</a> fire up a new terminal and check that the install was successful by running</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">quarto</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--version</span></span></code></pre></div></div>
<p>Now think of a name for your blog’s project directory; this will also be the name of its git repository. The name will have no effect on your website’s name or URL, so don’t think too hard. The <a href="https://quarto.org/docs/websites/website-blog.html">quarto documentation</a> calls it <code>myblog</code>, so we’ll one-up them and call ours <code>pirate-ninja-blog</code>. Run the following command to create it in the current directory.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb2-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">quarto</span> create-project pirate-ninja-blog <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--type</span> website:blog</span></code></pre></div></div>
<p>That command creates a directory called <code>pirate-ninja-blog</code> containing everything you need to render your new blog. You can preview your website by running</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb3-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">quarto</span> preview pirate-ninja-blog</span></code></pre></div></div>
<p>Your local website will open in a new browser window. As you edit various aspects of your blog, the preview will update with your changes. This preview feature is so simple and so great.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/pirate-ninja-blog-screenshot.png" class="img-fluid figure-img"></p>
<figcaption>Previewing your blog with quarto preview command</figcaption>
</figure>
</div>
</section>
<section id="set-up-a-git-repo" class="level3">
<h3 class="anchored" data-anchor-id="set-up-a-git-repo">Set up a git repo</h3>
<p>Change into your project directory and we’ll start setting up your git repo.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb4-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">cd</span> pirate-ninja-blog</span></code></pre></div></div>
<p>initialize a new git repo.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb5-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> init <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-b</span> main</span></code></pre></div></div>
<p>The <code>_site/</code> directory is where quarto puts the rendered output files, so you’ll want to ignore it in git. I also like to just ignore any hidden files too, so add the following to your <code>.gitignore</code> file.</p>
<div class="code-with-filename">
<div class="code-with-filename-file">
<pre><strong>.gitignore</strong></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" data-filename=".gitignore" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">/.quarto/</span></span>
<span id="cb6-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">/_site/</span></span>
<span id="cb6-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">*</span></span></code></pre></div></div>
</div>
<p>For now we’ll just stage the <code>.gitignore</code> file for the initial commit. Eventually you’ll want to commit the other files in your project too, either now or later as you edit them.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb7-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> add .gitignore </span>
<span id="cb7-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> commit <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-m</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Initial commit."</span></span></code></pre></div></div>
<p>Then follow GitHub’s instructions to <a href="https://docs.github.com/en/migrations/importing-source-code/using-the-command-line-to-import-source-code/adding-locally-hosted-code-to-github#adding-a-local-repository-to-github-using-git">add the local repo to GitHub using git</a>. Basically just create a new blank repo on GitHub’s website, copy the remote repository url, then add the remote repo url to your local git repo.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb8-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> remote add origin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>REMOTE_URL<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div></div>
<p>Then you’ll be able to push any commits you make to your remote repository on GitHub by saying <code>git push</code>.</p>
</section>
</section>
<section id="understand-the-components-of-a-quarto-blog" class="level2">
<h2 class="anchored" data-anchor-id="understand-the-components-of-a-quarto-blog">Understand the components of a Quarto blog</h2>
<section id="contents-of-the-quarto-project-directory" class="level3">
<h3 class="anchored" data-anchor-id="contents-of-the-quarto-project-directory">Contents of the quarto project directory</h3>
<p>Let’s have a quick look at what quarto put inside of the project directory.</p>
<pre><code>_quarto.yml
about.qmd
index.qmd
profile.jpg
posts
styles.css
_site</code></pre>
<ul>
<li>Quarto uses yaml files to specify configurations. The <code>_quarto.yml</code> file specifies project-wide configurations.</li>
<li>Quarto’s markdown file type uses extension <code>qmd``. Each qmd file will correspond to a page in our website.</code>index.qmd<code>is the homepage and</code>about.qmd` is the About page.</li>
<li><code>profile.jpg</code> is an image that is included on the about page.</li>
<li><code>styles.css</code> defines css styles for the website.</li>
<li><code>posts</code> is a directory where we can put qmd and other documents which will be rendered into blog posts.</li>
<li><code>posts/_metadata.yml</code> contains configurations that apply to all documents in the <code>posts</code> directory.</li>
<li><code>_site</code> is a directory that contains the rendered website. Whereas all the other files and directories constitute the source code for our blog, <code>_site</code> is the rendered output, i.e.&nbsp;the website itself.</li>
</ul>
<p>Let’s take a closer look at these components and start to make the blog yours.</p>
</section>
<section id="project-wide-configurations" class="level3">
<h3 class="anchored" data-anchor-id="project-wide-configurations">Project-wide Configurations</h3>
<p>The <code>_quarto.yml</code> file controls project-wide configurations, website options, and HTML document options. Options in this file are specified in yaml in a key/value structure with three top level keys: <code>project</code>, <code>website</code>, and <code>format</code>. <a href="https://quarto.org/docs/reference/projects/websites.html">The quarto website options documentation</a> has the full list of options that you can set here. It will be very helpful to take a look at some example <code>_quarto.yml</code> files in the wild, such as the one from <a href="https://github.com/quarto-dev/quarto-web/blob/main/_quarto.yml">quarto.org</a> or even the one from <a href="https://github.com/mcb00/rr-blog/blob/main/_quarto.yml">this blog</a>.</p>
<p>Under the <code>website</code> key, go ahead and set the title and description for your blog.</p>
<pre><code>website:
  title: "Pirate Ninja Blog"
  description: "A blog about pirates, ninjas, and other things"</code></pre>
<p>You can also customize your <a href="https://quarto.org/docs/reference/projects/websites.html#navbar">navbar</a> which is visible at the top of all pages on your site. Also go ahead and set your github and twitter urls for the icons in the navbar.</p>
<p>Under the <code>format</code> key, you can also try changing the <a href="https://quarto.org/docs/output-formats/html-themes.html">HTML theme</a> to one of the other 25 built-in themes.</p>
</section>
<section id="the-about-page" class="level3">
<h3 class="anchored" data-anchor-id="the-about-page">The About Page</h3>
<p>The <code>about.qmd</code> file defines an About page for the blog. Go ahead and fill in your details in the <code>about.qmd</code> file; you can also replace the <code>profile.jpg</code> file with your own image. Have a look at <a href="https://quarto.org/docs/websites/website-about.html">the quarto documentation on About pages</a> to explore more functionality. Notably, you can change the <code>template</code> option to change the page layout.</p>
</section>
<section id="the-homepage" class="level3">
<h3 class="anchored" data-anchor-id="the-homepage">The Homepage</h3>
<p>The <code>index.qmd</code> file defines the landing page for your website. It is a <a href="https://quarto.org/docs/websites/website-listings.html">listing page</a> which shows links to all the pages in the <code>posts</code> directory. For now we don’t need to change anything here.</p>
</section>
<section id="the-posts-directory" class="level3">
<h3 class="anchored" data-anchor-id="the-posts-directory">The <code>posts/</code> directory</h3>
<p>The <code>posts</code> directory contains all your blog posts. There aren’t really requirements for subdirectory structure inside the <code>posts</code> directory, but it’s a best practice to create a new subdirectory for each new blog post. This just helps keep auxillary files like images or conda environment files organized. Out of the box, the <code>posts</code> directory looks like this.</p>
<pre><code>posts
├── _metadata.yml
├── post-with-code
│&nbsp;&nbsp; ├── image.jpg
│&nbsp;&nbsp; └── index.qmd
└── welcome
    ├── index.qmd
    └── thumbnail.jpg</code></pre>
<p>There are two reasons we want to be deliberate about how we organize and name things in the <code>posts</code> directory. First, the vast majority of our blog’s content will live here, so we don’t want it to be a big confusing mess. Second, the directory sstructure and file naming will be reflected in the URLs to our blog posts; if you prefer tidy-looking URLs, and I know you do, then you want to use tidy directory and file names in the <code>posts</code> directory.</p>
<p>You can check how the URLs look by navigating to one of the pre-populated posts in the site preview in your browser. For instance, the welcome post’s URL would be</p>
<pre><code>https://example.com/posts/welcome/</code></pre>
<p>When quarto renders the qmd file at <code>posts/welcome/index.qmd</code> it creates an output document in the website at <code>posts/welcome/index.html</code>. In fact the full URL to the post is,</p>
<pre><code>https://example.com/posts/welcome/index.html</code></pre>
<p>but the browser knows if you give it a URL with a path ending in a <code>/</code>, then it should look for the <code>index.html</code> file inside that directory.</p>
<p>So I think the best practice here is to name your new post subdirectory with the title of the post in all lower case with dashes for spaces, e.g.&nbsp;<code>post-with-code</code>. Then to force all output pages to be called <code>index.html</code>, you can set the <code>output-file</code> key in the <code>posts/_metadata.yml</code> file like this.</p>
<div class="code-with-filename">
<div class="code-with-filename-file">
<pre><strong>posts/_metadata.yml</strong></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" data-filename="posts/_metadata.yml" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb14-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">output-file:</span> index.html</span></code></pre></div></div>
</div>
<p>Note that alternative naming conventions are possible; notably you might want to prefix each post name with the date in yyyy-mm-dd format, so the post subdirectories sort temporally and look nice in a list. That’s the convention used in Quarto’s own blog at <a href="https://github.com/quarto-dev/quarto-web/tree/main">quarto.org</a>, As long as you keep everything for a given post inside its subdirectory, you should be good to go with nice-looking URLs.</p>
</section>
</section>
<section id="authoring-posts-with-jupyter" class="level2">
<h2 class="anchored" data-anchor-id="authoring-posts-with-jupyter">Authoring posts with jupyter</h2>
<section id="creating-a-new-post" class="level3">
<h3 class="anchored" data-anchor-id="creating-a-new-post">Creating a new post</h3>
<p>It turns out that quarto will render not only <code>.qmd</code> files, but also <code>.ipynb</code> files in the <code>posts</code> directory. So let’s create a new blog post from a notebook.</p>
<p>I think it’s a best practice to write draft posts in their own git branches, that way if you need to deploy some kind of hotfix to main while you’re drafting a post, you won’t have to deploy a half-written post livin on the main branch. To start a new post, create a new development branch, change into the posts directory, create a new subdirectory with your preferred naming convention, change into that new directory, and fire up jupyter.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb15-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> checkout <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-b</span> new-post</span>
<span id="cb15-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">cd</span> posts</span>
<span id="cb15-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mkdir</span> new-post</span>
<span id="cb15-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">cd</span> new-post</span>
<span id="cb15-5"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">jupyter</span> notebook</span></code></pre></div></div>
<p>Now create a new notebook from the jupyter UI. In order for quarto to recognize the document, the first cell of the notebook must be a raw text cell (press <code>r</code> in command mode to change a cell to raw text), and it must contain the document’s yaml front matter. You can use the following as a frontmatter template.</p>
<pre><code>---
title: New Post
date: 2023-07-12
description: A nice new post
categories: [nonsense, code]
---</code></pre>
<p>Now to preview your post, open a new terminal, change into your blog’s project directory and run the <code>quarto preview</code> command. You’ll see a link to the new post in the listing on the homepage. I usually like to have the preview open in a browser while I’m editing the jupyter notebook, just to make sure things look the way I want in the rendered output. From here you can keep editing the notebook, and the preview will update in the browser dynamically.</p>
</section>
<section id="markdown-and-code-cells" class="level3">
<h3 class="anchored" data-anchor-id="markdown-and-code-cells">Markdown and code cells</h3>
<p>From here you can put text in markdown cells and you can write code in code cells. Let’s add a markdown cell with some markdown formatting.</p>
<pre><code>## A nice heading

Here is some lovely text and an equation.

$$ a^2 + b^2 = c^2 $$

Here's a list.

- a link to an [external website](https://quarto.org).
- a link to [another post in this blog](/posts/welcome/index.qmd).</code></pre>
<p>This markdown will be rendered into the HTML page for the post. The last line in the above cell demonstrates the best practice for using relative urls to link to other resources within your website. Instead of providing the full url in the parentheses, just give the path to the qmd or ipynb file that you want to link to. Note that paths need to start with the <code>/</code> at the root of the quarto project, since without it, quarto will try to resolve paths relative to the location of the current document instead of the root of the project.</p>
<p>Then create a code cell with some code. Try something like this.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Hello, Quarto!'</span>)</span></code></pre></div></div>
<p>By default, both code and cell output will be rendered into the HTML output. So far our jupyter notebook looks like this.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/authoring-in-jupyter.png" class="img-fluid figure-img"></p>
<figcaption>View of a new post being written in jupyter notebook</figcaption>
</figure>
</div>
<p>Back in the browser window running your blog preview, you can see the rendered page of the new post.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/new-post-preview.png" class="img-fluid figure-img"></p>
<figcaption>View of the preview of the rendered post</figcaption>
</figure>
</div>
</section>
<section id="figures" class="level3">
<h3 class="anchored" data-anchor-id="figures">Figures</h3>
<p>Let’s add a figure to our post. Add a new code cell with the following code.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># | fig-cap: This is my lovely line plot</span></span>
<span id="cb19-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># | fig-alt: A line plot extending up and to the right</span></span>
<span id="cb19-3"></span>
<span id="cb19-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb19-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb19-6"></span>
<span id="cb19-7">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb19-8">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb19-9">plt.plot(x, y)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>Notice a couple of important details. First I placed a semicolon at the end of the last line. That supresses the <code>[&lt;matplotlib.lines.Line2D at 0x1111d00a0&gt;]</code> text output, which would otherwise show up in your blog post too.</p>
<p>Second, I added a couple of special comments at the top of the cell. Quarto allows you to specify numerous <a href="https://quarto.org/docs/computations/execution-options.html">code execution options</a>, designated by the <code># |</code> prefix, to control the behavior and appearance of the code and output at a cell level. I set two keys here, <code>fig-cap</code> and <code>fig-alt</code> which respectively set the figure caption text and the image alt tag text. The <code>fig-alt</code> key is particularly important to set on all your figures because it provides the non-visual description for screenreader users reading your post. The alt tag should be a simple description of what the plot is and possibly what it shows or means. Be a friend of the blind and visually impaired community and set <code>fig-alt</code> on all of your figures.</p>
</section>
<section id="version-control" class="level3">
<h3 class="anchored" data-anchor-id="version-control">Version control</h3>
<p>As you edit your new post, go ahead and commit your changes on your development branch. Once you’ve finished your new post, you can merge it into main like this.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb20-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> checkout main</span>
<span id="cb20-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> merge new-post</span></code></pre></div></div>
<p>Then you can push to GitHub by running <code>git push</code>. You should also be sure to run a final <code>quarto preview</code> to check that everything looks good before publishing to the web.</p>
</section>
</section>
<section id="publishing-your-blog-to-the-web" class="level2">
<h2 class="anchored" data-anchor-id="publishing-your-blog-to-the-web">Publishing your blog to the web</h2>
<section id="hosting-with-github-pages" class="level3">
<h3 class="anchored" data-anchor-id="hosting-with-github-pages">Hosting with GitHub Pages</h3>
<p>It’s likely that the easiest (read best) option for you is to host your blog on <a href="https://pages.github.com/">GitHub Pages</a>. This is because GitHub pages is free, and since you already have your blog’s source code checked into a remote repository at GitHub, it’s very easy to set up. <a href="https://quarto.org/docs/publishing/github-pages.html">Quarto’s documentation on publishing to GitHub Pages</a> outlines three ways to publish your website, but I recommend their option 2, using the <code>quarto publish</code> command. Once you set up your <code>gh-pages</code> branch as described in the documentation, you simply run <code>quarto publish</code> at the command line and your updates are deployed to your website.</p>
</section>
<section id="setting-up-your-domain-name" class="level3">
<h3 class="anchored" data-anchor-id="setting-up-your-domain-name">Setting up your domain name</h3>
<p>By default, if you choose to host with GitHub Pages, your website will be published to a url in the form <code>https://username.github.io/reponame/</code>. You can certainly do this; for example Jake VanderPlas’s awesome blog Pythonic Perambulations lives at <a href="http://jakevdp.github.io">http://jakevdp.github.io</a>.</p>
<p>But, like me, you might want to get your own custom domain by buying, or really renting, one from a registrar. I use <a href="https://www.namecheap.com">Namecheap</a>. If you decide to go for a custom domain, refer to <a href="https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/about-custom-domains-and-github-pages">GitHub’s documentation on custom domains</a>. You’ll also need to point your domain registrar to the IP address where GitHub Pages is hosting your website. For an example of how to do this at Namecheap, see <a href="https://www.namecheap.com">Namecheap’s documentation about GitHub Pages</a></p>
<p>Whether you decide to use the standard <code>github.io</code> domain or your own custom domain, be sure to set the <code>site-url</code> key in your <code>_quarto.yml</code> file to ensure other quarto functionality works correctly. For example</p>
<div class="code-with-filename">
<div class="code-with-filename-file">
<pre><strong>_quarto.yml</strong></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" data-filename="_quarto.yml" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb21-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">website:</span></span>
<span id="cb21-2">  <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">site-url:</span> https://example.com/</span></code></pre></div></div>
</div>
<p>Edit: I found that after upgrading to quarto 1.3, using <code>quarto publish</code> to publish from the <code>gh-pages</code> branch obliterates the <code>CNAME</code> file that is created when you set a custom domain in your repository settings &gt; Pages &gt; Custom Domain. That breaks the mapping from your custom domain to your published website. See this <a href="https://github.com/quarto-dev/quarto-cli/discussions/3249">disscussion thread</a> for details. The fix is to manually create a <code>CNAME</code> file in the root of your project, and include it in the rendered website using the <code>resources</code> option under the <code>project</code> key in <code>_quarto.yml</code>. The <code>CNAME</code> file should just contain your custom domain, excluding any <code>https://</code>.</p>
<div class="code-with-filename">
<div class="code-with-filename-file">
<pre><strong>CNAME</strong></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb22" data-filename="CNAME" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb22-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">example.com</span></span></code></pre></div></div>
</div>
<p>With the <code>CNAME</code> file in the root of your quarto project, you can then include it in the rendered output.</p>
<div class="code-with-filename">
<div class="code-with-filename-file">
<pre><strong>_quarto.yml</strong></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb23" data-filename="_quarto.yml" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb23-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">project:</span></span>
<span id="cb23-2">  <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">resources:</span></span>
<span id="cb23-3">    <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">-</span> CNAME</span></code></pre></div></div>
</div>
</section>
</section>
<section id="keep-in-touch-with-your-readers" class="level2">
<h2 class="anchored" data-anchor-id="keep-in-touch-with-your-readers">Keep in touch with your readers</h2>
<section id="rss-feed" class="level3">
<h3 class="anchored" data-anchor-id="rss-feed">RSS Feed</h3>
<p>The RSS feed is handy for syndicating your posts to feed readers, other websites, and to your email subscribers. As described in <a href="https://quarto.org/docs/websites/website-blog.html#rss-feed">quarto’s documentation on RSS feeds</a>, you can automatically generate an RSS feed for your blog by first setting the value of <code>site-url</code> under the <code>website</code> key in <code>_quarto.yml</code>, and then setting <code>feed: true</code> under the <code>listing</code> key in the frontmatter of <code>index.qmd</code>. This will generate an RSS feed in the root of your website called <code>index.xml</code>. Once you have an RSS feed, go ahead and submit it to <a href="https://python-bloggers.com">Python-Bloggers</a> to have your work syndicated to a wider audience and to strengthen our little community of independent data science blogs.</p>
</section>
<section id="email-subscriptions" class="level3">
<h3 class="anchored" data-anchor-id="email-subscriptions">Email Subscriptions</h3>
<p>The idea here is to have a form field on your website where readers can input their email address to be added to your mailing list. <a href="https://quarto.org/docs/websites/website-blog.html#subscriptions">Quarto’s documentation on subscriptions</a> describes how to set up a subscribe box on your blog using MailChimp, so we won’t repeat it here. Once you have some subscribers, you can send them updates whenever you write a new post. You could do this manually or, in my case, set up an <a href="https://mailchimp.com/help/share-your-blog-posts-with-mailchimp/">automation through MailChimp</a> which uses your RSS feed to send out email updates to the list about new posts.</p>
</section>
<section id="comments" class="level3">
<h3 class="anchored" data-anchor-id="comments">Comments</h3>
<p>Quarto has build-in support for three different comment systems: hypothesis, utterances, and giscus. The good news is that these are all free to use, easy to set up, and AFAIK do not engage in any sketchy tracking activities. The bad news is that none of them are ideal because they all require the user to create an account and login to leave a comment. We want to encourage readers to comment, so we don’t want them to have to create accounts or deal with passwords or pick all the squares with bicycles or any such nonsense, just to leave a little comment. To that end, I’ve actually been working on self-hosted login-free comments for this blog using <a href="https://isso-comments.de">isso</a>, but it’s a bit more involved than these built-in solutions, so we’ll have to discuss it at length in a future post.</p>
<p>If you prefer an easy, out-of-the-box solution, I can recommend utterances, which uses GitHub issues to store comments for each post. I used utterances for comments on the first jekyll-based incarnation of this blog; you can still see the utterances comments on posts before this one. Go check out the <a href="https://quarto.org/docs/reference/projects/websites.html#comments">Quarto documentation on comments</a> to see how to set up utterances in your project.</p>
</section>
<section id="analytics" class="level3">
<h3 class="anchored" data-anchor-id="analytics">Analytics</h3>
<p>As a data enthusiast, you’ll likely enjoy collecting some data about page views and visitors to your site. You might be tempted to use Google Analytics to do this; indeed quarto makes it very easy to just add a line to your <code>_quarto.yml</code> file to set it up. Unfortunately, in this case, going with the easy and free solution means supporting <a href="https://en.wikipedia.org/wiki/Privacy_concerns_regarding_Google">Google’s dubious corporate surveillance activities</a>. Be a conscientious internet citizen and avoid using Google Analytics on your blog. Fortunately, there are numerous privacy-friendly alternatives to Google Analytics. For this blog I’m self-hosting <a href="https://umami.is">umami analytics</a>, which might warrant its own post in the future.</p>
</section>
</section>
<section id="more-humbly-suggested-best-practices" class="level2">
<h2 class="anchored" data-anchor-id="more-humbly-suggested-best-practices">More humbly suggested best practices</h2>
<section id="using-conda-environments-for-reproducibility" class="level3">
<h3 class="anchored" data-anchor-id="using-conda-environments-for-reproducibility">Using conda environments for reproducibility</h3>
<p>As you know, it’s a good practice to use an environment manager to keep track of packages, their versions, and other dependencies for software in a data science project. The same applies to blog posts; especially if you’re using unusual or bleeding-edge packages in a post. This will help us out a lot when we have to go back and re-run a notebook a couple years later to regenerate the output. Here we’ll use <a href="https://docs.conda.io/projects/conda/en/latest/index.html">conda</a> as our environment manager.</p>
<p>To be clear, I don’t bother doing this if I’m just using fairly stable functionality in standard packages like pandas, numpy, and matplotlib, but we’ll do it here for illustration. From a terminal sitting inside our post subdirectory at <code>posts/new-post</code>, create a new conda environment with the packages you’re using in the post.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb24-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">conda</span> create <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-p</span> ./venv jupyter numpy matplotlib</span></code></pre></div></div>
<p>Note the <code>-p</code> flag which tells conda to save the environment to <code>./venv</code> in the current working directory. This will save all the installed packages here in the post directory instead of in your system-wide location for conda environments. Note also that you’ll want to avoid checking anything in the <code>venv</code> directory into source control, so add <code>venv</code> to the <code>.gitignore</code> file at the root of the quarto project to ignore all <code>venv</code> directories throughout your quarto project.</p>
<p>Now whenever you work on this post, you’ll navigate to the post subdirectory with a terminal and activate the conda environment.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb25-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">conda</span> activate ./venv</span></code></pre></div></div>
<p>Then you can fire up your jupyter notebook from the command line, and it will use the active conda environment.</p>
<p>Since we don’t want to check the <code>venv</code> directory with all its installed libraries into source control, we need to create an <code>environment.yml</code> file from which the environment can later be reproduced. With the local conda environment active, run the following.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb26-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">conda</span> env export <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--from-history</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> environment.yml</span></code></pre></div></div>
<p>The <code>--from-history</code> flag tells conda to skip adding a bunch of system specific stuff that will gunk up your environment yaml file and make it harder to use for cross-platform reproducibility. This <code>environment.yml</code> file is the only environment management artifact that you need to check into git.</p>
<p>Later if you need to recreate the environment from the <code>environment.yml</code> file, you can use the following command.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb27-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">conda</span> env create <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-f</span> environment.yml <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-p</span> ./venv<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">`</span></span></code></pre></div></div>
</section>
<section id="image-file-best-practices" class="level3">
<h3 class="anchored" data-anchor-id="image-file-best-practices">Image file best practices</h3>
<p>Let’s talk about image file sizes. The key idea is that we want images to have just enough resolution to look good; any more than that and we’re just draging around larger-than-necessary files and wasting bandwidth and slowing down page load times.</p>
<p>You can read all about <a href="https://www.foregroundweb.com/image-size/">choosing optimal image sizes</a>, but the TLDR is that images should be just large enough (in pixels) to fill the containers they occupy on the page. In our quarto blog, the two most common kinds of images are inline images we put in the body of posts and image thumbnails that show up as the associated image for a post, e.g.&nbsp;in the listing on our homepage. The inline image container seems to be about 800 pixels wide in my browser and the thumbnails are smaller, so adding some margin of error, I decided to go for 1000x750 for inline images and 500x375 for the thumbnails.</p>
<p>I use a command line tool called <a href="https://imagemagick.org">Image Magick</a> to resize image files. Go ahead and <a href="https://formulae.brew.sh/formula/imagemagick">install image magick with homebrew</a>, and let’s add some images to our new post.</p>
<p>For this example I’ll use a nice shot of the <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Why_London_Underground_is_nicknamed_The_Tube.jpg/1920px-Why_London_Underground_is_nicknamed_The_Tube.jpg">London Underground</a> from Wikipedia. Save your image as <code>image.jpg</code>. Then use image magick to create two new resized images for inline and thumbnail use.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb28-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">convert</span> image.jpg <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-resize</span> 1000x1000 main.jpg </span>
<span id="cb28-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">convert</span> image.jpg <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-resize</span> 500x500 thumbnail.jpg </span></code></pre></div></div>
<p>These commands do not change the aspect ratio of the image; they just reduce the size so that the image fits within the size specified.</p>
<p>Now move both of your new images into the post subdirectory at <code>posts/new-post/</code>. To specify the thumbnail image, set the <code>image</code> key in the post’s front matter. Be sure to also add an alt tag description of the image using the <code>image-alt</code> key to keep it accessible for screen reader users. Our post’s frontmatter now looks like this.</p>
<pre><code>---
title: New Post
date: 2023-07-12
description: A nice new post
categories: [nonsense, code]
image: thumbnail.jpg
image-alt: "A London Underground train emerging from a tunnel"
---</code></pre>
<p>To include an image within the body of a post, use markdown in the post to include the image. I added a markdown cell just under the front matter containing the following.</p>
<pre><code>![A London Underground train emerging from a tunnel](main.jpg "")</code></pre>
<p>In your preview browser window, you can see we have the thumbnail for our new post on the homepage listing.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/homepage-with-new-post-thumbnail.jpg" class="img-fluid figure-img"></p>
<figcaption>A screenshot of the homepage showing the new post’s thumbnail image</figcaption>
</figure>
</div>
<p>And we also have the inline image appearing in the body of the post.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/new-post-with-inline-image.jpg" class="img-fluid figure-img"></p>
<figcaption>A screenshot of the new post showing the image included in the body of the post</figcaption>
</figure>
</div>
<p>You can take a look at <a href="https://github.com/mcb00/rr-blog">the source code for this blog</a> to see some examples of including images in posts.</p>
</section>
</section>
<section id="seo" class="level2">
<h2 class="anchored" data-anchor-id="seo">SEO</h2>
<p>SEO is a huge topic, but here we’ll just focus on a few fundamental technical aspects that we want to be sure to get right. This boils down to registering with the top search engines by market share and ensuring that we’re providing them with the information they need to properly index our pages.</p>
<p>I checked the <a href="https://www.statista.com/statistics/216573/worldwide-market-share-of-search-engines/#main-content">top search engines by global market share</a> and as of 2023 it looks like Google has about 85%, Bing has about 8%, and the others have 2% or less each. So let’s focus on setting our site up to work well with Google search and Bing to get over 90% coverage.</p>
<section id="google-search-console-and-bing-webmaster-tools" class="level3">
<h3 class="anchored" data-anchor-id="google-search-console-and-bing-webmaster-tools">Google Search Console and Bing Webmaster Tools</h3>
<p><a href="https://search.google.com/search-console/about">Google Search Console</a> is a tool for web admins to help analyze search traffic and identify any technical issues that might prevent pages from appearing or ranking well in search. Go ahead and set up an account and register your blog in search console. You can refer to <a href="https://developers.google.com/search/docs/monitor-debug/search-console-start">Google’s documentation on search console</a> to guide you through setup and configuration.</p>
<p>Once you get set up on GSC, you can also create an account for <a href="https://www.bing.com/webmasters/about">Bing Webmaster Tools</a>. Do this after setting up GSC because there is an option to import your information from your GSC account.</p>
<p>Once you’re set up with GSC and BWT, you’ll get email alerts anytime they crawl your site and detect any indexing problems. When that happens, track down the issues and fix them so your pages can appear in organic searches.</p>
</section>
<section id="sitemap" class="level3">
<h3 class="anchored" data-anchor-id="sitemap">Sitemap</h3>
<p>A sitemap is an xml document that lists all the pages on your website. It’s a map for the search engine bots that crawl the web looking for new pages to index. Quarto will automatically generate a sitemap called <code>sitemap.xml</code> in the root of your website, as long as you’ve filled out the <code>site-url</code> key in <code>_quarto.yml</code>. You can submit your website for indexing by providing your sitemap in Google Search Console and Bing Webmaster Tools.</p>
</section>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Boy howdy, that was a lot, but at this point you should have a fully functioning blog, built with a minimalist, data-science-friendly tech stack consisting of quarto, jupyter, and GitHub. If you do create a blog using quarto, drop a link to it in the comments, and we can all check it out and celebrate your creation!</p>


</section>

 ]]></description>
  <category>python</category>
  <category>tutorial</category>
  <category>blogging</category>
  <guid>https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/</guid>
  <pubDate>Wed, 06 Sep 2023 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/blogging-with-quarto-and-jupyter/thumbnail.png" medium="image" type="image/png" height="108" width="144"/>
</item>
<item>
  <title>Random Realizations Resurrected</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/random-realizations-resurrected/</link>
  <description><![CDATA[ 





<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/random-realizations-resurrected/main.jpg" class="img-fluid figure-img"></p>
<figcaption>Christ the Redeemer towers into a vast blue Brazilian sky.!</figcaption>
</figure>
</div>
<p>Well it’s been over a year since I posted anything here. You see, a lot has been going on here at the Random Realizations Remote Global Headquarters that has distracted from producing the high-quality data science content that you’re used to. Mostly I went on hiatus from work and started traveling, which turns out to be it’s own full time job. I had aspirations of writing more after leaving work, but of course, after leaving, I couldn’t be bothered to sit down at my laptop and type stuff about data science to yall. After all, life is bigger than that.</p>
<p>When I finally felt like opening up my laptop, I was confronted with an email from the maintainers of <a href="https://github.com/fastai/fastpages">fastpages</a>, the open source content management system (CMS) I originally used to create this blog, notifying me that the project was being deprecated and that I would need to migrate my content to some other platform.</p>
<p>Boo.</p>
<p>That didn’t sound like much fun, so I spent another few months ignoring the blog. But eventually, dear reader, I decided it was time to roll up my sleeves and get this blog thriving once again.</p>
<p>Ok so fastpages was going to be deprecated, and I needed to find a new CMS. My requirements were pretty simple: I wanted to write the blog posts with jupyter notebook, and I wanted to host the site on my own domain. Helpfully, the former maintainers of fastpages recommended an alternative CMS called <a href="https://quarto.org/">Quarto</a> which I had never heard of. Apparently I had been living under a rock because Quarto appears to be all the rage. Quarto’s website says it’s an open-source scientific and technical publishing system. I think it’s fair to think of it as a way to render plain text or source code from languages like python, R, and julia into a variety of different published formats like websites, books, or journal articles. It was developed by the good folks over at RStudio, and the project has a pretty active following over on <a href="https://github.com/quarto-dev">github</a>, so I think it’s less likely to suddenly disappear like fastpages.</p>
<p>So anyway, I’ve been migrating my content over into this new quarto universe.</p>
<p>You mayofficially consider this blog resurrected from the dead, because this is the first new post published after the migration. The site has a bit of a new look and feel, so I hope you like it. Do let me know in the comments if you find anything amiss with the new website. Otherwise we’ll just assume it’s fabulous.</p>
<p>I’m working on a post about how to create a blog with quarto using jupyter and python, so you can too!</p>
<p>See you in more posts real soon! Love, Matt.</p>



 ]]></description>
  <category>blogging</category>
  <guid>https://randomrealizations.com/posts/random-realizations-resurrected/</guid>
  <pubDate>Wed, 02 Aug 2023 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/random-realizations-resurrected/thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>XGBoost from Scratch</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/xgboost-from-scratch/</link>
  <description><![CDATA[ 





<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-from-scratch/main.jpg" class="img-fluid figure-img"></p>
<figcaption>A weathered tree reaches toward the sea at Playa Mal País</figcaption>
</figure>
</div>
<p>Well, dear reader, it’s that time again, time for us to do a seemingly unnecessary scratch build of a popular algorithm that most people would simply import from the library without a second thought. But readers of this blog are not most people. Of course you know that when we do scratch builds, it’s not for the hell of it, it’s for the purpose of demystification. To that end, today we are going to implement XGBoost from scratch in python, using only numpy and pandas.</p>
<p>Specifically we’re going to implement the core statistical learning algorithm of XGBoost, including most of the key hyperparameters and their functionality. Our implementation will also support user-defined custom objective functions, meaning that it can perform regression, classification, and whatever exotic learning tasks you can dream up, as long as you can write down a twice-differentiable objective function. We’ll refrain from implementing some simple features like column subsampling which will be left to you, gentle reader, as exercises. In terms of tree methods, we’re going to implement the exact tree-splitting algorithm, leaving the sparsity-aware method (used to handle missing feature values) and the approximate method (used for scalability) as exercises or maybe topics for future posts.</p>
<p>As always, if something is unclear, try backtracking through the previous posts on gradient boosting and decision trees to clarify your intuition. We’ve already built up all the statistical and computational background needed to make sense of this scratch build. Here are the most important prerequisite posts:</p>
<ol type="1">
<li><a href="../../posts/gradient-boosting-machine-from-scratch/">Gradient Boosting Machine from Scratch</a></li>
<li><a href="../../posts/decision-tree-from-scratch/">Decision Tree From Scratch</a></li>
<li><a href="../../posts/how-to-understand-xgboost/">How to Understand XGBoost</a></li>
</ol>
<p>Great, let’s do this.</p>
<section id="the-xgboost-model-class" class="level2">
<h2 class="anchored" data-anchor-id="the-xgboost-model-class">The XGBoost Model Class</h2>
<p>We begin with the user-facing API for our model, a class called <code>XGBoostModel</code> which will implement gradient boosting and prediction. To be more consistent with the XGBoost library, we’ll pass hyperparameters to our model in a parameter dictionary, so our init method is going to pull relevant parameters out of the dictionary and set them as object attributes. Note the use of python’s <code>defaultdict</code> so we don’t have to worry about handling key errors if we try to access a parameter that the user didn’t set in the dictionary.</p>
<div id="cell-5" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> math</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np </span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> defaultdict</span></code></pre></div></div>
</div>
<div id="cell-6" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> XGBoostModel():</span>
<span id="cb2-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''XGBoost from Scratch</span></span>
<span id="cb2-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb2-4">    </span>
<span id="cb2-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, params, random_seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb2-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, params)</span>
<span id="cb2-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.subsample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb2-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb2-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb2-10">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span></span>
<span id="cb2-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'base_score'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb2-12">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'base_score'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span>
<span id="cb2-13">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb2-14">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb2-15">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.rng <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.default_rng(seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>random_seed)</span></code></pre></div></div>
</div>
<p>The fit method, based on our classic GBM, takes a feature dataframe, a target vector, the objective function, and the number of boosting rounds as arguments. The user-supplied objective function should be an object with loss, gradient, and hessian methods, each of which takes a target vector and a prediction vector as input; the loss method should return a scalar loss score, the gradient method should return a vector of gradients, and the hessian method should return a vector of hessians.</p>
<p>In contrast to boosting in the classic GBM, instead of computing residuals between the current predictions and the target, we compute gradients and hessians of the loss function with respect to the current predictions, and instead of predicting residuals with a decision tree, we fit a special XGBoost tree booster (which we’ll implement in a moment) using the gradients and hessians. I’ve also added row subsampling by drawing a random subset of instance indices and passing them to the tree booster during each boosting round. The rest of the fit method is the same as the classic GBM, and the predict method is identical too.</p>
<div id="cell-8" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fit(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, y, objective, num_boost_round, verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>):</span>
<span id="cb3-2">    current_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.ones(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y.shape)</span>
<span id="cb3-3">    <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb3-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_boost_round):</span>
<span id="cb3-5">        gradients <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> objective.gradient(y, current_predictions)</span>
<span id="cb3-6">        hessians <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> objective.hessian(y, current_predictions)</span>
<span id="cb3-7">        sample_idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.subsample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb3-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.rng.choice(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y), </span>
<span id="cb3-9">                                 size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>math.floor(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.subsample<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y)), </span>
<span id="cb3-10">                                 replace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb3-11">        booster <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TreeBooster(X, gradients, hessians, </span>
<span id="cb3-12">                              <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth, sample_idxs)</span>
<span id="cb3-13">        current_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> booster.predict(X)</span>
<span id="cb3-14">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters.append(booster)</span>
<span id="cb3-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> verbose: </span>
<span id="cb3-16">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'[</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">] train loss = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>objective<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>loss(y, current_predictions)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb3-17">            </span>
<span id="cb3-18"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb3-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate </span>
<span id="cb3-20">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>([booster.predict(X) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> booster <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters], axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb3-21"></span>
<span id="cb3-22">XGBoostModel.fit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fit</span>
<span id="cb3-23">XGBoostModel.predict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> predict            </span></code></pre></div></div>
</div>
<p>All we have to do now is implement the tree booster.</p>
</section>
<section id="the-xgboost-tree-booster" class="level2">
<h2 class="anchored" data-anchor-id="the-xgboost-tree-booster">The XGBoost Tree Booster</h2>
<p>The XGBoost tree booster is a modified version of the decision tree that we built in the decision tree from scratch post. Like the decision tree, we recursively build a binary tree structure by finding the best split rule for each node in the tree. The main difference is the criterion for evaluating splits and the way that we define a leaf’s predicted value. Instead of being functions of the target values of the instances in each node, the criterion and predicted values are functions of the instance gradients and hessians. Thus we need only make a couple of modifications to our previous decision tree implementation to create the XGBoost tree booster.</p>
<section id="initialization-and-inserting-child-nodes" class="level3">
<h3 class="anchored" data-anchor-id="initialization-and-inserting-child-nodes">Initialization and Inserting Child Nodes</h3>
<p>Most of the init method is just parsing the parameter dictionary to assign parameters as object attributes. The one notable difference from our decision tree is in the way we define the node’s predicted value. We define <code>self.value</code> according to equation 5 of the XGBoost paper, a simple function of the gradient and hessian values of the instances in the current node. Of course the init also goes on to build the tree via the maybe insert child nodes method. This method is nearly identical to the one we implemented for our decision tree. So far so good.</p>
<div id="cell-12" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> TreeBooster():</span>
<span id="cb4-2"> </span>
<span id="cb4-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, g, h, params, max_depth, idxs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb4-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params</span>
<span id="cb4-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> max_depth</span>
<span id="cb4-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth must be nonnegative'</span></span>
<span id="cb4-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_child_weight <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb4-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb4-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg_lambda'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg_lambda'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb4-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.gamma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'gamma'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'gamma'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span></span>
<span id="cb4-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.colsample_bynode <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'colsample_bynode'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb4-12">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'colsample_bynode'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb4-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(g, pd.Series): g <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g.values</span>
<span id="cb4-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(h, pd.Series): h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h.values</span>
<span id="cb4-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> idxs <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(g))</span>
<span id="cb4-16">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X, g, h, idxs</span>
<span id="cb4-17">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(idxs), X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb4-18">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>g[idxs].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (h[idxs].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Eq (5)</span></span>
<span id="cb4-19">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span></span>
<span id="cb4-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb4-21">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._maybe_insert_child_nodes()</span>
<span id="cb4-22"></span>
<span id="cb4-23">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _maybe_insert_child_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb4-24">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c): <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._find_better_split(i)</span>
<span id="cb4-25">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span></span>
<span id="cb4-26">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs,<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx]</span>
<span id="cb4-27">        left_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb4-28">        right_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb4-29">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TreeBooster(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params, </span>
<span id="cb4-30">                                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[left_idx])</span>
<span id="cb4-31">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TreeBooster(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params, </span>
<span id="cb4-32">                                 <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[right_idx])</span>
<span id="cb4-33"></span>
<span id="cb4-34">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@property</span></span>
<span id="cb4-35">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_leaf(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span></span>
<span id="cb4-36"></span>
<span id="cb4-37">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _find_better_split(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, feature_idx):</span>
<span id="cb4-38">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span></code></pre></div></div>
</div>
</section>
<section id="split-finding" class="level3">
<h3 class="anchored" data-anchor-id="split-finding">Split Finding</h3>
<p>Split finding follows the exact same pattern that we used in the decision tree, except we keep track of gradient and hessian stats instead of target value stats, and of course we use the XGBoost gain criterion (equation 7 from the paper) for evaluating splits.</p>
<div id="cell-14" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _find_better_split(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, feature_idx):</span>
<span id="cb5-2">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs, feature_idx]</span>
<span id="cb5-3">    g, h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs], <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs]</span>
<span id="cb5-4">    sort_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(x)</span>
<span id="cb5-5">    sort_g, sort_h, sort_x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g[sort_idx], h[sort_idx], x[sort_idx]</span>
<span id="cb5-6">    sum_g, sum_h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(), h.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>()</span>
<span id="cb5-7">    sum_g_right, sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sum_g, sum_h</span>
<span id="cb5-8">    sum_g_left, sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span></span>
<span id="cb5-9"></span>
<span id="cb5-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb5-11">        g_i, h_i, x_i, x_i_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sort_g[i], sort_h[i], sort_x[i], sort_x[i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb5-12">        sum_g_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> g_i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> sum_g_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> g_i</span>
<span id="cb5-13">        sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> h_i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> h_i</span>
<span id="cb5-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_child_weight <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> x_i_next:<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb5-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_child_weight: <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb5-16"></span>
<span id="cb5-17">        gain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ((sum_g_left<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda))</span>
<span id="cb5-18">                        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (sum_g_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda))</span>
<span id="cb5-19">                        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (sum_g<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sum_h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda))</span>
<span id="cb5-20">                        ) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.gamma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Eq(7) in the xgboost paper</span></span>
<span id="cb5-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> gain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far: </span>
<span id="cb5-22">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> feature_idx</span>
<span id="cb5-23">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gain</span>
<span id="cb5-24">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> x_i_next) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb5-25">            </span>
<span id="cb5-26">TreeBooster._find_better_split <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _find_better_split</span></code></pre></div></div>
</div>
</section>
<section id="prediction" class="level3">
<h3 class="anchored" data-anchor-id="prediction">Prediction</h3>
<p>Prediction works exactly the same as in our decision tree, and the methods are nearly identical.</p>
<div id="cell-16" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb6-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.array([<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._predict_row(row) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> X.iterrows()])</span>
<span id="cb6-3"></span>
<span id="cb6-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _predict_row(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, row):</span>
<span id="cb6-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: </span>
<span id="cb6-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value</span>
<span id="cb6-7">    child <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb6-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right</span>
<span id="cb6-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> child._predict_row(row)</span>
<span id="cb6-10"></span>
<span id="cb6-11">TreeBooster.predict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> predict </span>
<span id="cb6-12">TreeBooster._predict_row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _predict_row </span></code></pre></div></div>
</div>
</section>
</section>
<section id="the-complete-xgboost-from-scratch-implementation" class="level2">
<h2 class="anchored" data-anchor-id="the-complete-xgboost-from-scratch-implementation">The Complete XGBoost From Scratch Implementation</h2>
<p>Here’s the entire implementation which produces a usable <code>XGBoostModel</code> class with fit and predict methods.</p>
<div id="cell-18" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode numberSource python number-lines code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> XGBoostModel():</span>
<span id="cb7-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''XGBoost from Scratch</span></span>
<span id="cb7-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb7-4">    </span>
<span id="cb7-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, params, random_seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb7-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, params)</span>
<span id="cb7-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.subsample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb7-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-10">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span></span>
<span id="cb7-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'base_score'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-12">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'base_score'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span>
<span id="cb7-13">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-14">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb7-15">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.rng <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.default_rng(seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>random_seed)</span>
<span id="cb7-16">                </span>
<span id="cb7-17">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fit(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, y, objective, num_boost_round, verbose<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>):</span>
<span id="cb7-18">        current_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.ones(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y.shape)</span>
<span id="cb7-19">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb7-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_boost_round):</span>
<span id="cb7-21">            gradients <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> objective.gradient(y, current_predictions)</span>
<span id="cb7-22">            hessians <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> objective.hessian(y, current_predictions)</span>
<span id="cb7-23">            sample_idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.subsample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-24">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.rng.choice(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y), </span>
<span id="cb7-25">                                     size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>math.floor(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.subsample<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y)), </span>
<span id="cb7-26">                                     replace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb7-27">            booster <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TreeBooster(X, gradients, hessians, </span>
<span id="cb7-28">                                  <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth, sample_idxs)</span>
<span id="cb7-29">            current_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> booster.predict(X)</span>
<span id="cb7-30">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters.append(booster)</span>
<span id="cb7-31">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> verbose: </span>
<span id="cb7-32">                <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'[</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">] train loss = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>objective<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>loss(y, current_predictions)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb7-33">            </span>
<span id="cb7-34">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb7-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate </span>
<span id="cb7-36">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>([booster.predict(X) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> booster <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.boosters], axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb7-37">    </span>
<span id="cb7-38"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> TreeBooster():</span>
<span id="cb7-39"> </span>
<span id="cb7-40">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, g, h, params, max_depth, idxs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb7-41">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params</span>
<span id="cb7-42">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> max_depth</span>
<span id="cb7-43">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth must be nonnegative'</span></span>
<span id="cb7-44">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_child_weight <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-45">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb7-46">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg_lambda'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg_lambda'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb7-47">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.gamma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'gamma'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'gamma'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span></span>
<span id="cb7-48">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.colsample_bynode <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'colsample_bynode'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-49">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> params[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'colsample_bynode'</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span></span>
<span id="cb7-50">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(g, pd.Series): g <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g.values</span>
<span id="cb7-51">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(h, pd.Series): h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> h.values</span>
<span id="cb7-52">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> idxs <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(g))</span>
<span id="cb7-53">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X, g, h, idxs</span>
<span id="cb7-54">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(idxs), X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb7-55">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>g[idxs].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (h[idxs].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Eq (5)</span></span>
<span id="cb7-56">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span></span>
<span id="cb7-57">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb7-58">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._maybe_insert_child_nodes()</span>
<span id="cb7-59"></span>
<span id="cb7-60">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _maybe_insert_child_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb7-61">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c): <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._find_better_split(i)</span>
<span id="cb7-62">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span></span>
<span id="cb7-63">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs,<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx]</span>
<span id="cb7-64">        left_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb7-65">        right_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb7-66">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TreeBooster(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params, </span>
<span id="cb7-67">                                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[left_idx])</span>
<span id="cb7-68">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TreeBooster(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.params, </span>
<span id="cb7-69">                                 <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[right_idx])</span>
<span id="cb7-70"></span>
<span id="cb7-71">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@property</span></span>
<span id="cb7-72">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_leaf(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span></span>
<span id="cb7-73">    </span>
<span id="cb7-74">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _find_better_split(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, feature_idx):</span>
<span id="cb7-75">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs, feature_idx]</span>
<span id="cb7-76">        g, h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.g[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs], <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.h[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs]</span>
<span id="cb7-77">        sort_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(x)</span>
<span id="cb7-78">        sort_g, sort_h, sort_x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g[sort_idx], h[sort_idx], x[sort_idx]</span>
<span id="cb7-79">        sum_g, sum_h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> g.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(), h.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>()</span>
<span id="cb7-80">        sum_g_right, sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sum_g, sum_h</span>
<span id="cb7-81">        sum_g_left, sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span></span>
<span id="cb7-82"></span>
<span id="cb7-83">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb7-84">            g_i, h_i, x_i, x_i_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sort_g[i], sort_h[i], sort_x[i], sort_x[i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb7-85">            sum_g_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> g_i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> sum_g_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> g_i</span>
<span id="cb7-86">            sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> h_i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> h_i</span>
<span id="cb7-87">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_child_weight <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> x_i_next:<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb7-88">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_child_weight: <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb7-89"></span>
<span id="cb7-90">            gain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ((sum_g_left<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sum_h_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda))</span>
<span id="cb7-91">                            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (sum_g_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sum_h_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda))</span>
<span id="cb7-92">                            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (sum_g<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sum_h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.reg_lambda))</span>
<span id="cb7-93">                            ) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.gamma<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Eq(7) in the xgboost paper</span></span>
<span id="cb7-94">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> gain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far: </span>
<span id="cb7-95">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> feature_idx</span>
<span id="cb7-96">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gain</span>
<span id="cb7-97">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> x_i_next) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb7-98">                </span>
<span id="cb7-99">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb7-100">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.array([<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._predict_row(row) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> X.iterrows()])</span>
<span id="cb7-101"></span>
<span id="cb7-102">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _predict_row(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, row):</span>
<span id="cb7-103">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: </span>
<span id="cb7-104">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value</span>
<span id="cb7-105">        child <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-106">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right</span>
<span id="cb7-107">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> child._predict_row(row)</span></code></pre></div></div>
</div>
</section>
<section id="testing" class="level2">
<h2 class="anchored" data-anchor-id="testing">Testing</h2>
<p>Let’s take this baby for a spin and benchmark its performance against the actual XGBoost library. We use the scikit learn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_california_housing.html">California housing dataset</a> for benchmarking.</p>
<div id="cell-20" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> fetch_california_housing</span>
<span id="cb8-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split</span>
<span id="cb8-3">    </span>
<span id="cb8-4">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fetch_california_housing(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, return_X_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb8-5">X_train, X_test, y_train, y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(X, y, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, </span>
<span id="cb8-6">                                                    random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">43</span>)</span></code></pre></div></div>
</div>
<p>Let’s start with a nice friendly squared error objective function for training. We should probably have a future post all about how to define custom objective functions in XGBoost, but for now, here’s how I define squared error.</p>
<div id="cell-22" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> SquaredErrorObjective():</span>
<span id="cb9-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> loss(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, pred): <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.mean((y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pred)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb9-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> gradient(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, pred): <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> y</span>
<span id="cb9-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> hessian(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, pred): <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.ones(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y))</span></code></pre></div></div>
</div>
<p>Here I use a more or less arbitrary set of hyperparameters for training. Feel free to play around with tuning and trying other parameter combinations yourself.</p>
<div id="cell-24" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> xgboost <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> xgb</span>
<span id="cb10-2"></span>
<span id="cb10-3">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb10-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'learning_rate'</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>,</span>
<span id="cb10-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,</span>
<span id="cb10-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'subsample'</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>,</span>
<span id="cb10-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reg_lambda'</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>,</span>
<span id="cb10-8">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'gamma'</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>,</span>
<span id="cb10-9">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_child_weight'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>,</span>
<span id="cb10-10">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'base_score'</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>,</span>
<span id="cb10-11">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tree_method'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'exact'</span>,</span>
<span id="cb10-12">}</span>
<span id="cb10-13">num_boost_round <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span></span>
<span id="cb10-14"></span>
<span id="cb10-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train the from-scratch XGBoost model</span></span>
<span id="cb10-16">model_scratch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> XGBoostModel(params, random_seed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb10-17">model_scratch.fit(X_train, y_train, SquaredErrorObjective(), num_boost_round)</span>
<span id="cb10-18"></span>
<span id="cb10-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># train the library XGBoost model</span></span>
<span id="cb10-20">dtrain <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(X_train, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_train)</span>
<span id="cb10-21">dtest <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.DMatrix(X_test, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_test)</span>
<span id="cb10-22">model_xgb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> xgb.train(params, dtrain, num_boost_round)</span></code></pre></div></div>
</div>
<p>Let’s check the models’ performance on the held out test data to benchmark our implementation.</p>
<div id="cell-26" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">pred_scratch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model_scratch.predict(X_test)</span>
<span id="cb11-2">pred_xgb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model_xgb.predict(dtest)</span>
<span id="cb11-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'scratch score: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>SquaredErrorObjective()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>loss(y_test, pred_scratch)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb11-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'xgboost score: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>SquaredErrorObjective()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>loss(y_test, pred_xgb)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>scratch score: 0.2434125759558149
xgboost score: 0.24123239765807963</code></pre>
</div>
</div>
<p>Well, look at that! Our scratch-built SGBoost is looking pretty consistent with the library. Go us!</p>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>I’d say this is a pretty good milestone for us here at Random Realizations. We’ve been hammering away at the various concepts around gradient boosting, leaving a trail of equations and scratch-built algos in our wake. Today we put all of that together to create a legit scratch build of XGBoost, something that would have been out of reach for me before we embarked on this journey together over a year ago. To anyone with the patience to read through this stuff, cheers to you! I hope you’re learning and enjoying this as much as I am.</p>
</section>
<section id="reader-exercises" class="level2">
<h2 class="anchored" data-anchor-id="reader-exercises">Reader Exercises</h2>
<p>If you want to take this a step further and deepen your understanding and coding abilities, let me recommend some exercises for you.</p>
<ol type="1">
<li>Implement column subsampling. XGBoost itself provides column subsampling by tree, by level, and by node. Try implementing by tree first, then try adding by level or by node as well. These should be pretty straightforward to do.</li>
<li>Implement sparsity aware split finding for missing feature values (Algorithm 2 in the <a href="https://arxiv.org/abs/1603.02754">XGBoost paper</a>). This will be a little more involved, since you’ll need to refactor and modify several parts of the tree booster class.</li>
</ol>


</section>

 ]]></description>
  <category>python</category>
  <category>gradient boosting</category>
  <category>xgboost</category>
  <category>from scratch</category>
  <guid>https://randomrealizations.com/posts/xgboost-from-scratch/</guid>
  <pubDate>Sat, 07 May 2022 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/xgboost-from-scratch/thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>XGBoost Explained</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/xgboost-explained/</link>
  <description><![CDATA[ 





<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-explained/main.jpg" class="img-fluid figure-img"></p>
<figcaption>Tree branches on a chilly day in Johnson City</figcaption>
</figure>
</div>
<p>Ahh, XGBoost, what an absolutely stellar implementation of gradient boosting. Once Tianqi Chen and Carlos Guestrin of the University of Washington published the <a href="https://www.kdd.org/kdd2016/papers/files/rfp0697-chenAemb.pdf">XGBoost paper</a> and shared the <a href="https://github.com/dmlc/xgboost">open source code</a> in the mid 2010’s, the algorithm quickly gained adoption in the ML community, appearing in over half of winning Kagle submissions in 2015. Nowadays it’s certainly among the most popular gradient boosting libraries, along with LightGBM and CatBoost, although the highly scientific indicator of <a href="https://www.githubcompare.com/dmlc/xgboost+microsoft/lightgbm+catboost/catboost">GitHub stars per year</a> indicates that it is in fact the most beloved gradient boosting package of all. Since it was the first of the modern popular boosting frameworks, and since <a href="https://blog.dataiku.com/the-many-flavors-of-gradient-boosting-algorithms">benchmarking</a> indicates that no other boosting algorithm outperforms it, we can comfortably focus our attention on understanding XGBoost.</p>
<p>The XGBoost authors identify two key aspects of a machine learning system: (1) a flexible statistical model and (2) a scalable learning system to fit that model using data. XGBoost improves on both of these aspects, providing a more flexible and feature-rich statistical model and building a truly scalable system to fit it. In this post we’re going to focus on the statistical modeling innovations, outlining the key differences from the classic gradient boosting machine and divinginto the mathematical derivation of the XGBoost learning algorithm. If you’re not already familiar with <a href="../../posts/gradient-boosting-machine-from-scratch/">gradient boosting</a>, go back and read the earlier posts in the series before jumping in here.</p>
<p>Buckle up, dear reader. Today we understand how XGBoost works, no hand waving required.</p>
<section id="xgboost-is-a-gradient-boosting-machine" class="level2">
<h2 class="anchored" data-anchor-id="xgboost-is-a-gradient-boosting-machine">XGBoost is a Gradient Boosting Machine</h2>
<p>At a high level, XGBoost is an iteratively constructed composite model, just like the classic gradient boosting machine we discussed back in the <a href="../../posts/gradient-boosting-machine-from-scratch/">GBM post</a> . The final model takes the form</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i%20=%20F(%5Cmathbf%7Bx%7D_i)%20=%20b%20+%20%5Ceta%20%5Csum_%7Bk=1%7D%5EK%20f_k(%5Cmathbf%7Bx%7D_i)%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?b"> is the base prediction, <img src="https://latex.codecogs.com/png.latex?%5Ceta"> is the learning rate hyperparameter that helps control overfitting by reducing the contributions of each booster, and each of the <img src="https://latex.codecogs.com/png.latex?K"> boosters <img src="https://latex.codecogs.com/png.latex?f_k"> is a decision tree. To help us connect the dots between theory and code, whenever we encounter new hyperparameters, I’ll point out their names from the <a href="https://xgboost.readthedocs.io/en/stable/parameter.html">XGBoost Parameter Documentation</a>. So, <img src="https://latex.codecogs.com/png.latex?b"> can be set by <code>base_score</code>, and <img src="https://latex.codecogs.com/png.latex?%5Ceta"> is set by either <code>eta</code> or <code>learning_rate</code>.</p>
<p>XGBoost introduces two key statistical learning improvements over the classic gradient boosting model. First, it reimagines the gradient descent algorithm used for training, and second it uses a custom-built decision tree with extra functionality as its booster. We’ll dive into each of these key innovations in the following sections.</p>
</section>
<section id="descent-algorithm-innovations" class="level2">
<h2 class="anchored" data-anchor-id="descent-algorithm-innovations">Descent Algorithm Innovations</h2>
<section id="regularized-objective-function" class="level3">
<h3 class="anchored" data-anchor-id="regularized-objective-function">Regularized Objective Function</h3>
<p>In the post on <a href="../../posts/gradient-boosting-machine-with-any-loss-function/">GBM with any loss function</a>, we looked at loss functions of the form <img src="https://latex.codecogs.com/png.latex?%5Csum_i%20l(y_i,%5Chat%7By%7D_i)"> which compute some distance between targets <img src="https://latex.codecogs.com/png.latex?y_i"> and predictions <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> and sum them up over the training dataset. XGBoost introduces regularization into the objective function so that the objective takes the form</p>
<p><img src="https://latex.codecogs.com/png.latex?%20L%20=%20%5Csum_i%20l(y_i,%5Chat%7By%7D_i)%20+%20%5Csum_k%20%5COmega(f_k)%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?l"> is some twice-differentiable loss function. <img src="https://latex.codecogs.com/png.latex?%5COmega"> is a regularization that penalizes the complexity of each tree booster, taking the form</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5COmega(f)%20=%20%5Cgamma%20T%20+%20%5Cfrac%7B1%7D%7B2%7D%20%5Clambda%20%7C%7Cw%7C%7C%5E2%20"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?T"> is the number of leaf nodes and <img src="https://latex.codecogs.com/png.latex?%7C%7Cw%7C%7C%5E2"> is the squared sum of the leaf prediction values. This introduces two new hyperparameters: <img src="https://latex.codecogs.com/png.latex?%5Cgamma"> which penalizes the number of leaf nodes and <img src="https://latex.codecogs.com/png.latex?%5Clambda"> which is the L-2 regularization parameter for leaf predicted values. These are set by <code>gamma</code> and <code>reg_lambbda</code> in the XGBoost parametrization. Together, these provide powerful new controls to reduce overfitting due to overly complex tree boosters. Note that <img src="https://latex.codecogs.com/png.latex?%5Cgamma=%5Clambda=0"> reduces the objective back to an unregularized loss function as used in the classic GBM.</p>
</section>
<section id="an-aside-on-newtons-method" class="level3">
<h3 class="anchored" data-anchor-id="an-aside-on-newtons-method">An Aside on Newton’s Method</h3>
<p>As we’ll see soon, XGBoost uses <a href="https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization">Newton’s Method</a> to minimize its objective function, so let’s start with a quick refresher.</p>
<p>Newton’s method is an iterative procedure for minimizing a function <img src="https://latex.codecogs.com/png.latex?s(x)">. At each step we have some input <img src="https://latex.codecogs.com/png.latex?x_t">, and our goal is to find a nudge value <img src="https://latex.codecogs.com/png.latex?u"> such that</p>
<p><img src="https://latex.codecogs.com/png.latex?%20s(x_t%20+%20u)%20%5Cle%20s(x_t)"></p>
<p>To find a good nudge value <img src="https://latex.codecogs.com/png.latex?u">, we generate a local quadratic approximation of the function in the neighborhood of the input <img src="https://latex.codecogs.com/png.latex?x_t">, and then we find the input value that would bring us to the minimum of the quadratic approximation.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/xgboost-explained/newton.png" class="img-fluid figure-img"></p>
<figcaption>Schematic of Newton’s method</figcaption>
</figure>
</div>
<p>The figure shows a single Newton step where we start at <img src="https://latex.codecogs.com/png.latex?x_t">, find the local quadratic approximation, and then jump a distance <img src="https://latex.codecogs.com/png.latex?u"> along the <img src="https://latex.codecogs.com/png.latex?x">-axis to land at the minimum of the quadratic. If we iterate in this way, we are likely to land close to the minimum of <img src="https://latex.codecogs.com/png.latex?s(x)">.</p>
<p>So how do we compute the quadratic approximation? We use the second order Taylor series expansion of <img src="https://latex.codecogs.com/png.latex?s(x)"> near the point <img src="https://latex.codecogs.com/png.latex?x_t">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20s(x_t%20+%20u)%20%5Capprox%20%20s(x_t)%20+%20s'(x_t)u%20+%20%5Cfrac%7B1%7D%7B2%7D%20s''(x_t)%20u%5E2%20"></p>
<p>To find the nudge value <img src="https://latex.codecogs.com/png.latex?u"> that minimizes the quadratic approximation, we can take the derivative with respect to <img src="https://latex.codecogs.com/png.latex?u">, set it to zero, and solve for <img src="https://latex.codecogs.com/png.latex?u">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%200%20=%20%5Cfrac%7Bd%7D%7Bdu%7D%20%20%5Cleft%20(%20s(x_t)%20+%20s'(x_t)u%20+%20%5Cfrac%7B1%7D%7B2%7D%20s''(x_t)%20u%5E2%20%5Cright%20)%20=%20s'(x_t)%20+%20s''(x_t)%20u%20"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Crightarrow%20u%5E*%20=%20-%5Cfrac%7Bs'(x_t)%7D%7Bs''(x_t)%7D%20"></p>
<p>And as long as <img src="https://latex.codecogs.com/png.latex?s''(x_t)%3E0"> (i.e., the parabola is pointing up), <img src="https://latex.codecogs.com/png.latex?s(x_t%20+%20u%5E*)%20%5Cle%20s(x_t)">.</p>
</section>
<section id="tree-boosting-with-newtons-method" class="level3">
<h3 class="anchored" data-anchor-id="tree-boosting-with-newtons-method">Tree Boosting with Newton’s Method</h3>
<p>This lands us at the heart of XGBoost, which uses Newton’s method, rather than gradient descent, to guide each round of boosting. This explanation will correspond very closely to section 2.2 of the XGBoost paper, but here I’ll explicitly spell out some of the intermediate steps which are omitted from their derivation, and you’ll get some additional commentary from me along the way.</p>
<section id="newton-descent-in-tree-space" class="level4">
<h4 class="anchored" data-anchor-id="newton-descent-in-tree-space">Newton Descent in Tree Space</h4>
<p>Suppose we’ve done <img src="https://latex.codecogs.com/png.latex?t-1"> boosting rounds, and we want to add the <img src="https://latex.codecogs.com/png.latex?t">-th booster to our composite model. Our current model’s prediction for instance <img src="https://latex.codecogs.com/png.latex?i"> is <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i%5E%7B(t-1)%7D">. If we add a new tree booster <img src="https://latex.codecogs.com/png.latex?f_t"> to our model, the objective function would give</p>
<p><img src="https://latex.codecogs.com/png.latex?%20L%5E%7B(t)%7D%20=%20%5Csum_%7Bi=1%7D%5En%20l(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%20+%20f_t(%5Cmathbf%7Bx%7D_i))%20+%20%5COmega(f_t)%20"></p>
<p>We need to choose <img src="https://latex.codecogs.com/png.latex?f_t"> so that it decreases the loss, i.e.&nbsp;we want</p>
<p><img src="https://latex.codecogs.com/png.latex?%20l(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%20+%20f_t(%5Cmathbf%7Bx%7D_i))%20%5Cle%20l(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D)"></p>
<p>Does that sound familiar? In the previous section we used Newton’s method to find a value of <img src="https://latex.codecogs.com/png.latex?u"> that would make <img src="https://latex.codecogs.com/png.latex?s(x_t%20+%20u)%20%5Cle%20s(x_t)">. Let’s try the same thing with our loss function. To be explicit, the parallels are: <img src="https://latex.codecogs.com/png.latex?s(%5Ccdot)%20%5Crightarrow%20l(y_i,%20%5Ccdot)">, <img src="https://latex.codecogs.com/png.latex?x_t%20%5Crightarrow%20%5Chat%7By%7D_i%5E%7B(t-1)%7D">, and <img src="https://latex.codecogs.com/png.latex?u%20%5Crightarrow%20f_t(%5Cmathbf%7Bx%7D_i)">.</p>
<p>Let’s start by finding the second order Taylor series approximation for the loss around the point <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i%5E%7B(t-1)%7D">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20l(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%20+%20f_t(%5Cmathbf%7Bx%7D_i))%20%5Capprox%20l(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D)%20+%20g_i%20f_t(%5Cmathbf%7Bx%7D_i)%20+%20%5Cfrac%7B1%7D%7B2%7D%20h_i%20f_t(%5Cmathbf%7Bx%7D_i)%5E2%20"></p>
<p>where</p>
<p><img src="https://latex.codecogs.com/png.latex?%20g_i%20=%20%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7D%20l(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D)"></p>
<p>and</p>
<p><img src="https://latex.codecogs.com/png.latex?%20h_i%20=%20%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%5E2%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7D%20l(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D)"></p>
<p>are the first and second order partial derivatives of the loss with respect to the current predictions. The XGBoost paper calls these the gradients and hessians, respectively. Remember that when we specify an actual loss function to use, we would also specify the functional form of the gradients and hessians, so that they are directly computable.</p>
<p>Now we can go back and substitute our quadratic approximation in for the loss function to get an approximation of the objective function in the neighborhood of <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i%5E%7B(t-1)%7D">..</p>
<p><img src="https://latex.codecogs.com/png.latex?%20L%5E%7B(t)%7D%20%5Capprox%20%5Csum_%7Bi=1%7D%5En%20%5Bl(y_i,%20%5Chat%7By%7D_i%5E%7B(t-1)%7D)%20+%20g_i%20f_t(%5Cmathbf%7Bx%7D_i)%20+%20%5Cfrac%7B1%7D%7B2%7D%20h_i%20f_t(%5Cmathbf%7Bx%7D_i)%5E2%5D%20+%20%5COmega(f_t)%20"></p>
<p>Since <img src="https://latex.codecogs.com/png.latex?l(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D)"> is constant regardless of our choice of <img src="https://latex.codecogs.com/png.latex?f_t">, we can drop it and instead work with the modified objective, which gives us Equation (3) from the paper.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Ctilde%7BL%7D%5E%7B(t)%7D%20=%20%5Csum_%7Bi=1%7D%5En%20%5B%20g_i%20f_t(%5Cmathbf%7Bx%7D_i)%20+%20%5Cfrac%7B1%7D%7B2%7D%20h_i%20f_t(%5Cmathbf%7Bx%7D_i)%5E2%5D%20+%20%5COmega(f_t)%20"></p>
<p>Now the authors are about to do something great. They’re about to show how to directly compute the optimal prediction values for the leaf nodes of <img src="https://latex.codecogs.com/png.latex?f_t">. We’ll circle back in a moment about how we find a good structure for <img src="https://latex.codecogs.com/png.latex?f_t">, i.e.&nbsp;good node splits, but we’re going to find the optimal predicted values for any tree structure having <img src="https://latex.codecogs.com/png.latex?T"> terminal nodes. Let <img src="https://latex.codecogs.com/png.latex?I_j"> denote the set of instances <img src="https://latex.codecogs.com/png.latex?i"> that are in the <img src="https://latex.codecogs.com/png.latex?j">-th leaf node of <img src="https://latex.codecogs.com/png.latex?f_t">. Then we can rewrite the objective.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Ctilde%7BL%7D%5E%7B(t)%7D%20=%20%5Csum_%7Bj=1%7D%5ET%20%5Cleft%20%5B%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20g_i%20f_t(%5Cmathbf%7Bx%7D_i)%20+%20%5Cfrac%7B1%7D%7B2%7D%20%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20h_i%20f_t(%5Cmathbf%7Bx%7D_i)%5E2%20%5Cright%20%5D%20+%20%5COmega(f_t)"></p>
<p>We notice that for all instances in <img src="https://latex.codecogs.com/png.latex?I_j">, the tree yields the same predicted value <img src="https://latex.codecogs.com/png.latex?f_t(%5Cmathbf%7Bx%7D_i)=w_j">. Substituting in <img src="https://latex.codecogs.com/png.latex?w_j"> for the predicted values and expanding <img src="https://latex.codecogs.com/png.latex?%5COmega(f_t)"> we get</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Ctilde%7BL%7D%5E%7B(t)%7D%20=%20%5Csum_%7Bj=1%7D%5ET%20%5Cleft%20%5B%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20g_i%20w_j%20+%20%5Cfrac%7B1%7D%7B2%7D%20%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20h_i%20w_j%5E2%20%5Cright%20%5D%20+%20%5Cgamma%20T%20+%20%5Cfrac%7B1%7D%7B2%7D%20%5Clambda%20%5Csum_%7Bj=1%7D%5ET%20w_j%5E2"></p>
<p>Rearranging terms we obtain Equation (4).</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Ctilde%7BL%7D%5E%7B(t)%7D%20=%20%5Csum_%7Bj=1%7D%5ET%20%5Cleft%20%5B%20w_j%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20g_i%20+%20%5Cfrac%7B1%7D%7B2%7D%20%20w_j%5E2%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20h_i%20+%20%5Clambda%20%5Cright%20)%20%20%5Cright%20%5D%20+%20%5Cgamma%20T%20"></p>
<p>For each leaf node <img src="https://latex.codecogs.com/png.latex?j">, our modified objective function is quadratic in <img src="https://latex.codecogs.com/png.latex?w_j">. To find the optimal predicted values we take the derivative, set to zero, and solve for <img src="https://latex.codecogs.com/png.latex?w_j">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%200%20=%20%5Cfrac%7Bd%7D%7Bdw_j%7D%20%5Cleft%20%5B%20w_j%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20g_i%20+%20%5Cfrac%7B1%7D%7B2%7D%20%20w_j%5E2%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20h_i%20+%20%5Clambda%20%5Cright%20)%20%20%5Cright%20%5D%20=%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20h_i%20+%20%5Clambda%20%5Cright%20)%20w_j%20+%20%5Csum_%7Bi%20%5Cin%20I_j%7D%20g_i%20"></p>
<p>This yields Equation (5).</p>
<p><img src="https://latex.codecogs.com/png.latex?%20w_j%5E*%20=%20-%20%5Cfrac%7B%5Csum_%7Bi%20%5Cin%20I_j%7D%20g_i%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I_j%7D%20h_i%20+%20%5Clambda%20%7D%20"></p>
</section>
<section id="split-finding" class="level4">
<h4 class="anchored" data-anchor-id="split-finding">Split Finding</h4>
<p>Now that we know how to find the optimal predicted value for any leaf node, we need to identify a criterion for finding a good tree structure, which boils down to finding the best split for a given node. Back in the [decision tree from scratch](/decision-tree-from-scratch post, we derived a split evaluation metric based on the reduction in the objective function associated with a particular split.<br>
To do that, first we need a way to compute the objective function given a particular tree structure. Substituting the optimal predicted values <img src="https://latex.codecogs.com/png.latex?w_j%5E*"> into the objective function, we get Equation (6).</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Ctilde%7BL%7D%5E%7B(t)%7D%20=%20-%5Cfrac%7B1%7D%7B2%7D%20%5Csum_%7Bj=1%7D%5ET%20%5Cfrac%7B%20(%5Csum_%7Bi%20%5Cin%20I_j%7D%20g_i%20)%5E2%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I_j%7D%20h_i%20+%20%5Clambda%7D%20+%20%5Cgamma%20T%20"></p>
<p>We can then evaluate potential splits by comparing the objective before making a split to the objective after making a split, where the split with the maximum reduction in objective (a.k.a. gain) is best.</p>
<p>More formally, let <img src="https://latex.codecogs.com/png.latex?I"> be the set of <img src="https://latex.codecogs.com/png.latex?n"> data instances in the current node, and let <img src="https://latex.codecogs.com/png.latex?I_L"> and <img src="https://latex.codecogs.com/png.latex?I_R"> be the instances that fall into the left and right child nodes of a proposed split. Let <img src="https://latex.codecogs.com/png.latex?L"> be the total loss for all instances in the node, while <img src="https://latex.codecogs.com/png.latex?L_L"> and <img src="https://latex.codecogs.com/png.latex?L_R"> are the losses for the left and right child nodes. The total loss contributed by instances in node <img src="https://latex.codecogs.com/png.latex?I"> prior to any split is</p>
<p><img src="https://latex.codecogs.com/png.latex?L_%7B%5Ctext%7Bbefore%20split%7D%7D%20=%20-%5Cfrac%7B1%7D%7B2%7D%20%5Cfrac%7B%20(%5Csum_%7Bi%20%5Cin%20I%7D%20g_i%20)%5E2%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I%7D%20h_i%20+%20%5Clambda%7D%20+%20%5Cgamma%20"></p>
<p>And the loss after splitting <img src="https://latex.codecogs.com/png.latex?I"> into <img src="https://latex.codecogs.com/png.latex?I_L"> and <img src="https://latex.codecogs.com/png.latex?I_R"> is</p>
<p><img src="https://latex.codecogs.com/png.latex?L_%7B%5Ctext%7Bafter%20split%7D%7D%20=%20L_L%20+%20L_R%20=%20-%5Cfrac%7B1%7D%7B2%7D%20%20%5Cfrac%7B%20(%5Csum_%7Bi%20%5Cin%20I_L%7D%20g_i%20)%5E2%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I_L%7D%20h_i%20+%20%5Clambda%7D%20-%5Cfrac%7B1%7D%7B2%7D%20%20%5Cfrac%7B%20(%5Csum_%7Bi%20%5Cin%20I_R%7D%20g_i%20)%5E2%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I_R%7D%20h_i%20+%20%5Clambda%7D%20+%202%20%5Cgamma%20"></p>
<p>The gain from this split is then</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5CDelta%20L%20=%20L_%7B%5Ctext%7Bbefore%20split%7D%7D%20-%20%20L_%7B%5Ctext%7Bafter%20split%7D%7D%20=%20L%20-%20(L_L%20+%20L_R)"> <img src="https://latex.codecogs.com/png.latex?%5CDelta%20L%20=%20%5Cfrac%7B1%7D%7B2%7D%20%5Cleft%20%5B%20%5Cfrac%7B%20(%5Csum_%7Bi%20%5Cin%20I_L%7D%20g_i%20)%5E2%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I_L%7D%20h_i%20+%20%5Clambda%7D%20+%20%5Cfrac%7B%20(%5Csum_%7Bi%20%5Cin%20I_R%7D%20g_i%20)%5E2%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I_R%7D%20h_i%20+%20%5Clambda%7D%20-%20%5Cfrac%7B%20(%5Csum_%7Bi%20%5Cin%20I%7D%20g_i%20)%5E2%20%7D%20%7B%5Csum_%7Bi%20%5Cin%20I%7D%20h_i%20+%20%5Clambda%7D%20%5Cright%20%5D%20-%20%5Cgamma%20"></p>
<p>which is Equation (7) from the paper. In practice it makes sense to accept a split only if the gain is positive, thus the <img src="https://latex.codecogs.com/png.latex?%5Cgamma"> parameter sets the minimum gain required to make a further split. This is why <img src="https://latex.codecogs.com/png.latex?%5Cgamma"> can be set with the parameter <code>gamma</code> or the more descriptive<code>min_loss_split</code>.</p>
</section>
</section>
</section>
<section id="tree-booster-innovations" class="level2">
<h2 class="anchored" data-anchor-id="tree-booster-innovations">Tree Booster Innovations</h2>
<section id="missing-values-and-sparsity-aware-split-finding" class="level3">
<h3 class="anchored" data-anchor-id="missing-values-and-sparsity-aware-split-finding">Missing Values and Sparsity-Aware Split Finding</h3>
<p>The XGBoost paper also introduces a modified algorithm for tree split finding which explicitly handles missing feature values. Recall that in order to find the best threshold value for a given feature, we can simply try all possible threshold values, recording the score for each. If some feature values are missing, the XGBoost split finding algorithm simply scores each threshold twice: once with missing value instances in the left node and once with them in the right node. The best split will then specify both the threshold value and to which node instances with missing values should be assigned. The paper calls this the sparsity aware split finding routine, which is defined as Algorithm 2.</p>
</section>
<section id="preventing-further-splitting" class="level3">
<h3 class="anchored" data-anchor-id="preventing-further-splitting">Preventing Further Splitting</h3>
<p>In addition to <code>min_loss_split</code> discussed above, XGBoost offers another parameter for limiting further tree splitting called <code>min_child_weight</code>. This name is a little confusing to me because the word “weight” has various meanings. In the context of this parameter, “weight” refers to the sum of the hessians <img src="https://latex.codecogs.com/png.latex?%5Csum%20h_i"> over instances in the node. For squared error loss <img src="https://latex.codecogs.com/png.latex?h_i=1">, so this is equivalent to the number of samples. Thus this parameter generalizes the notion of the minimum number of samples allowed in a terminal node.</p>
</section>
<section id="sampling" class="level3">
<h3 class="anchored" data-anchor-id="sampling">Sampling</h3>
<p>XGBoost takes a cue from Random Forest and introduces both column and row subsampling. These sampling methods can prevent overfitting and reduce training time by limiting the amount of data to be processed during boosting.</p>
<p>Like random forest, XGBoost implements column subsampling, which limits tree split finding to randomly selected subsets of features. XGBoost provides column sampling for each tree, for each depth level within a tree, and for each split point within a tree, controlled by <code>colsample_bytree</code>, <code>colsample_bbylevel</code>, and <code>colsample_bbynode</code> respectively.</p>
<p>One interesting distinction is that XGBoost implements row sampling without replacement using <code>subbsample</code>, whereas random forest uses bootstrapping. The choice to bootstrap rows in RF probably spurred from a desire to use as much data as possible while training on the smaller datasets of the 1990’s when RF was developed. With larger datasets and the ability to generate a large number of trees, XGBoost simply takes a subsample of rows for each tree.</p>
</section>
</section>
<section id="scalability" class="level2">
<h2 class="anchored" data-anchor-id="scalability">Scalability</h2>
<p>Even though we’re focused on statistical learning, I figured I’d comment on why XGBoost is highly scalable. Basically it boils down to efficient, parallelizable, and distributable methods for growing trees. You’ll notice there is a <code>tree_method</code> parameter which allows you to choose between the greedy exact algorithm (like the one we discussed in the decision tree from scratch post) and the approximate algorithm, which offers various scalability-related functionality, notably including the ability to consider only a small number of candidate split points instead of trying all possible splits. The algorithm also uses clever tricks like pre-sorting data for split finding and caching frequently needed values.</p>
<section id="why-xgboost-is-so-successful" class="level3">
<h3 class="anchored" data-anchor-id="why-xgboost-is-so-successful">Why XGBoost is so Successful</h3>
<p>As I mentioned in the intro, XGBoost is simply a very good implementation of the gradient boosting tree model. Therefore it inherits all the benefits of <a href="../../consider-the-decision-tree">decision trees and tree ensembles</a>, while making even further improvements over the classic gradient boosting machine. These improvements boil down to</p>
<ol type="1">
<li>more ways to control overfitting</li>
<li>elegant handling of custom objectives</li>
<li>scalability</li>
</ol>
<p>First, XGBoost introduces two new tree regularization hyperparameters <img src="https://latex.codecogs.com/png.latex?%5Cgamma"> and <img src="https://latex.codecogs.com/png.latex?%5Clambda"> which are baked directly into its objective function. Combining these with the additional column and row sampling functionality provides a variety of ways to reduce overfitting.</p>
<p>Second, the XGBoost formulation provides a much more elegant way to train models on custom objective functions. Recall that for <a href="../../posts/gradient-boosting-machine-with-any-loss-function/">custom objectives</a>, the classic GBM finds tree structure by fitting a squared error decision tree to the gradients of the loss function and then sets each leaf’s predicted value by running a numerical optimization routine to find the optimal predicted value.</p>
<p>The XGBoost formulation improves on this two-stage approach by unifying the generation of tree structure and predicted values. Both the split scoring metric and the predicted values are directly computable from the instance gradient and hessian values, which are connected directly back to the overall training objective. This also removes the need for additional numerical optimizations, which contributes to speed, stability, and scalability.</p>
<p>Finally, speaking of scalability, XGBoost emerged at a time when industrial dataset size was exploding. Many use cases require scalable ML systems, and all use cases benefit from faster training and higher model development velocity.</p>
</section>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Well, there you go, those are the salient ideas behind XGBoost, the gold standard in gradient boosting model implementations. Hopefully now we all understand the mathematical basis for the algorithm and appreciate the key improvements it makes over the classic GBM. If you want to go even deeper, you can join us for the next post where we’ll roll up our sleeves and implement XGBoost entirely from scratch.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p><a href="https://www.kdd.org/kdd2016/papers/files/rfp0697-chenAemb.pdf">The XGBoost paper</a></p>
</section>
<section id="exercise" class="level2">
<h2 class="anchored" data-anchor-id="exercise">Exercise</h2>
<p>Proove that the XGBoost Newton Descent generalizes the classic GBM gradient descent. Hint: show that XGBoost with a squared error objective and no regularization reduces to the classic GBM.</p>


</section>

 ]]></description>
  <category>gradient boosting</category>
  <category>xgboost</category>
  <guid>https://randomrealizations.com/posts/xgboost-explained/</guid>
  <pubDate>Sun, 13 Mar 2022 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/xgboost-explained/thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Decision Tree from Scratch</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/decision-tree-from-scratch/</link>
  <description><![CDATA[ 





<p><img src="https://randomrealizations.com/posts/decision-tree-from-scratch/thumbnail.png" title="decision tree" class="img-fluid"></p>
<p>Yesterday we had a lovely discussion about the key strengths and weaknesses of decision trees and why tree ensembles are so great. But today, gentle reader, we abandon our philosophizing and get down to the business of implementing one of these decision trees from scratch.</p>
<p>A note before we get started. This is going to be the most involved scratch-build that we’ve done at Random Realizations so far. It is not the kind of algorithm that I could just sit down and write all at once. We need to start with a basic frame and then add functionality step by step, testing all along the way to make sure things are working properly. Since I’m writing this in a jupyter notebook, I’ll try to give you a sense for how I actually put the algorithm together interactively in pieces, eventually landing on a fully-functional final product.</p>
<p>Shall we?</p>
<section id="binary-tree-data-structure" class="level2">
<h2 class="anchored" data-anchor-id="binary-tree-data-structure">Binary Tree Data Structure</h2>
<p>A decision tree takes a dataset with features and a target, partitions the feature space into chunks, and assigns a prediction value to each chunk. Since each partitioning step divides one chunk in two, and since the partitioning is done recursively, it’s natural to use a binary tree data structure to represent a decision tree.</p>
<p>The basic idea of the binary tree is that we define a class to represent nodes in the tree. If we want to add children to a given node, we simply assign them as attributes of the parent node. The child nodes we add are themselves instances of the same class, so we can add children to them in the same way.</p>
<p>Let’s start out with a simple class for our decision tree. It takes a single value called <code>max_depth</code> as input, which will dictate how many layers of child nodes should be inserted below the root. This controls the depth of the tree. As long as <code>max_depth</code> is positive, the parent will instantiate two new instances of the binary tree node class, passing along <code>max_depth</code> decremented by one and attaching the two children to itself as attributes called <code>left</code> and <code>right</code>.</p>
<div id="cell-5" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> math</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np </span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span></code></pre></div></div>
</div>
<div id="cell-6" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> DecisionTree():</span>
<span id="cb2-2"></span>
<span id="cb2-3">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, max_depth):</span>
<span id="cb2-4">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth must be nonnegative'</span></span>
<span id="cb2-5">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> max_depth</span>
<span id="cb2-6">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb2-7">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-8">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</div>
<p>Let’s make a new instance of our decision tree class, a tree with depth 2.</p>
<div id="cell-8" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/decision-tree-from-scratch/binary_tree.png" class="img-fluid figure-img"></p>
<figcaption>Binary tree structure diagram</figcaption>
</figure>
</div>
<p>We can access individual nodes and check their value of <code>max_depth</code>.</p>
<div id="cell-11" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">t.max_depth, t.left.max_depth, t.left.right.max_depth</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="5">
<pre><code>(2, 1, 0)</code></pre>
</div>
</div>
<p>Our full decision tree can expand on this idea where each node receives some input, modifies it, creates two child nodes, and passes the modified input along to them. Specifically, each node in our decision tree will receive a dataset, determine how best to split the dataset into two parts, create two child nodes, and pass one part of the data to the left child and the other part to the right child.</p>
<p>All we have to do now is add some additional functionality to our decision tree. First we’ll start by capturing all the inputs we need to grow a tree, which include the feature dataframe <code>X</code>, the target array <code>y</code>, <code>max_depth</code> to explicitly limit tree depth, <code>min_samples_leaf</code> to specify the minimum number of observations that are allowed in a leaf node, and an optional <code>idxs</code> which specifies the indices of data that the node should use. The indices argument is useful for users of our decision tree because it will allow them to implement row subsampling in ensemble methods like random forest. It will also be handy for internal use inside the decision tree when passing data along to child nodes; instead of passing copies of the two data subsets, we’ll just pass a reference to the full dataset and pass along a set of indices to identify that node’s instance subset.</p>
<p>Once we get our input, we’ll do a little bit of input validation and store things that we want to keep as object attributes. In case this is a leaf node, we’ll go ahead and compute its predicted value; since this is a regression tree, the prediction is just the mean of the target <code>y</code>. We’ll also go ahead and initialize a score metric which we’ll use to help us find the best split later; since lower scores are going to be better, we’ll initialize it to positive infinity. Finally, we’ll push the logic to add child nodes into a method called <code>_maybe_insert_child_nodes</code> that we’ll define next.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>a leading underscore in a method name indicates the method is for internal use and not part of the user-facing API of the class.</p>
</div>
</div>
<div id="cell-14" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> DecisionTree():</span>
<span id="cb6-2"></span>
<span id="cb6-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, y, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, idxs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb6-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth must be nonnegative'</span></span>
<span id="cb6-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> min_samples_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_samples_leaf must be positive'</span></span>
<span id="cb6-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> min_samples_leaf, max_depth</span>
<span id="cb6-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(y, pd.Series): y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.values</span>
<span id="cb6-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> idxs <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y))</span>
<span id="cb6-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X, y, idxs</span>
<span id="cb6-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(idxs), X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb6-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.mean(y[idxs]) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># node's prediction value</span></span>
<span id="cb6-12">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'inf'</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># initial loss before split finding</span></span>
<span id="cb6-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb6-14">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._maybe_insert_child_nodes()</span>
<span id="cb6-15">            </span>
<span id="cb6-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _maybe_insert_child_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb6-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span></code></pre></div></div>
</div>
<p>Now in order to test our class, we’ll need some actual data. We can use the same scikit-learn diabetes data from the last post.</p>
<div id="cell-16" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> load_diabetes</span>
<span id="cb7-2"></span>
<span id="cb7-3">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_diabetes(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, return_X_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
</div>
<div id="cell-17" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(X, y, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span></code></pre></div></div>
</div>
<p>So far, so good.</p>
</section>
<section id="inserting-child-nodes" class="level2">
<h2 class="anchored" data-anchor-id="inserting-child-nodes">Inserting Child Nodes</h2>
<p>Our node inserting function <code>_maybe_insert_child_nodes</code> needs to first find the best split; then if a valid split exists, it needs to insert the child nodes. To find the best valid split, we need to loop through the columns and search each one for the best valid split. Again we’ll push the logic of finding the best split into a function that we’ll define later. Next if no split was found, we need to bail by returning before trying to insert the child nodes. To check if this node is a leaf (i.e.&nbsp;it shouldn’t have child nodes), we define a property called <code>is_leaf</code> which will just check if the best score so far is still infinity, in which case no split was found and the node is a leaf.</p>
<p>If a valid split was found, then we need to insert the child nodes. We’ll assume that our split finding function assigned attributes called <code>split_feature_idx</code> and <code>threshold</code> to tell us the split feature’s index and the split threshold value. We then use these to compute the indices of the data to be passed to the child nodes; the left child gets instances where the split feature value is less than or equal to the threshold, and the right child node gets instances where the split feature value is greater than the threshold. Then we create two new decision trees, passing the corresponding data indices to each and assigning them to the <code>left</code> and <code>right</code> attributes of the current node.</p>
<div id="cell-20" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _maybe_insert_child_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c): </span>
<span id="cb9-3">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._find_better_split(j)</span>
<span id="cb9-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># do not insert children</span></span>
<span id="cb9-5">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> </span>
<span id="cb9-6">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs,<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx]</span>
<span id="cb9-7">        left_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb9-8">        right_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb9-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf, </span>
<span id="cb9-10">                                  <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[left_idx])</span>
<span id="cb9-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf, </span>
<span id="cb9-12">                                  <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[right_idx])</span>
<span id="cb9-13"></span>
<span id="cb9-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _find_better_split(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, feature_idx):</span>
<span id="cb9-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb9-16">    </span>
<span id="cb9-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@property</span></span>
<span id="cb9-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_leaf(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'inf'</span>)</span></code></pre></div></div>
</div>
<p>To test these new methods , we can assign them to our <code>DecisionTree</code> class and create a new class instance to make sure things are still working.</p>
<div id="cell-22" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">DecisionTree._maybe_insert_child_nodes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _maybe_insert_child_nodes</span>
<span id="cb10-2">DecisionTree._find_better_split <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _find_better_split</span>
<span id="cb10-3">DecisionTree.is_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> is_leaf</span>
<span id="cb10-4">t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(X, y, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)</span></code></pre></div></div>
</div>
<p>Yep, we’re still looking good.</p>
</section>
<section id="split-finding" class="level2">
<h2 class="anchored" data-anchor-id="split-finding">Split Finding</h2>
<p>Now we need to fill in the functionality of the split finding method. The overall strategy is to consider every possible way to split on the current feature, measuring the quality of each potential split with some scoring mechanism, and keeping track of the best split we’ve seen so far. We’ll come back to the issue of how to try all the possible splits in a moment, but let’s start by figuring out how to score a particular potential split.</p>
<p>Like other machine learning models, trees are trained by attempting to minimize some loss function that measures how well the model predicts the target data. We’ll be training our regression tree to minimize squared error.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20L%20=%20%5Csum_%7Bi=1%7D%5En%20(y_i-%5Chat%7By%7D_i)%5E2"></p>
<p>For a given node, we can replace <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D"> with <img src="https://latex.codecogs.com/png.latex?%5Cbar%7By%7D"> because each node uses the sample mean of its target instances as its prediction. We can then rewrite the loss for a given node as</p>
<p><img src="https://latex.codecogs.com/png.latex?%20L%20=%20%5Csum_%7Bi=1%7D%5En(y_i%20-%20%5Cbar%7By%7D)%5E2%20"> <img src="https://latex.codecogs.com/png.latex?%20%20=%20%5Csum_%7Bi=1%7D%5En(y_i%5E2%20-2y_i%5Cbar%7By%7D%20+%20%5Cbar%7By%7D%5E2)%20%20"> <img src="https://latex.codecogs.com/png.latex?%20%20=%20%5Csum_%7Bi=1%7D%5Eny_i%5E2%20-2%5Cbar%7By%7D%5Csum_%7Bi=1%7D%5Eny_i%20+%20n%5Cbar%7By%7D%5E2%20"> <img src="https://latex.codecogs.com/png.latex?%20%20=%20%5Csum_%7Bi=1%7D%5Eny_i%5E2%20-%20%5Cfrac%7B1%7D%7Bn%7D%20%5Cleft%20(%20%5Csum_%7Bi=1%7D%5Eny_i%20%5Cright%20)%5E2%20"></p>
<p>We can then evaluate potential splits by comparing the loss after splitting to the loss before splitting, where the split with the greatest loss reduction is best. Let’s work out a simple expression for the loss reduction from a given split.</p>
<p>Let <img src="https://latex.codecogs.com/png.latex?I"> be the set of <img src="https://latex.codecogs.com/png.latex?n"> data instances in the current node, and let <img src="https://latex.codecogs.com/png.latex?I_L"> and <img src="https://latex.codecogs.com/png.latex?I_R"> be the instances that fall into the left and right child nodes of a proposed split. Let <img src="https://latex.codecogs.com/png.latex?L"> be the total loss for all instances in the node, while <img src="https://latex.codecogs.com/png.latex?L_L"> and <img src="https://latex.codecogs.com/png.latex?L_R"> are the losses for the left and right child nodes. The total loss contributed by instances in <img src="https://latex.codecogs.com/png.latex?I"> prior to any split is</p>
<p><img src="https://latex.codecogs.com/png.latex?L_%7B%5Ctext%7Bbefore%20split%7D%7D%20=%20L%20=%20%20%5Csum_%7Bi%20%5Cin%20I%7D%20y_i%5E2%20-%20%5Cfrac%7B1%7D%7Bn%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I%7D%20y_i%20%5Cright%20)%5E2%20"></p>
<p>And the loss after splitting <img src="https://latex.codecogs.com/png.latex?I"> into <img src="https://latex.codecogs.com/png.latex?I_L"> and <img src="https://latex.codecogs.com/png.latex?I_R"> is</p>
<p><img src="https://latex.codecogs.com/png.latex?L_%7B%5Ctext%7Bafter%20split%7D%7D%20=%20L_L%20+%20L_R%20=%20%20%5Csum_%7Bi%20%5Cin%20I_L%7D%20y_i%5E2%20-%20%5Cfrac%7B1%7D%7Bn_L%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_L%7D%20y_i%20%5Cright%20)%5E2%20+%20%5Csum_%7Bi%20%5Cin%20I_R%7D%20y_i%5E2%20-%20%5Cfrac%7B1%7D%7Bn_R%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_R%7D%20y_i%20%5Cright%20)%5E2%20"></p>
<p>The reduction in loss from this split is</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5CDelta%20L%20=%20L_%7B%5Ctext%7Bafter%20split%7D%7D%20-%20%20L_%7B%5Ctext%7Bbefore%20split%7D%7D%20=%20(L_L%20+%20L_R)%20-%20L%20"> <img src="https://latex.codecogs.com/png.latex?%20%20=%20%5Csum_%7Bi%20%5Cin%20I_L%7D%20y_i%5E2%20-%20%5Cfrac%7B1%7D%7Bn_L%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_L%7D%20y_i%20%5Cright%20)%5E2%20+%20%5Csum_%7Bi%20%5Cin%20I_R%7D%20y_i%5E2%20-%20%5Cfrac%7B1%7D%7Bn_R%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_R%7D%20y_i%20%5Cright%20)%5E2%20-%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I%7D%20y_i%5E2%20-%20%5Cfrac%7B1%7D%7Bn%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I%7D%20y_i%20%5Cright%20)%5E2%20%5Cright%20)%20"></p>
<p>Since <img src="https://latex.codecogs.com/png.latex?I%20=%20I_L%20%5Ccup%20I_R"> the <img src="https://latex.codecogs.com/png.latex?%5Csum%20y%5E2"> terms cancel and we can simplify.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5CDelta%20L%20=%20-%20%5Cfrac%7B1%7D%7Bn_L%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_L%7D%20y_i%20%5Cright%20)%5E2%0A-%20%5Cfrac%7B1%7D%7Bn_R%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I_R%7D%20y_i%20%5Cright%20)%5E2%0A+%20%5Cfrac%7B1%7D%7Bn%7D%20%5Cleft%20(%20%5Csum_%7Bi%20%5Cin%20I%7D%20y_i%20%5Cright%20)%5E2%20%20"></p>
<p>This is a really nice formulation of the split scoring metric from a computational complexity perspective. We can sort the data by the feature values then, starting with the smallest <code>min_samples_leaf</code> instances in the left node and the rest in the right node, we check the score. Then to check the next split, we simply move a single target value from the right node into the left node, updating the score by subtracting it from the right node’s partial sum and adding it to the left node’s partial sum. The third term is constant for all splits, so we only need to compute it once. If any split’s score is lower than the best score so far, then we update the best score so far, the split feature, and the threshold value. When we’re done we can be sure we found the best possible split. The time bottleneck is the sort, which puts us at an average time complexity of <img src="https://latex.codecogs.com/png.latex?O(n%5Clog%20n)">.</p>
<div id="cell-25" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _find_better_split(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, feature_idx):</span>
<span id="cb11-2">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs,feature_idx]</span>
<span id="cb11-3">        y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs]</span>
<span id="cb11-4">        sort_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(x)</span>
<span id="cb11-5">        sort_y, sort_x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y[sort_idx], x[sort_idx]</span>
<span id="cb11-6">        sum_y, n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(), <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y)</span>
<span id="cb11-7">        sum_y_right, n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sum_y, n</span>
<span id="cb11-8">        sum_y_left, n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-9">    </span>
<span id="cb11-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf):</span>
<span id="cb11-11">            y_i, x_i, x_i_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sort_y[i], sort_x[i], sort_x[i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb11-12">            sum_y_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> y_i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> sum_y_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> y_i</span>
<span id="cb11-13">            n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-14">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span>  n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> x_i_next:</span>
<span id="cb11-15">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb11-16">            score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sum_y_left<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sum_y_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sum_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n</span>
<span id="cb11-17">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far:</span>
<span id="cb11-18">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score</span>
<span id="cb11-19">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> feature_idx</span>
<span id="cb11-20">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> x_i_next) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span></code></pre></div></div>
</div>
<p>Again, we assign the split finding method to our class and instantiate a new tree to make sure things are still working.</p>
<div id="cell-27" class="cell" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">DecisionTree._find_better_split <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _find_better_split</span>
<span id="cb12-2">t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(X, y, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)</span>
<span id="cb12-3">X.columns[t.split_feature_idx], t.threshold</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="12">
<pre><code>('s5', -0.0037611760063045703)</code></pre>
</div>
</div>
<p>Nice! Looks like the tree started with a split on the <code>s5</code> feature.</p>
</section>
<section id="inspecting-the-tree" class="level2">
<h2 class="anchored" data-anchor-id="inspecting-the-tree">Inspecting the Tree</h2>
<p>While we’re developing something complex like a decision tree class, we need a good way to inspect the object to help with testing and debugging. Let’s write a quick string representation method to make it easier to check what’s going on with a particular node.</p>
<div id="cell-30" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb14-2">        s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'n: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span></span>
<span id="cb14-3">        s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'; value:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>value<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span></span>
<span id="cb14-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf:</span>
<span id="cb14-5">            split_feature_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.columns[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx]</span>
<span id="cb14-6">            s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'; split: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>split_feature_name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> &lt;= </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>threshold<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span></span>
<span id="cb14-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> s</span></code></pre></div></div>
</div>
<p>We can assign the string representation method to the class and print a few nodes.</p>
<div id="cell-32" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1">DecisionTree.<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span></span>
<span id="cb15-2">t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(X, y, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb15-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(t)</span>
<span id="cb15-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(t.left)</span>
<span id="cb15-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(t.left.left)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>n: 442; value:152.13; split: s5 &lt;= -0.004
n: 218; value:109.99; split: bmi &lt;= 0.006
n: 171; value:96.31</code></pre>
</div>
</div>
</section>
<section id="prediction" class="level2">
<h2 class="anchored" data-anchor-id="prediction">Prediction</h2>
<p>We need a public <code>predict</code> method that takes a feature dataframe and returns an array of predictions. We’ll need to look up the predicted value for one instance at a time and stitch them together in an array. We can do that by iterating over the feature dataframe rows with a list comprehension that calls a <code>_predict_row</code> method to grab the prediction for each row. The row predict method needs to return the current node’s predicted value if it’s a leaf, or if not, it needs to identify the appropriate child node based on its split and ask it for a prediction.</p>
<div id="cell-34" class="cell" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb17-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.array([<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._predict_row(row) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> X.iterrows()])</span>
<span id="cb17-3">    </span>
<span id="cb17-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _predict_row(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, row):</span>
<span id="cb17-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: </span>
<span id="cb17-6">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value</span>
<span id="cb17-7">        child <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb17-8">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right</span>
<span id="cb17-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> child._predict_row(row)</span></code></pre></div></div>
</div>
<p>Let’s assign the predict methods and make predictions on a few rows.</p>
<div id="cell-36" class="cell" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">DecisionTree.predict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> predict</span>
<span id="cb18-2">DecisionTree._predict_row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _predict_row</span>
<span id="cb18-3">t.predict(X.iloc[:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, :])</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="16">
<pre><code>array([225.87962963,  96.30994152, 225.87962963])</code></pre>
</div>
</div>
</section>
<section id="the-complete-decision-tree-implementation" class="level2">
<h2 class="anchored" data-anchor-id="the-complete-decision-tree-implementation">The Complete Decision Tree Implementation</h2>
<p>Here’s the implementation, all in one place.</p>
<div id="cell-39" class="cell" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> DecisionTree():</span>
<span id="cb20-2"></span>
<span id="cb20-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, y, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, idxs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb20-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max_depth must be nonnegative'</span></span>
<span id="cb20-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> min_samples_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'min_samples_leaf must be positive'</span></span>
<span id="cb20-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> min_samples_leaf, max_depth</span>
<span id="cb20-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(y, pd.Series): y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.values</span>
<span id="cb20-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> idxs <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y))</span>
<span id="cb20-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X, y, idxs</span>
<span id="cb20-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(idxs), X.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb20-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.mean(y[idxs]) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># node's prediction value</span></span>
<span id="cb20-12">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'inf'</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># initial loss before split finding</span></span>
<span id="cb20-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb20-14">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._maybe_insert_child_nodes()</span>
<span id="cb20-15">            </span>
<span id="cb20-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _maybe_insert_child_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb20-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.c): </span>
<span id="cb20-18">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._find_better_split(j)</span>
<span id="cb20-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># do not insert children</span></span>
<span id="cb20-20">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> </span>
<span id="cb20-21">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs,<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx]</span>
<span id="cb20-22">        left_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb20-23">        right_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb20-24">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf, </span>
<span id="cb20-25">                                  <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[left_idx])</span>
<span id="cb20-26">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf, </span>
<span id="cb20-27">                                  <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs[right_idx])</span>
<span id="cb20-28">    </span>
<span id="cb20-29">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@property</span></span>
<span id="cb20-30">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_leaf(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'inf'</span>)</span>
<span id="cb20-31">    </span>
<span id="cb20-32">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _find_better_split(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, feature_idx):</span>
<span id="cb20-33">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.values[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs,feature_idx]</span>
<span id="cb20-34">        y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.idxs]</span>
<span id="cb20-35">        sort_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(x)</span>
<span id="cb20-36">        sort_y, sort_x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y[sort_idx], x[sort_idx]</span>
<span id="cb20-37">        sum_y, n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(), <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y)</span>
<span id="cb20-38">        sum_y_right, n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sum_y, n</span>
<span id="cb20-39">        sum_y_left, n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb20-40">    </span>
<span id="cb20-41">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf):</span>
<span id="cb20-42">            y_i, x_i, x_i_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sort_y[i], sort_x[i], sort_x[i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb20-43">            sum_y_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> y_i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> sum_y_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> y_i</span>
<span id="cb20-44">            n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb20-45">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span>  n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_samples_leaf <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> x_i_next:</span>
<span id="cb20-46">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb20-47">            score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sum_y_left<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sum_y_right<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_right <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sum_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n</span>
<span id="cb20-48">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far:</span>
<span id="cb20-49">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.best_score_so_far <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> score</span>
<span id="cb20-50">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> feature_idx</span>
<span id="cb20-51">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x_i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> x_i_next) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb20-52">                </span>
<span id="cb20-53">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb20-54">        s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'n: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span></span>
<span id="cb20-55">        s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'; value:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>value<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span></span>
<span id="cb20-56">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf:</span>
<span id="cb20-57">            split_feature_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X.columns[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx]</span>
<span id="cb20-58">            s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'; split: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>split_feature_name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> &lt;= </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>threshold<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span></span>
<span id="cb20-59">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> s</span>
<span id="cb20-60">    </span>
<span id="cb20-61">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb20-62">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.array([<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._predict_row(row) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> X.iterrows()])</span>
<span id="cb20-63">    </span>
<span id="cb20-64">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _predict_row(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, row):</span>
<span id="cb20-65">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.is_leaf: </span>
<span id="cb20-66">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.value</span>
<span id="cb20-67">        child <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.left <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> row[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.split_feature_idx] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.threshold <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb20-68">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.right</span>
<span id="cb20-69">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> child._predict_row(row)</span></code></pre></div></div>
</div>
</section>
<section id="from-scratch-versus-scikit-learn" class="level2">
<h2 class="anchored" data-anchor-id="from-scratch-versus-scikit-learn">From Scratch versus Scikit-Learn</h2>
<p>As usual, we’ll test our homegrown handiwork by comparing it to the existing implementation in scikit-learn. First let’s train both models on the <a href="https://scikit-learn.org/stable/datasets/real_world.html">California Housing dataset</a> which gives us 20k instances and 8 features to predict median house price by district.</p>
<div id="cell-42" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> fetch_california_housing</span>
<span id="cb21-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.model_selection <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> train_test_split</span>
<span id="cb21-3"></span>
<span id="cb21-4">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fetch_california_housing(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, return_X_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb21-5">X_train, X_test, y_train, y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_test_split(X, y, test_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">43</span>)</span></code></pre></div></div>
</div>
<div id="cell-43" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.tree <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> DecisionTreeRegressor</span>
<span id="cb22-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> mean_squared_error</span>
<span id="cb22-3"></span>
<span id="cb22-4">max_depth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span></span>
<span id="cb22-5">min_samples_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span></span>
<span id="cb22-6"></span>
<span id="cb22-7">tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(X_train, y_train, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>min_samples_leaf)</span>
<span id="cb22-8">pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tree.predict(X_test)</span>
<span id="cb22-9"></span>
<span id="cb22-10">sk_tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTreeRegressor(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>min_samples_leaf)</span>
<span id="cb22-11">sk_tree.fit(X_train, y_train)</span>
<span id="cb22-12">sk_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sk_tree.predict(X_test)</span>
<span id="cb22-13"></span>
<span id="cb22-14"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'from scratch MSE: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>mean_squared_error(y_test, pred)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb22-15"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'scikit-learn MSE: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>mean_squared_error(y_test, sk_pred)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>from scratch MSE: 0.3988
scikit-learn MSE: 0.3988</code></pre>
</div>
</div>
<p>We get similar accuracy on a held-out test dataset.</p>
<p>Let’s benchmark the two implementations on training time.</p>
<div id="cell-45" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb24-2">sk_tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTreeRegressor(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>min_samples_leaf)</span>
<span id="cb24-3">sk_tree.fit(X_train, y_train)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 45.3 ms, sys: 555 µs, total: 45.8 ms
Wall time: 45.3 ms</code></pre>
</div>
<div class="cell-output cell-output-display" data-execution_count="20">
<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: "▸";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: "▾";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: "";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: "";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: "";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id="sk-container-id-1" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>DecisionTreeRegressor(max_depth=8, min_samples_leaf=16)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br>On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class="sk-container" hidden=""><div class="sk-item"><div class="sk-estimator sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-1" type="checkbox" checked=""><label for="sk-estimator-id-1" class="sk-toggleable__label sk-toggleable__label-arrow">DecisionTreeRegressor</label><div class="sk-toggleable__content"><pre>DecisionTreeRegressor(max_depth=8, min_samples_leaf=16)</pre></div></div></div></div></div>
</div>
</div>
<div id="cell-46" class="cell" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span>time</span>
<span id="cb26-2">tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTree(X_train, y_train, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth, min_samples_leaf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>min_samples_leaf)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>CPU times: user 624 ms, sys: 1.65 ms, total: 625 ms
Wall time: 625 ms</code></pre>
</div>
</div>
<p>Wow, the scikit-learn implementation absolutely smoked us, training an order of magnitude faster. This is to be expected, since they implement split finding in cython, which generates compiled C code that can run much faster than our native python code. Maybe we can take a look at how to optimize python code with cython here on the blog one of these days.</p>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Holy cow, we just implemented a decision tree using nothing but numpy. I hope you enjoyed the scratch build as much as I did, and I hope you got a little bit better at coding (I certainly did). That was actually way harder than I expected, but looking back at the finished product, it doesn’t seem so bad right? I almost thought we were going to get away with not implementing our own decision tree, but it turns out that this will be super helpful for us when it comes time to implement XGBoost from scratch.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p>This implementation is inspired and partially adapted from Jeremy Howard’s live coding of a <a href="https://course18.fast.ai/lessonsml1/lesson7.html">Random Forest</a> as part of the fastai ML course.</p>


</section>

 ]]></description>
  <category>python</category>
  <category>gradient boosting</category>
  <category>from scratch</category>
  <guid>https://randomrealizations.com/posts/decision-tree-from-scratch/</guid>
  <pubDate>Mon, 13 Dec 2021 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/decision-tree-from-scratch/thumbnail.png" medium="image" type="image/png" height="86" width="144"/>
</item>
<item>
  <title>Consider the Decision Tree</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/consider-the-decision-tree/</link>
  <description><![CDATA[ 





<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/main.jpg" title="." class="img-fluid figure-img"></p>
<figcaption>A California cypress tree abides in silence on Alameda Beach.</figcaption>
</figure>
</div>
<p>Ah, the decision tree. It’s an underrated and often overlooked hero of modern statistical learning. Trees aren’t particularly powerful learning algorithms on their own, but when utilized as building blocks in larger ensemble models like random forest and gradient boosted trees, they can achieve state of the art performance in many practical applications. Since we’ve been focusing on gradient boosting ensembles lately, let’s take a moment to consider the humble decision tree itself. This post gives a high-level intuition for how trees work, an opinionated list of their key strengths and weaknesses, and some perspective on why ensembling makes them truly shine.</p>
<p>Onward!</p>
<section id="classification-and-regression-trees" class="level2">
<h2 class="anchored" data-anchor-id="classification-and-regression-trees">Classification and Regression Trees</h2>
<p>A Decision tree is a type of statistical model that takes features or covariates as input and yields a prediction as output. The idea of the decision tree as a statistical learning tool traces back to a monograph published in 1984 by Breiman, Freidman, Olshen, and Stone called “Classification and Regression Trees” (a.k.a. CART). As the name suggests, trees come in two main varieties: classification trees which predict discrete class labels (e.g.&nbsp;<a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">DecisionTreeClassifier</a>) and regression trees which predict numeric values (e.g.&nbsp;<a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html">DecisionTreeRegressor</a>).</p>
<p>As I mentioned earlier, tree models are not very powerful learners on their own. You might find that an individual tree model is useful for creating a simple and highly interpretable model in specific situations, but in general, trees tend to shine most as building blocks in more complex algorithms. These composite models are called ensembles, and the most important tree ensembles are random forest and gradient boosted trees. While random forest uses either regression or classification trees depending on the type of target, gradient boosting can use regression trees to solve both classification and regression tasks.</p>
</section>
<section id="regression-tree-in-action" class="level2">
<h2 class="anchored" data-anchor-id="regression-tree-in-action">Regression Tree in Action</h2>
<p>Let’s have a closer look at regression trees by training one on the diabetes dataset from scikit learn. According to the <a href="https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset">documentation</a>:</p>
<blockquote class="blockquote">
<p>Ten baseline variables, age, sex, body mass index, average blood pressure, and six blood serum measurements were obtained for each of n = 442 diabetes patients, as well as the response of interest, a quantitative measure of disease progression one year after baseline.</p>
</blockquote>
<p>First we load the data. To make our lives easier, we’ll just use two features: average blood pressure (bp) and the first blood serum measurement (s1) to predict the target. I’ll rescale the features to make the values easier for me to read, but it won’t affect our tree–more on that later.</p>
<div id="cell-6" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np </span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> seaborn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sns</span>
<span id="cb1-5">color_palette <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"viridis"</span></span></code></pre></div></div>
</div>
<div id="cell-7" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.datasets <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> load_diabetes</span>
<span id="cb2-2"></span>
<span id="cb2-3">X, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_diabetes(as_frame<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, return_X_y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb2-4"></span>
<span id="cb2-5">X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> X[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bp'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'s1'</span>]]</span></code></pre></div></div>
</div>
<div id="cell-8" class="cell" data-scrolled="true" data-execution_count="4">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-5-output-1.png" class="img-fluid figure-img" alt="Scatterplot of two features with color of the points indicating the target value for each data point"></p>
</figure>
</div>
</div>
</div>
<p>Let’s grow a tree to predict the target given values of blood pressure and blood serum.</p>
<div id="cell-10" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.tree <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> DecisionTreeRegressor</span>
<span id="cb3-2"></span>
<span id="cb3-3">tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTreeRegressor(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-4">tree.fit(X,y)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</div>
<div id="cell-11" class="cell" data-scrolled="true" data-execution_count="6">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-7-output-1.png" class="img-fluid figure-img" alt="Tree diagram showing split rules and predicted values for the fitted tree"></p>
</figure>
</div>
</div>
</div>
<p>To make predictions using our fitted tree, we start at the root node (which is at the top), and we work our way down moving left if our feature is less than the split threshold and to the right if it’s greater than the split threshold. For example let’s predict the target for a new case with bp= 1 and s1 = 5. Since our blood pressure of 1 is less than 2.359, we move to the left child node. Here, since our serum of 5 is greater than the threshold at 0.875, we move to the right child node. This node has no further children, and thus we return its predicted value of 155.343.</p>
<div id="cell-13" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">tree.predict(pd.DataFrame({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bp'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'s1'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>}, index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]))</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="7">
<pre><code>array([155.34313725])</code></pre>
</div>
</div>
<p>Let’s overlay these splits on our feature scatterplot to see how the tree has partitioned the feature space.</p>
<div id="cell-15" class="cell" data-execution_count="8">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-9-output-1.png" class="img-fluid figure-img" alt="Scatterplot of two features with vertical and horizontal dashed lines corresponding to the splits"></p>
</figure>
</div>
</div>
</div>
<p>The tree has managed to carve out regions of feature space where the target values tend to be similar within each region, e.g.&nbsp;we have low target values in the bottom left partition and high target values in the far right region.</p>
<p>Let’s take a look at the regression surface predicted by our tree. Since the tree predicts the exact same value for all instances in a given partition, the surface has only four distinct values.</p>
<div id="cell-17" class="cell" data-execution_count="9">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-10-output-1.png" class="img-fluid figure-img" alt="Plot of the space spanned by two features with color indicating the model predicted value"></p>
</figure>
</div>
</div>
</div>
<p>Fabulous, now that we’ve seen a tree in action, let’s talk about trees’ key strengths and weaknesses.</p>
</section>
<section id="why-trees-are-awesome" class="level2">
<h2 class="anchored" data-anchor-id="why-trees-are-awesome">Why trees are awesome</h2>
<p>Trees are awesome because they are easy to use, and trees are easy to use because they are robust, require minimal data preprocessing, and can learn complex relationships without user intervention.</p>
<section id="feature-scaling" class="level3">
<h3 class="anchored" data-anchor-id="feature-scaling">Feature Scaling</h3>
<p>Trees owe their minimal data preprocessing requirements and their robustness to the fact that split finding is controlled by the sort order of the input feature values, rather than the values themselves. This means that trees are invariant to the scaling of input features, which in turn means that we don’t need to fuss around with carefully rescaling all the numeric features before fitting a tree. It also means that trees tend to work well even if features are highly skewed or contain outliers.</p>
</section>
<section id="categoricals" class="level3">
<h3 class="anchored" data-anchor-id="categoricals">Categoricals</h3>
<p>Since trees just split data based on numeric feature values, we can easily handle most categorical features by using integer encoding. For example we might encode a size feature with small = 1, medium = 2, and large = 3. This works particularly well with ordered categories, because partitioning is consistent with the category semantics. It can also work well even if the categories have no order, because with enough splits a tree can carve each category into its own partition.</p>
</section>
<section id="missing-values" class="level3">
<h3 class="anchored" data-anchor-id="missing-values">Missing Values</h3>
<p>It’s worth calling out that different implementations of the decision tree handle missing feature values in different ways. Notably, scikit-learn handles them by throwing an error and telling you not to pull such shenanigans.</p>
<pre><code>ValueError: Input contains NaN, infinity or a value too large for dtype('float32').</code></pre>
<p>On the other hand, XGBoost supports an elegant way to make use of missing values, which we will discuss more in a later post.</p>
</section>
<section id="interactions" class="level3">
<h3 class="anchored" data-anchor-id="interactions">Interactions</h3>
<p>Feature interactions can also be learned automatically. An interaction means that the effect of one feature on the target differs depending on the value of another feature. For example, the effect of some drug may depend on whether or not the patient exercises. After a tree splits on exercise, it can naturally learn the correct drug effects for both exercisers and non-exercisers. This intuition extends to higher-order interactions as well, as long as the tree has enough splits to parse the relationships.</p>
</section>
<section id="feature-selection" class="level3">
<h3 class="anchored" data-anchor-id="feature-selection">Feature Selection</h3>
<p>Because trees choose the best feature and threshold value at each split, they essentially perform automatic feature selection. This is great because even if we throw a lot of irrelevant features at a decision tree, it will simply tend not to use them for splits. Similarly, if two or more features are highly correlated or even redundant, the tree will simply choose one or the other when making each split; having both in the model will not cause catastrophic instability as it could in a linear model.</p>
</section>
<section id="feature-target-relationship" class="level3">
<h3 class="anchored" data-anchor-id="feature-target-relationship">Feature-Target Relationship</h3>
<p>Finally, it is possible for trees to discover complex nonlinear feature-target relationships without the need for user-specification of the relationships. This is because trees use local piecewise constant approximations without making any parametric assumptions. With enough splits, the tree can approximate arbitrary feature-target relationships.</p>
<div id="cell-22" class="cell" data-execution_count="11">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-12-output-1.png" class="img-fluid figure-img" alt="Figure showing sinusoidal scatter data and a piecewise constant approximation from a decision tree"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="why-trees-are-not-so-awesome" class="level2">
<h2 class="anchored" data-anchor-id="why-trees-are-not-so-awesome">Why trees are not so awesome</h2>
<p>The main weakness of the decision tree is that, on its own, it tends to have poor predictive performance compared to other algorithms. The main reasons for this are the tendency to overfit and prediction quantization issues.</p>
<section id="overfitting" class="level3">
<h3 class="anchored" data-anchor-id="overfitting">Overfitting</h3>
<p>If we grow a decision tree until each leaf has exactly one instance in it, we will have simply memorized the training data, and our model will not generalize well. Basically the only defense against overfitting is to reduce the number of leaf nodes in the tree, either by using hyperparameters to stop splitting earlier or by removing certain leaf nodes after growing a deep tree. The problem here is that some of the benefits of trees, like ability to approximate arbitrary target patterns and ability to learn interaction effects, depend on having enough splits for the task. We can sometimes find ourselves in a situation where we cannot learn these complex relationships without overfitting the tree.</p>
</section>
<section id="quantization" class="level3">
<h3 class="anchored" data-anchor-id="quantization">Quantization</h3>
<p>Because regression trees use piecewise constant functions to approximate the target, prediction accuracy can deteriorate near split boundaries. For example, if the target is increasing with the feature, a tree might tend to overpredict the target on the left side of split boundaries and overpredict on the right side of split boundaries.</p>
<div id="cell-24" class="cell" data-scrolled="true" data-execution_count="12">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-13-output-1.png" class="img-fluid figure-img" alt="Figure showing scatter data and a decision tree fit where data points near splits are either over or under predicted"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="extrapolation" class="level3">
<h3 class="anchored" data-anchor-id="extrapolation">Extrapolation</h3>
<p>Because they are trained by partitioning the feature space in a training dataset, trees cannot intelligently extrapolate beyond the data on which they are trained. For example if we query a tree for predictions beyond the greatest feature value encountered in training, it will just return the prediction corresponding to the largest in-sample feature values.</p>
<div id="cell-26" class="cell" data-scrolled="true" data-execution_count="13">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-14-output-1.png" class="img-fluid figure-img" alt="Figure showing scatter data and a decision tree fit with a constant predicted value outside the data range"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="the-dark-side-of-convenience" class="level3">
<h3 class="anchored" data-anchor-id="the-dark-side-of-convenience">The Dark Side of Convenience</h3>
<p>Finally, there is always a price to pay for convenience. While trees can work well even with a messy dataset containing outliers, redundant features, and thoughtlessly encoded categoricals, we will rarely achieve the best performance under these conditions. Taking the time to deal with outliers, removing redundant information, purposefully choosing appropriate categorical encodings, and building an understanding of the data will often lead to much better results.</p>
</section>
</section>
<section id="how-ensembling-makes-trees-shine" class="level2">
<h2 class="anchored" data-anchor-id="how-ensembling-makes-trees-shine">How ensembling makes trees shine</h2>
<p>We can go a long way toward addressing the issues of overfitting and prediction quantization by using trees as building blocks in larger algorithms called tree ensembles, the most popular examples being random forest and gradient boosted trees. A tree ensemble is a collection of different individual tree models whose predictions are averaged to generate an overall prediction.</p>
<p>Ensembling helps address overfitting because even if each individual tree is overfitted, the average of their individual noisy predictions will tend to be more stable. Think of it in terms of the <a href="https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff">bias variance tradeoff</a>, where bias refers to a model’s failure to capture certain patterns and variance refers to how different a model prediction would be if the model were trained on a different sample of training data. Since the ensemble is averaging over the predictions of all the individual models, training it on a different sample of training data would change the individual models predictions, but their overall average prediction will tend to remain stable. Thus, ensembling helps reduce the effects of overfitting by reducing model variance without increasing bias.</p>
<p>Ensembling also helps address prediction quantization issues. While each individual tree’s predictions might express large jumps in the regression surface, averaging many different trees’ predictions together effectively generates a surface with more partitions and smaller jumps between them. This provides a smoother approximation of the feature-target relationship.</p>
<div id="cell-29" class="cell" data-scrolled="true" data-execution_count="14">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/consider-the-decision-tree/consider-the-decision-tree_files/figure-html/cell-15-output-1.png" class="img-fluid figure-img" alt="Figure showing scatter data and a smooth model prediction from a tree ensemble model"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Well, there you go, that’s my take on the high-level overview of the decision tree and its main strengths and weaknesses. As we’ve seen, ensembling allows us to keep the conveniences of the decision tree while mitigating its core weakness of relatively weak predictive power. This is why tree ensembles are so popular in practical applications. We glossed over pretty much all details of how trees actually do their magic, but fear not, next time we’re going to get rowdy and build one of these things from scratch.</p>


</section>

 ]]></description>
  <category>gradient boosting</category>
  <guid>https://randomrealizations.com/posts/consider-the-decision-tree/</guid>
  <pubDate>Sun, 12 Dec 2021 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/consider-the-decision-tree/thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>How to Implement a Gradient Boosting Machine that Works with Any Loss Function</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/</link>
  <description><![CDATA[ 





<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/main.jpg" class="img-fluid figure-img"></p>
<figcaption>Cold water cascades over the rocks in Erwin, Tennessee.</figcaption>
</figure>
</div>
<p>Friends, this is going to be an epic post! Today, we bring together all the ideas we’ve built up over the past few posts to nail down our understanding of the key ideas in Jerome Friedman’s seminal 2001 paper: “<a href="https://statweb.stanford.edu/~jhf/ftp/trebst.pdf">Greedy Function Approximation: A Gradient Boosting Machine</a>.” In particular, we’ll summarize the highlights from the paper, and we’ll build an in-house python implementation of his generic gradient boosting algorithm which can train with any differentiable loss function. What’s more, we’ll go ahead and take our generic gradient boosting machine for a spin by training it with several of the most popular loss functions used in practice.</p>
<p>Are you freaking stoked or what?</p>
<p>Sweet. Let’s do this.</p>
<section id="friedman-2001-tldr" class="level2">
<h2 class="anchored" data-anchor-id="friedman-2001-tldr">Friedman 2001: TL;DR</h2>
<p>I’ve mentioned this paper a couple of times before, but as far as I can tell, this is the origin of gradient boosting; it is therefore, a seminal work worth reading. You know what, I think you might like to pick up <a href="https://statweb.stanford.edu/~jhf/ftp/trebst.pdf">the paper</a> and read it yourself. Like many papers, there is a lot of scary looking math in the first few pages, but if you’ve been following along on this blog, you’ll find that it’s actually totally approachable. This is the kind of thing that cures imposter syndrome, so give it a shot. That said, here’s the TL;DR as I see it.</p>
<p>The first part of the paper introduces the idea of fitting models by doing gradient descent in function space, an ingenious idea we spent <a href="../../posts/how-gradient-boosting-does-gradient-descent/">an entire post</a> demystifying earlier. Friedman goes on to introduce the generic gradient boost algorithm, which works with any differentiable loss function, as well as specific variants for minimizing absolute error, Huber loss, and binary deviance. In terms of hyperparameters, he points out that the learning rate can be used to reduce overfitting, while increased tree depth can help capture more complex interactions among features. He even discusses feature importance and partial dependence methods for interpreting fitted gradient boosting models.</p>
<p>Friedman concludes by musing about the advantages of gradient boosting with trees. He notes some key advantages afforded by the use of decision trees including no need to rescale input data, robustness against irrelevant input features, and elegant handling of missing feature values. He points out that gradient boosting manages to capitalize on the benefits of decision trees while minimizing their key weakness (crappy accuracy). I think this offers a great insight into why gradient boosting models have become so widespread and successful in practical ML applications.</p>
</section>
<section id="friedmans-generic-gradient-boosting-algorithm" class="level2">
<h2 class="anchored" data-anchor-id="friedmans-generic-gradient-boosting-algorithm">Friedman’s Generic Gradient Boosting Algorithm</h2>
<p>Let’s take a closer look at Friedman’s original gradient boost algorithm, Alg. 1 in Section 3 of <a href="https://statweb.stanford.edu/~jhf/ftp/trebst.pdf">the paper</a> (translated into the notation we’ve been using so far).</p>
<p>Like last time, we have training data <img src="https://latex.codecogs.com/png.latex?(%5Cmathbf%7By%7D,%20%5Cmathbf%7BX%7D)"> where <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D"> is a length-<img src="https://latex.codecogs.com/png.latex?n"> vector of target values, and <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D"> is an <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20p"> matrix with <img src="https://latex.codecogs.com/png.latex?n"> observations of <img src="https://latex.codecogs.com/png.latex?p"> features. We also have a differentiable loss function <img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D)%20=%20%5Csum_%7Bi=1%7D%5En%20l(y_i,%20%5Chat%7By%7D_i)">, a “learning rate” hyperparameter <img src="https://latex.codecogs.com/png.latex?%5Ceta">, and a fixed number of model iterations <img src="https://latex.codecogs.com/png.latex?M">.</p>
<p><strong>Algorithm:</strong> <em>gradient_boost</em><img src="https://latex.codecogs.com/png.latex?(%5Cmathbf%7BX%7D,%5Cmathbf%7By%7D,L,%5Ceta,%20M)"> returns: model <img src="https://latex.codecogs.com/png.latex?F_M"></p>
<ol type="1">
<li><p>Let base model <img src="https://latex.codecogs.com/png.latex?F_0(%5Cmathbf%7Bx%7D)%20=%20c">, where <img src="https://latex.codecogs.com/png.latex?c%20=%20%5Ctext%7Bargmin%7D_%7Bc%7D%20%5Csum_%7Bi=1%7D%5En%20l(y_i,%20c)"></p></li>
<li><p><code>for</code> <img src="https://latex.codecogs.com/png.latex?m"> = <img src="https://latex.codecogs.com/png.latex?0"> to <img src="https://latex.codecogs.com/png.latex?M-1">:</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; Let “pseudo-residual” vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D_m%20=%20-%5Cnabla_%7B%5Cmathbf%7B%5Chat%7By%7D%7D_m%7D%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D_m)"></p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; Train decision tree regressor <img src="https://latex.codecogs.com/png.latex?h_m(%5Cmathbf%7BX%7D)"> to predict <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D_m"> (minimizing squared error)</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; <code>foreach</code> terminal leaf node <img src="https://latex.codecogs.com/png.latex?t%20%5Cin%20h_m">:</p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; Let <img src="https://latex.codecogs.com/png.latex?v%20=%20%5Ctext%7Bargmin%7D_v%20%5Csum_%7Bi%20%5Cin%20t%7D%20l(y_i,%20F_m(%5Cmathbf%7Bx%7D_i)%20+%20v)"></p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; Set terminal leaf node <img src="https://latex.codecogs.com/png.latex?t"> to predict value <img src="https://latex.codecogs.com/png.latex?v"></p></li>
<li><p>&nbsp;&nbsp;&nbsp;&nbsp; <img src="https://latex.codecogs.com/png.latex?F_%7Bm+1%7D(%5Cmathbf%7BX%7D)%20=%20F_%7Bm%7D(%5Cmathbf%7BX%7D)%20+%20%5Ceta%20h_m(%5Cmathbf%7BX%7D)"></p></li>
<li><p>Return composite model <img src="https://latex.codecogs.com/png.latex?F_M"></p></li>
</ol>
<p>By now, most of this is already familiar to us. We begin by setting the base model <img src="https://latex.codecogs.com/png.latex?F_0"> equal to the constant prediction value that minimizes the loss over all examples in the training dataset (line 1). Then we begin the boosting iterations (line 2), each time computing the negative gradients of the loss with respect to the current model predictions (known as the pseudo residuals) (line 3). We then fit our next decision tree regressor to predict the pseudo residuals (line 4).</p>
<p>Then we encounter something new on lines 5-7. When we fit a vanilla decision tree regressor to predict pseudo residuals, we’re using mean squared error as the loss function to train the tree. As you might imagine, this works well when the global loss function is also squared error. But if we want to use a global loss other than squared error, there is an additional trick we can use to further increase the composite model’s accuracy. The idea is to continue using squared error to train each decision tree, keeping its structure and split conditions but altering the predicted value in each leaf to help minimize the global loss function. Instead of using the mean target value as the prediction for each node (as we would do when minimizing squared error), we use a numerical optimization method like line search to choose the constant value for that leaf that leads to the best overall loss. This is the same thing we did in line 1 of the algorithm to set the base prediction, but here we choose the optimal prediction for each terminal node of the newly trained decision tree.</p>
</section>
<section id="implementation" class="level2">
<h2 class="anchored" data-anchor-id="implementation">Implementation</h2>
<p>I did some (half-assed) searching on the interweb for an implementation of GBM that allows the user to provide a custom loss function, and you know what? I couldn’t find anything. If you find another implementation, post in the comments so we can learn from it too.</p>
<p>Since we need to modify the values predicted by our decision trees’ terminal nodes, we’ll want to brush up on the scikit-learn <a href="https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html">decision tree structure</a> before we get going. You can see explanations of all the necessary decision tree hacks in this <a href="https://github.com/mcb00/blog/blob/master/supplemental/friedman-gbm-implementation.ipynb">notebook</a>.</p>
<div id="cell-6" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.tree <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> DecisionTreeRegressor </span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.optimize <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> minimize</span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> GradientBoostingMachine():</span>
<span id="cb1-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Gradient Boosting Machine supporting any user-supplied loss function.</span></span>
<span id="cb1-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    </span></span>
<span id="cb1-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb1-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    n_trees : int</span></span>
<span id="cb1-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        number of boosting rounds</span></span>
<span id="cb1-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        </span></span>
<span id="cb1-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    learning_rate : float</span></span>
<span id="cb1-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        learning rate hyperparameter</span></span>
<span id="cb1-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        </span></span>
<span id="cb1-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    max_depth : int</span></span>
<span id="cb1-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        maximum tree depth</span></span>
<span id="cb1-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb1-19">    </span>
<span id="cb1-20">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, n_trees, learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb1-21">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_trees<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_trees<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> </span>
<span id="cb1-22">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>learning_rate</span>
<span id="cb1-23">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-24">    </span>
<span id="cb1-25">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fit(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, y, objective):</span>
<span id="cb1-26">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Fit the GBM using the specified loss function.</span></span>
<span id="cb1-27"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        </span></span>
<span id="cb1-28"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Parameters</span></span>
<span id="cb1-29"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        ----------</span></span>
<span id="cb1-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        X : ndarray of size (number observations, number features)</span></span>
<span id="cb1-31"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            design matrix</span></span>
<span id="cb1-32"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            </span></span>
<span id="cb1-33"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        y : ndarray of size (number observations,)</span></span>
<span id="cb1-34"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            target values</span></span>
<span id="cb1-35"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            </span></span>
<span id="cb1-36"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        objective : loss function class instance</span></span>
<span id="cb1-37"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            Class specifying the loss function for training.</span></span>
<span id="cb1-38"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            Should implement two methods:</span></span>
<span id="cb1-39"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">                loss(labels: ndarray, predictions: ndarray) -&gt; float</span></span>
<span id="cb1-40"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">                negative_gradient(labels: ndarray, predictions: ndarray) -&gt; ndarray</span></span>
<span id="cb1-41"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        '''</span></span>
<span id="cb1-42">        </span>
<span id="cb1-43">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.trees <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb1-44">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._get_optimal_base_value(y, objective.loss)</span>
<span id="cb1-45">        current_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.ones(shape<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y.shape)</span>
<span id="cb1-46">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.n_trees):</span>
<span id="cb1-47">            pseudo_residuals <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> objective.negative_gradient(y, current_predictions)</span>
<span id="cb1-48">            tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DecisionTreeRegressor(max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_depth)</span>
<span id="cb1-49">            tree.fit(X, pseudo_residuals)</span>
<span id="cb1-50">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._update_terminal_nodes(tree, X, y, current_predictions, objective.loss)</span>
<span id="cb1-51">            current_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tree.predict(X)</span>
<span id="cb1-52">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.trees.append(tree)</span>
<span id="cb1-53">     </span>
<span id="cb1-54">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _get_optimal_base_value(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, loss):</span>
<span id="cb1-55">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Find the optimal initial prediction for the base model.'''</span></span>
<span id="cb1-56">        fun <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> c: loss(y, c)</span>
<span id="cb1-57">        c0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.mean()</span>
<span id="cb1-58">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> minimize(fun<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>fun, x0<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c0).x[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb1-59">        </span>
<span id="cb1-60">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _update_terminal_nodes(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, tree, X, y, current_predictions, loss):</span>
<span id="cb1-61">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Update the tree's predictions according to the loss function.'''</span></span>
<span id="cb1-62">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># terminal node id's</span></span>
<span id="cb1-63">        leaf_nodes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.nonzero(tree.tree_.children_left <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb1-64">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># compute leaf for each sample in ``X``.</span></span>
<span id="cb1-65">        leaf_node_for_each_sample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tree.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">apply</span>(X)</span>
<span id="cb1-66">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> leaf <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> leaf_nodes:</span>
<span id="cb1-67">            samples_in_this_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.where(leaf_node_for_each_sample <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> leaf)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb1-68">            y_in_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.take(samples_in_this_leaf, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-69">            preds_in_leaf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> current_predictions.take(samples_in_this_leaf, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-70">            val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._get_optimal_leaf_value(y_in_leaf, </span>
<span id="cb1-71">                                               preds_in_leaf,</span>
<span id="cb1-72">                                               loss)</span>
<span id="cb1-73">            tree.tree_.value[leaf, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> val</span>
<span id="cb1-74">            </span>
<span id="cb1-75">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _get_optimal_leaf_value(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, current_predictions, loss):</span>
<span id="cb1-76">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Find the optimal prediction value for a given leaf.'''</span></span>
<span id="cb1-77">        fun <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> c: loss(y, current_predictions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> c)</span>
<span id="cb1-78">        c0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y.mean()</span>
<span id="cb1-79">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> minimize(fun<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>fun, x0<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c0).x[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb1-80">          </span>
<span id="cb1-81">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb1-82">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Generate predictions for the given input data.'''</span></span>
<span id="cb1-83">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_prediction </span>
<span id="cb1-84">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.learning_rate </span>
<span id="cb1-85">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>([tree.predict(X) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> tree <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.trees], axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
</div>
<p>In terms of design, we implement a class for the GBM with scikit-like <code>fit</code> and <code>predict</code> methods. Notice in the below implementation that the <code>fit</code> method is only 10 lines long, and corresponds very closely to Friedman’s gradient boost algorithm from above. Most of the complexity comes from the helper methods for updating the leaf values according to the specified loss function.</p>
<p>When the user wants to call the <code>fit</code> method, they’ll need to supply the loss function they want to use for boosting. We’ll make the user implement their loss (a.k.a. objective) function as a class with two methods: (1) a <code>loss</code> method taking the labels and the predictions and returning the loss score and (2) a <code>negative_gradient</code> method taking the labels and the predictions and returning an array of negative gradients.</p>
</section>
<section id="testing-our-model" class="level2">
<h2 class="anchored" data-anchor-id="testing-our-model">Testing our Model</h2>
<p>Let’s test drive our custom-loss-ready GBM with a few different loss functions! We’ll compare it to the scikit-learn GBM to sanity check our implementation.</p>
<div id="cell-9" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.ensemble <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> GradientBoostingRegressor, GradientBoostingClassifier</span>
<span id="cb2-2"></span>
<span id="cb2-3">rng <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.default_rng()</span>
<span id="cb2-4"></span>
<span id="cb2-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># test data</span></span>
<span id="cb2-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> make_test_data(n, noise_scale):</span>
<span id="cb2-7">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>).reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-8">    y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (np.where(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, noise_scale, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x.shape)).ravel()</span>
<span id="cb2-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x, y</span>
<span id="cb2-10">    </span>
<span id="cb2-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># print model loss scores</span></span>
<span id="cb2-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> print_model_loss_scores(obj, y, preds, sk_preds):</span>
<span id="cb2-13">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'From Scratch Loss = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>obj<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>loss(y, pred)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.4}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span>
<span id="cb2-14">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Scikit-Learn Loss = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>obj<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>loss(y, sk_pred)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:0.4}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>)</span></code></pre></div></div>
</div>
<section id="mean-squared-error" class="level3">
<h3 class="anchored" data-anchor-id="mean-squared-error">Mean Squared Error</h3>
<p>Mean Squared Error (a.k.a. Least Squares) loss produces estimates of the mean target value conditioned on the feature values. Here’s the implementation.</p>
<div id="cell-11" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">x, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_test_data(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>)</span></code></pre></div></div>
</div>
<div id="cell-12" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># from scratch GBM</span></span>
<span id="cb4-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> SquaredErrorLoss():</span>
<span id="cb4-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''User-Defined Squared Error Loss'''</span></span>
<span id="cb4-4">    </span>
<span id="cb4-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> loss(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb4-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.mean((y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> preds)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb4-7">    </span>
<span id="cb4-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> negative_gradient(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb4-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> preds</span>
<span id="cb4-10">    </span>
<span id="cb4-11"></span>
<span id="cb4-12">gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingMachine(n_trees<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb4-13">                              learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb4-14">                              max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb4-15">gbm.fit(x, y, SquaredErrorLoss())</span>
<span id="cb4-16">pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gbm.predict(x)</span></code></pre></div></div>
</div>
<div id="cell-13" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># scikit-learn GBM</span></span>
<span id="cb5-2">sk_gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingRegressor(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb5-3">                                   learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb5-4">                                   max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb5-5">                                   loss<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'squared_error'</span>)</span>
<span id="cb5-6">sk_gbm.fit(x, y)</span>
<span id="cb5-7">sk_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sk_gbm.predict(x)</span></code></pre></div></div>
</div>
<div id="cell-14" class="cell" data-scrolled="true" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">print_model_loss_scores(SquaredErrorLoss(), y, pred, sk_pred)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>From Scratch Loss = 0.168
Scikit-Learn Loss = 0.168</code></pre>
</div>
</div>
<div id="cell-15" class="cell" data-scrolled="false" data-execution_count="7">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/gbm-any-loss_files/figure-html/cell-8-output-1.png" class="img-fluid figure-img" alt="Scatterplot showing data and model prediction of y given x"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="mean-absolute-error" class="level3">
<h3 class="anchored" data-anchor-id="mean-absolute-error">Mean Absolute Error</h3>
<p>Mean Absolute Error (a.k.a.Least Absolute Deviations) loss produces estimates of the median target value conditioned on the feature values. Here’s the implementation.</p>
<div id="cell-18" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">x, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_test_data(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>)</span></code></pre></div></div>
</div>
<div id="cell-19" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"></span>
<span id="cb9-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># from scratch GBM</span></span>
<span id="cb9-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> AbsoluteErrorLoss():</span>
<span id="cb9-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''User-Defined Absolute Error Loss'''</span></span>
<span id="cb9-5">    </span>
<span id="cb9-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> loss(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb9-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.mean(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> preds))</span>
<span id="cb9-8">    </span>
<span id="cb9-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> negative_gradient(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb9-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.sign(y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> preds)</span>
<span id="cb9-11"></span>
<span id="cb9-12"></span>
<span id="cb9-13">gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingMachine(n_trees<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb9-14">                              learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb9-15">                              max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb9-16">gbm.fit(x, y, AbsoluteErrorLoss())</span>
<span id="cb9-17">pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gbm.predict(x)</span></code></pre></div></div>
</div>
<div id="cell-20" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># scikit-learn GBM</span></span>
<span id="cb10-2">sk_gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingRegressor(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb10-3">                                   learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb10-4">                                   max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb10-5">                                   loss<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'absolute_error'</span>)</span>
<span id="cb10-6">sk_gbm.fit(x, y)</span>
<span id="cb10-7">sk_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sk_gbm.predict(x)</span></code></pre></div></div>
</div>
<div id="cell-21" class="cell" data-scrolled="true" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">print_model_loss_scores(AbsoluteErrorLoss(), y, pred, sk_pred)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>From Scratch Loss = 0.3225
Scikit-Learn Loss = 0.3208</code></pre>
</div>
</div>
<div id="cell-22" class="cell" data-scrolled="false" data-execution_count="12">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/gbm-any-loss_files/figure-html/cell-14-output-1.png" class="img-fluid figure-img" alt="Figure showing scatterplot of data and model prediction of median of y given x"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="quantile-loss" class="level3">
<h3 class="anchored" data-anchor-id="quantile-loss">Quantile Loss</h3>
<p>Quantile loss yields estimates of a given quantile of the target variable conditioned on the features. Here’s my implementation.</p>
<div id="cell-25" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1">x, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_test_data(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</div>
<div id="cell-26" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"></span>
<span id="cb14-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># from scratch GBM</span></span>
<span id="cb14-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> QuantileLoss():</span>
<span id="cb14-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Quantile Loss</span></span>
<span id="cb14-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    </span></span>
<span id="cb14-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb14-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb14-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    alpha : float</span></span>
<span id="cb14-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        quantile to be estimated, 0 &lt; alpha &lt; 1</span></span>
<span id="cb14-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb14-11">    </span>
<span id="cb14-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, alpha):</span>
<span id="cb14-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:</span>
<span id="cb14-14">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'alpha must be between 0 and 1'</span>)</span>
<span id="cb14-15">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> alpha</span>
<span id="cb14-16">        </span>
<span id="cb14-17">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> loss(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb14-18">        e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> preds</span>
<span id="cb14-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.mean(np.where(e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> e, (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> e))</span>
<span id="cb14-20">    </span>
<span id="cb14-21">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> negative_gradient(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb14-22">        e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> preds </span>
<span id="cb14-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.where(e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.alpha, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb14-24"></span>
<span id="cb14-25">gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingMachine(n_trees<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb14-26">                              learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb14-27">                             max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb14-28">gbm.fit(x, y, QuantileLoss(alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>))</span>
<span id="cb14-29">pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gbm.predict(x)    </span></code></pre></div></div>
</div>
<div id="cell-27" class="cell" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># scikit-learn GBM</span></span>
<span id="cb15-2">sk_gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingRegressor(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb15-3">                                 learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb15-4">                                 max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb15-5">                                 loss<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quantile'</span>, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>)</span>
<span id="cb15-6">sk_gbm.fit(x, y)</span>
<span id="cb15-7">sk_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sk_gbm.predict(x)</span></code></pre></div></div>
</div>
<div id="cell-28" class="cell" data-scrolled="true" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1">print_model_loss_scores(QuantileLoss(alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>), y, pred, sk_pred)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>From Scratch Loss = 0.1853
Scikit-Learn Loss = 0.1856</code></pre>
</div>
</div>
<div id="cell-29" class="cell" data-scrolled="true" data-execution_count="17">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/gbm-any-loss_files/figure-html/cell-20-output-1.png" class="img-fluid figure-img" alt="Figure showing scatterplot of data and model prediction of 0.9 quantile of y given x"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="binary-cross-entropy-loss" class="level3">
<h3 class="anchored" data-anchor-id="binary-cross-entropy-loss">Binary Cross Entropy Loss</h3>
<p>The previous losses are useful for regression problems, where the target is numeric. But we can also solve classification problems, simply by swapping in an appropriate loss function. Here we’ll implement binary cross entropy, a.k.a. binary deviance, a.k.a. negative binomial log likelihood (sometimes abusively called log loss). One thing to remember is that, as with logistic regression, our model is actually predicting the log odds ratio, not the probability of the positive class. Thus we use expit transformations (the inverse of logit) whenever probabilities are needed, e.g., when predicting the probability that an observation belongs to the positive class.</p>
<div id="cell-32" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># make categorical test data</span></span>
<span id="cb18-2"></span>
<span id="cb18-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> expit(t):</span>
<span id="cb18-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.exp(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.exp(t))</span>
<span id="cb18-5"></span>
<span id="cb18-6">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>)</span>
<span id="cb18-7">p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> expit(x)</span>
<span id="cb18-8">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rng.binomial(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, p, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p.shape)</span>
<span id="cb18-9">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</div>
<div id="cell-33" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># from scratch GBM</span></span>
<span id="cb19-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> BinaryCrossEntropyLoss():</span>
<span id="cb19-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''Binary Cross Entropy Loss</span></span>
<span id="cb19-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    </span></span>
<span id="cb19-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Note that the predictions should be log odds ratios.</span></span>
<span id="cb19-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb19-7">    </span>
<span id="cb19-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb19-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.expit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> t: np.exp(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.exp(t))</span>
<span id="cb19-10">    </span>
<span id="cb19-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> loss(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb19-12">        p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.expit(preds)</span>
<span id="cb19-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>np.mean(y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.log(p) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> y) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.log(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p))</span>
<span id="cb19-14">    </span>
<span id="cb19-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> negative_gradient(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, y, preds):</span>
<span id="cb19-16">        p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.expit(preds)</span>
<span id="cb19-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> y) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p)</span>
<span id="cb19-18"></span>
<span id="cb19-19">    </span>
<span id="cb19-20">gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingMachine(n_trees<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb19-21">                              learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb19-22">                              max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb19-23">gbm.fit(x, y, BinaryCrossEntropyLoss())</span>
<span id="cb19-24">pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> expit(gbm.predict(x))</span></code></pre></div></div>
</div>
<div id="cell-34" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># scikit-learn GBM</span></span>
<span id="cb20-2">sk_gbm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GradientBoostingClassifier(n_estimators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb20-3">                                    learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb20-4">                                    max_depth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb20-5">                                    loss<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'log_loss'</span>)</span>
<span id="cb20-6">sk_gbm.fit(x, y)</span>
<span id="cb20-7">sk_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sk_gbm.predict_proba(x)[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span></code></pre></div></div>
</div>
<div id="cell-35" class="cell" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1">print_model_loss_scores(BinaryCrossEntropyLoss(), y, pred, sk_pred)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>From Scratch Loss = 0.6379
Scikit-Learn Loss = 0.6403</code></pre>
</div>
</div>
<div id="cell-36" class="cell" data-scrolled="false" data-execution_count="22">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/gbm-any-loss_files/figure-html/cell-26-output-1.png" class="img-fluid figure-img" alt="Figure showing data and model prediction of probability that y equals one given x"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Woohoo! We did it! We finally made it through Friedman’s paper in its entirety, and we implemented the generic gradient boosting algorithm which works with any differentiable loss function. If you made it this far, great job, gold star! By now you hopefully have a pretty solid grasp on gradient boosting, which is good, because soon we’re going to dive into the modern Newton descent gradient boosting frameworks like XGBoost. Onward!</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p>Friedman’s 2001 paper: <a href="https://statweb.stanford.edu/~jhf/ftp/trebst.pdf">Greedy Function Approximation: A Gradient Boosting Machine</a></p>


</section>

 ]]></description>
  <category>python</category>
  <category>gradient boosting</category>
  <category>from scratch</category>
  <guid>https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/</guid>
  <pubDate>Sat, 23 Oct 2021 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/gradient-boosting-machine-with-any-loss-function/thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Hello PySpark!</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/hello-pyspark/</link>
  <description><![CDATA[ 





<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/hello-pyspark/guiones_wave.jpeg" class="img-fluid figure-img"></p>
<figcaption>A big day at Playa Guiones</figcaption>
</figure>
</div>
<p>Well, you guessed it: it’s time for us to learn PySpark!</p>
<p>I know, I know, I can hear you screaming into your pillow. Indeed we just spent all that time converting from R and learning python and why the hell do we need yet another API for working with dataframes?</p>
<p>That’s a totally fair question.</p>
<p>So what happens when we’re working on something in the real world, where datasets get large in a hurry, and we suddenly have a dataframe that no longer fits into memory? We need a way for our computations and datasets to scale across multiple nodes in a distributed system without having to get too fussy about all the distributed compute details.</p>
<p>Enter PySpark.</p>
<p>I think it’s fair to think of PySpark as a python package for working with arbitrarily large dataframes, i.e., it’s like pandas but scalable. It’s built on top of <a href="https://spark.apache.org/">Apache Spark</a>, a unified analytics engine for large-scale data processing. <a href="https://spark.apache.org/docs/latest/api/python/">PySpark</a> is essentially a way to access the functionality of spark via python code. While there are other high-level interfaces to Spark (such as Java, Scala, and R), for data scientists who are already working extensively with python, PySpark will be the natural interface of choice. PySpark also has great integration with <a href="https://spark.apache.org/docs/latest/sql-programming-guide.html">SQL</a>, and it has a companion machine learning library called <a href="https://spark.apache.org/mllib/">MLlib</a> that’s more or less a scalable scikit-learn (maybe we can cover it in a future post).</p>
<p>So, here’s the plan. First we’re going to get set up to run PySpark locally in a jupyter notebook on our laptop. This is my preferred environment for interactively playing with PySpark and learning the ropes. Then we’re going to get up and running in PySpark as quickly as possible by reviewing the most essential functionality for working with dataframes and comparing it to how we would do things in pandas. Once we’re comfortable running PySpark on the laptop, it’s going to be much easier to jump onto a distributed cluster and run PySpark at scale.</p>
<p>Let’s do this.</p>
<section id="how-to-run-pyspark-in-a-jupyter-notebook-on-your-laptop" class="level2">
<h2 class="anchored" data-anchor-id="how-to-run-pyspark-in-a-jupyter-notebook-on-your-laptop">How to Run PySpark in a Jupyter Notebook on Your Laptop</h2>
<p>Ok, I’m going to walk us through how to get things installed on a Mac or Linux machine where we’re using homebrew and conda to manage virtual environments. If you have a different setup, your favorite search engine will help you get PySpark set up locally.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>It’s possible for Homebrew and Anaconda to interfere with one another. The simple rule of thumb is that whenever you want to use the <code>brew</code> command, first deactivate your conda environment by running <code>conda deactivate</code>. See this <a href="https://stackoverflow.com/questions/42859781/best-practices-with-anaconda-and-brew">Stack Overflow question</a> for more details.</p>
</div>
</div>
<section id="install-spark" class="level3">
<h3 class="anchored" data-anchor-id="install-spark">Install Spark</h3>
<p>Install Spark with homebrew.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">brew</span> install apache-spark</span></code></pre></div></div>
<p>Next we need to set up a <code>SPARK_HOME</code> environment variable in the shell. Check where Spark is installed.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb2-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">brew</span> info apache-spark</span></code></pre></div></div>
<p>You should see something like</p>
<pre><code>==&gt; apache-spark: stable 3.3.2 (bottled), HEAD
Engine for large-scale data processing
https://spark.apache.org/
/opt/homebrew/Cellar/apache-spark/3.3.2 (1,453 files, 320.9MB) *
...</code></pre>
<p>Set the <code>SPARK_HOME</code> environment variable to your spark installation path with <code>/libexec</code> appended to the end. To do this I added the following line to my <code>.zshrc</code> file.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb4-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">export</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">SPARK_HOME</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>/opt/homebrew/Cellar/apache-spark/3.3.2/libexec</span></code></pre></div></div>
<p>Restart your shell, and test the installation by starting the Spark shell.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb5-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">spark-shell</span></span></code></pre></div></div>
<pre><code>...
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 3.3.2
      /_/
         
Using Scala version 2.12.15 (OpenJDK 64-Bit Server VM, Java 19.0.2)
Type in expressions to have them evaluated.
Type :help for more information.

scala&gt; </code></pre>
<p>If you get the <code>scala&gt;</code> prompt, then you’ve successfully installed Spark on your laptop!</p>
</section>
<section id="install-pyspark" class="level3">
<h3 class="anchored" data-anchor-id="install-pyspark">Install PySpark</h3>
<p>Use conda to install the PySpark python package. As usual, it’s advisable to do this in a new virtual environment.</p>
<pre><code>$ conda install pyspark</code></pre>
<p>You should be able to launch an interactive PySpark REPL by saying pyspark.</p>
<pre><code>$ pyspark
...
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 3.1.2
      /_/

Using Python version 3.8.3 (default, Jul  2 2020 11:26:31)
Spark context Web UI available at http://192.168.100.47:4041
Spark context available as 'sc' (master = local[*], app id = local-1624127229929).
SparkSession available as 'spark'.
&gt;&gt;&gt; </code></pre>
<p>This time we get a familiar python <code>&gt;&gt;&gt;</code> prompt. This is an interactive shell where we can easily experiment with PySpark. Feel free to run the example code in this post here in the PySpark shell, or, if you prefer a notebook, read on and we’ll get set up to run PySpark in a jupyter notebook.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>When I tried following this setup on a new Mac, I hit an error about being unable to find the Java Runtime. This <a href="https://stackoverflow.com/questions/75021908/cannot-start-pyspark-unable-to-locate-a-java-runtime">stack overflow question</a> lead me to the fix.</p>
</div>
</div>
</section>
<section id="the-spark-session-object" class="level3">
<h3 class="anchored" data-anchor-id="the-spark-session-object">The Spark Session Object</h3>
<p>You may have noticed that when we launched that PySpark interactive shell, it told us that something called <code>SparkSession</code> was available as <code>'spark'</code>. So basically, what’s happening here is that when we launch the pyspark shell, it instantiates an object called <code>spark</code> which is an instance of class <code>pyspark.sql.session.SparkSession</code>. The spark session object is going to be our entry point for all kinds of PySpark functionality, i.e., we’re going to be saying things like <code>spark.this()</code> and <code>spark.that()</code> to make stuff happen.</p>
<p>The PySpark interactive shell is kind enough to instantiate one of these spark session objects for us automatically. However, when we’re using another interface to PySpark (like say a jupyter notebook running a python kernal), we’ll have to make a spark session object for ourselves.</p>
</section>
<section id="create-a-pyspark-session-in-a-jupyter-notebook" class="level3">
<h3 class="anchored" data-anchor-id="create-a-pyspark-session-in-a-jupyter-notebook">Create a PySpark Session in a Jupyter Notebook</h3>
<p>There are a few ways to run PySpark in jupyter which you can read about <a href="https://www.datacamp.com/community/tutorials/apache-spark-python">here</a>.</p>
<p>For derping around with PySpark on your laptop, I think the best way is to instantiate a spark session from a jupyter notebook running on a regular python kernel. The method we’ll use involves running a standard jupyter notebook session with a python kernal and using the findspark package to initialize the spark session. So, first install the findspark package.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb9-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">conda</span> install <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-c</span> conda-forge findspark</span></code></pre></div></div>
<p>Launch jupyter as usual.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode zsh code-with-copy"><code class="sourceCode zsh"><span id="cb10-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">jupyter</span> notebook</span></code></pre></div></div>
<p>Go ahead and fire up a new notebook using a regular python 3 kernal. Once you land inside the notebook, there are a couple things we need to do to get a spark session instantiated. You can think of this as boilerplate code that we need to run in the first cell of a notebook where we’re going to use PySpark.</p>
<div id="cell-11" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pyspark</span>
<span id="cb11-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> findspark</span>
<span id="cb11-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pyspark.sql <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> SparkSession</span>
<span id="cb11-4"></span>
<span id="cb11-5">findspark.init()</span>
<span id="cb11-6">spark <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SparkSession.builder.appName(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'My Spark App'</span>).getOrCreate()</span></code></pre></div></div>
</div>
<p>First we’re running findspark’s <code>init()</code> method to find our Spark installation. If you run into errors here, make sure you got the <code>SPARK_HOME</code> environment variable correctly set in the install instructions above. Then we instantiate a spark session as <code>spark</code>. Once you run this, you’re ready to rock and roll with PySpark in your jupyter notebook.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>Spark provides a handy web UI that you can use for monitoring and debugging. Once you instantiate the spark session You can open the UI in your web browser at <a href="http://localhost:4040/jobs/">http://localhost:4040/jobs/</a>.</p>
</div>
</div>
</section>
</section>
<section id="pyspark-concepts" class="level2">
<h2 class="anchored" data-anchor-id="pyspark-concepts">PySpark Concepts</h2>
<p>PySpark provides two main abstractions for data: the RDD and the dataframe. <strong>RDD</strong>’s are just a distributed list of objects; we won’t go into details about them in this post. For us, the key object in PySpark is the <strong>dataframe</strong>.</p>
<p>While PySpark dataframes expose much of the functionality you would expect from a library for tabular data manipulation, they behave a little differently from pandas dataframes, both syntactically and under-the-hood. There are a couple of key concepts that will help explain these idiosyncracies.</p>
<p><strong>Immutability</strong> - Pyspark RDD’s and dataframes are immutable. This means that if you change an object, e.g.&nbsp;by adding a column to a dataframe, PySpark returns a reference to a new dataframe; it does not modify the existing dataframe. This is kind of nice, because we don’t have to worry about that whole <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy">view versus copy</a> nonsense that happens in pandas.</p>
<p><strong>Lazy Evaluation</strong> - Lazy evaluation means that when we start manipulating a dataframe, PySpark won’t actually perform any of the computations until we explicitly ask for the result. This is nice because it potentially allows PySpark to do fancy optimizations before executing a sequence of operations. It’s also confusing at first, because PySpark will seem to blaze through complex operations and then take forever to print a few rows of the dataframe.</p>
</section>
<section id="pyspark-dataframe-essentials" class="level2">
<h2 class="anchored" data-anchor-id="pyspark-dataframe-essentials">PySpark Dataframe Essentials</h2>
<section id="creating-a-pyspark-dataframe-with-createdataframe" class="level3">
<h3 class="anchored" data-anchor-id="creating-a-pyspark-dataframe-with-createdataframe">Creating a PySpark dataframe with <code>createDataFrame()</code></h3>
<p>The first thing we’ll need is a way to make dataframes. <a href="https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.SparkSession.createDataFrame.html"><code>createDataFrame()</code></a> allows us to create PySpark dataframes from python objects like nested lists or pandas dataframes. Notice that <code>createDataFrame()</code> is a method of the spark session class, so we’ll call it from our spark session <code>spark</code>by saying <code>spark.createDataFrame()</code>.</p>
<div id="cell-18" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># create pyspark dataframe from nested  lists</span></span>
<span id="cb12-2">my_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> spark.createDataFrame(</span>
<span id="cb12-3">    data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb12-4">        [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2022</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tiger"</span>],</span>
<span id="cb12-5">        [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2023</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rabbit"</span>],</span>
<span id="cb12-6">        [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2024</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dragon"</span>]</span>
<span id="cb12-7">    ],</span>
<span id="cb12-8">    schema<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'year'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'animal'</span>]</span>
<span id="cb12-9">)</span></code></pre></div></div>
</div>
<p>Let’s read the seaborn tips dataset into a pandas dataframe and then use it to create a PySpark dataframe.</p>
<div id="cell-20" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb13-2"></span>
<span id="cb13-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># load tips dataset into a pandas dataframe</span></span>
<span id="cb13-4">pandas_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_csv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv'</span>)</span>
<span id="cb13-5"></span>
<span id="cb13-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># create pyspark dataframe from a pandas dataframe</span></span>
<span id="cb13-7">pyspark_df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> spark.createDataFrame(pandas_df)</span></code></pre></div></div>
</div>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>In real life when we’re running PySpark on a large-scale distributed system, we would not generally want to use python lists or pandas dataframes to load data into PySpark. Ideally we would want to read data directly from where it is stored on HDFS, e.g.&nbsp;by reading <a href="https://spark.apache.org/docs/latest/sql-data-sources-parquet.html">parquet files</a>, or by querying directly from a hive database using <a href="https://spark.apache.org/docs/latest/sql-programming-guide.html">spark sql</a>.</p>
</div>
</div>
</section>
<section id="peeking-at-a-dataframes-contents" class="level3">
<h3 class="anchored" data-anchor-id="peeking-at-a-dataframes-contents">Peeking at a dataframe’s contents</h3>
<p>The default print method for the PySpark dataframe will just give you the schema.</p>
<div id="cell-23" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">pyspark_df</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="4">
<pre><code>DataFrame[total_bill: double, tip: double, sex: string, smoker: string, day: string, time: string, size: bigint]</code></pre>
</div>
</div>
<p>If we want to peek at some of the data, we’ll need to use the <code>show()</code> method, which is analogous to the pandas <code>head()</code>. Remember that <code>show()</code> will cause PySpark to execute any operations that it’s been lazily waiting to evaluate, so sometimes it can take a while to run.</p>
<div id="cell-25" class="cell" data-scrolled="true" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># show the first few rows of the dataframe</span></span>
<span id="cb16-2">pyspark_df.show(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>+----------+----+------+------+---+------+----+
|total_bill| tip|   sex|smoker|day|  time|size|
+----------+----+------+------+---+------+----+
|     16.99|1.01|Female|    No|Sun|Dinner|   2|
|     10.34|1.66|  Male|    No|Sun|Dinner|   3|
|     21.01| 3.5|  Male|    No|Sun|Dinner|   3|
|     23.68|3.31|  Male|    No|Sun|Dinner|   2|
|     24.59|3.61|Female|    No|Sun|Dinner|   4|
+----------+----+------+------+---+------+----+
only showing top 5 rows
</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code>
[Stage 0:&gt;                                                          (0 + 1) / 1]

                                                                                </code></pre>
</div>
</div>
<p>We thus encounter our first rude awakening. PySpark’s default representation of dataframes in the notebook isn’t as pretty as that of pandas. But no one ever said it would be pretty, they just said it would be scalable.</p>
<p>You can also use the <code>printSchema()</code> method for a nice vertical representation of the schema.</p>
<div id="cell-28" class="cell" data-scrolled="true" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># show the dataframe schema</span></span>
<span id="cb19-2">pyspark_df.printSchema()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>root
 |-- total_bill: double (nullable = true)
 |-- tip: double (nullable = true)
 |-- sex: string (nullable = true)
 |-- smoker: string (nullable = true)
 |-- day: string (nullable = true)
 |-- time: string (nullable = true)
 |-- size: long (nullable = true)
</code></pre>
</div>
</div>
</section>
<section id="select-columns-by-name" class="level3">
<h3 class="anchored" data-anchor-id="select-columns-by-name">Select columns by name</h3>
<p>You can select specific columns from a dataframe using the <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.select.html"><code>select()</code></a> method. You can pass either a list of names, or pass names as arguments.</p>
<div id="cell-30" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># select some of the columns</span></span>
<span id="cb21-2">pyspark_df.select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tip'</span>)</span>
<span id="cb21-3"></span>
<span id="cb21-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># select columns in a list</span></span>
<span id="cb21-5">pyspark_df.select([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'day'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>])</span></code></pre></div></div>
</div>
</section>
<section id="filter-rows-based-on-column-values" class="level3">
<h3 class="anchored" data-anchor-id="filter-rows-based-on-column-values">Filter rows based on column values</h3>
<p>Analogous to the <code>WHERE</code> clause in SQL, and the <code>query()</code> method in pandas, PySpark provides a <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.filter.html"><code>filter()</code></a> method which returns only the rows that meet the specified conditions. Its argument is a string specifying the condition to be met for rows to be included in the result. You specify the condition as an expression involving the column names and comparison operators like &lt;, &gt;, &lt;=, &gt;=, == (equal), and ~= (not equal). You can specify compound expressions using <code>and</code> and <code>or</code>, and you can even do a SQL-like <code>in</code> to check if the column value matches any items in a list.</p>
<div id="cell-32" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">## compare a column to a value</span></span>
<span id="cb22-2">pyspark_df.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill &gt; 20'</span>)</span>
<span id="cb22-3"></span>
<span id="cb22-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># compare two columns with arithmetic</span></span>
<span id="cb22-5">pyspark_df.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tip &gt; 0.15 * total_bill'</span>)</span>
<span id="cb22-6"></span>
<span id="cb22-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># check equality with a string value</span></span>
<span id="cb22-8">pyspark_df.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sex == "Male"'</span>)</span>
<span id="cb22-9"></span>
<span id="cb22-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># check equality with any of several possible values</span></span>
<span id="cb22-11">pyspark_df.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'day in ("Sat", "Sun")'</span>)</span>
<span id="cb22-12"></span>
<span id="cb22-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># use "and" </span></span>
<span id="cb22-14">pyspark_df.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'day == "Fri" and time == "Lunch"'</span>)</span></code></pre></div></div>
</div>
<p>If you’re into boolean indexing with the brackets, PySpark does support that too, but I encourage you to use <code>filter()</code> instead. Check out my rant about <a href="../../8020-pandas-tutorial#select-rows-based-on-their-values-with-query">why you shouldn’t use boolean indexing</a> for the details. The TLDR is that <code>filter()</code> requires less typing, makes your code more readable and portable, and it allows you to chain method calls together using dot chains.</p>
<p>Here’s the boolean indexing equivalent of the last example from above.</p>
<div id="cell-34" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># using boolean indexing</span></span>
<span id="cb23-2">pyspark_df[(pyspark_df.day <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Fri'</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> (pyspark_df.time <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Lunch'</span>)]</span></code></pre></div></div>
</div>
<p>I know, it looks horrendous, but not as horrendous as the error message you’ll get if you forget the parentheses.</p>
</section>
<section id="add-new-columns-to-a-dataframe" class="level3">
<h3 class="anchored" data-anchor-id="add-new-columns-to-a-dataframe">Add new columns to a dataframe</h3>
<p>You can add new columns which are functions of the existing columns with the <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.withColumn.html"><code>withColumn()</code></a> method.</p>
<div id="cell-37" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pyspark.sql.functions <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f</span>
<span id="cb24-2"></span>
<span id="cb24-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add a new column using col() to reference other columns</span></span>
<span id="cb24-4">pyspark_df.withColumn(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tip_percent'</span>, f.col(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tip'</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> f.col(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>))</span></code></pre></div></div>
</div>
<p>Notice that we’ve imported the <a href="[pyspark.sql.functions](https://spark.apache.org/docs/2.4.0/api/python/pyspark.sql.html#module-pyspark.sql.functions)"><code>pyspark.sql.functions</code></a> module. This module contains lots of useful functions that we’ll be using all over the place, so it’s probably a good idea to go ahead and import it whenever you’re using PySpark. BTW, it seems like folks usually import this module as <code>f</code> or <code>F</code>. In this example we’re using the <code>col()</code> function, which allows us to refer to columns in our dataframe using string representations of the column names.</p>
<p>You could also achieve the same result using the dot to reference the other columns, but this requires us to type the dataframe name over and over again, which makes it harder to reuse this code on different dataframes or in <a href="https://blog.mattbowers.dev/8020-pandas-tutorial#Chain-transformations-together-with-the-dot-chain">dot chains</a>.</p>
<div id="cell-39" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># add a new column using the dot to reference other columns (less recommended)</span></span>
<span id="cb25-2">pyspark_df.withColumn(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tip_percent'</span>, pyspark_df.tip <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> pyspark_df.total_bill)</span></code></pre></div></div>
</div>
<p>If you want to apply numerical transformations like exponents or logs, use the built-in functions in the <code>pyspark.sql.functions</code> module.</p>
<div id="cell-41" class="cell" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># log </span></span>
<span id="cb26-2">pyspark_df.withColumn(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'log_bill'</span>, f.log(f.col(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>)))</span>
<span id="cb26-3"></span>
<span id="cb26-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># exponent</span></span>
<span id="cb26-5">pyspark_df.withColumn(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bill_squared'</span>, f.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">pow</span>(f.col(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
</div>
<p>You can implement conditional assignment like SQL’s <code>CASE WHEN</code> construct using the <code>when()</code> function and the <code>otherwise()</code> method.</p>
<div id="cell-43" class="cell" data-scrolled="true" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># conditional assignment (like CASE WHEN)</span></span>
<span id="cb27-2">pyspark_df.withColumn(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'is_male'</span>, f.when(f.col(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sex'</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Male'</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>).otherwise(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>))</span>
<span id="cb27-3"></span>
<span id="cb27-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># using multiple when conditions and values</span></span>
<span id="cb27-5">pyspark_df.withColumn(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bill_size'</span>, </span>
<span id="cb27-6">    f.when(f.col(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'small'</span>)</span>
<span id="cb27-7">    .when(f.col(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'medium'</span>)</span>
<span id="cb27-8">    .otherwise(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'large'</span>)</span>
<span id="cb27-9">)</span></code></pre></div></div>
</div>
<p>Remember that since PySpark dataframes are immutable, calling <code>withColumns()</code> on a dataframe returns a new dataframe. If you want to persist the result, you’ll need to make an assignment.</p>
<pre><code>pyspark_df = pyspark_df.withColumns(...)</code></pre>
</section>
<section id="group-by-and-aggregate" class="level3">
<h3 class="anchored" data-anchor-id="group-by-and-aggregate">Group by and aggregate</h3>
<p>PySpark provides a <code>groupBy()</code> method similar to the pandas <code>groupby()</code>. Just like in pandas, we can call methods like <code>count()</code> and <code>mean()</code> on our grouped dataframe, and we also have a more flexible <code>agg()</code> method that allows us to specify column-aggregation mappings.</p>
<div id="cell-46" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1"></span>
<span id="cb29-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># group by and count</span></span>
<span id="cb29-3">pyspark_df.groupBy(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>).count().show()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>+------+-----+
|  time|count|
+------+-----+
|Dinner|  176|
| Lunch|   68|
+------+-----+
</code></pre>
</div>
</div>
<div id="cell-47" class="cell" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1"></span>
<span id="cb31-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># group by and specify column-aggregation mappings with agg()</span></span>
<span id="cb31-3">pyspark_df.groupBy(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>).agg({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_bill'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mean'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tip'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'max'</span>}).show()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>+------+--------+------------------+
|  time|max(tip)|   avg(total_bill)|
+------+--------+------------------+
|Dinner|    10.0| 20.79715909090909|
| Lunch|     6.7|17.168676470588235|
+------+--------+------------------+
</code></pre>
</div>
</div>
<p>If you want to get fancier with your aggregations, it might just be easier to express them using hive syntax. Read on to find out how.</p>
</section>
<section id="run-hive-sql-on-dataframes" class="level3">
<h3 class="anchored" data-anchor-id="run-hive-sql-on-dataframes">Run Hive SQL on dataframes</h3>
<p>One of the mind-blowing features of PySpark is that it allows you to write hive SQL queries on your dataframes. To take a PySpark dataframe into the SQL world, use the <code>createOrReplaceTempView()</code> method. This method takes one string argument which will be the dataframes name in the SQL world. Then you can use <code>spark.sql()</code> to run a query. The result is returned as a PySpark dataframe.</p>
<div id="cell-50" class="cell" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1"></span>
<span id="cb33-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># put pyspark dataframe in SQL world and query it</span></span>
<span id="cb33-3">pyspark_df.createOrReplaceTempView(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tips'</span>)</span>
<span id="cb33-4">spark.sql(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'select * from tips'</span>).show(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>+----------+----+------+------+---+------+----+
|total_bill| tip|   sex|smoker|day|  time|size|
+----------+----+------+------+---+------+----+
|     16.99|1.01|Female|    No|Sun|Dinner|   2|
|     10.34|1.66|  Male|    No|Sun|Dinner|   3|
|     21.01| 3.5|  Male|    No|Sun|Dinner|   3|
|     23.68|3.31|  Male|    No|Sun|Dinner|   2|
|     24.59|3.61|Female|    No|Sun|Dinner|   4|
+----------+----+------+------+---+------+----+
only showing top 5 rows
</code></pre>
</div>
</div>
<p>This is awesome for a couple of reasons. First, it allows us to easily express any transformations in hive syntax. If you’re like me and you’ve already been using hive, this will dramatically reduce the PySpark learning curve, because when in doubt, you can always bump a dataframe into the SQL world and simply use hive to do what you need. Second, if you have a hive deployment, PySpark’s SQL world also has access to all of your hive tables. This means you can write queries involving both hive tables and your PySpark dataframes. It also means you can run hive commands, like inserting into a table, directly from PySpark.</p>
<p>Let’s do some aggregations that might be a little trickier to do using the PySpark built-in functions.</p>
<div id="cell-53" class="cell" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1"></span>
<span id="cb35-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># run hive query and save result to dataframe</span></span>
<span id="cb35-3">tip_stats_by_time <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> spark.sql(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb35-4"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    select</span></span>
<span id="cb35-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        time</span></span>
<span id="cb35-6"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        , count(*) as n </span></span>
<span id="cb35-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        , avg(tip) as avg_tip</span></span>
<span id="cb35-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        , percentile_approx(tip, 0.5) as med_tip</span></span>
<span id="cb35-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        , avg(case when tip &gt; 3 then 1 else 0 end) as pct_tip_gt_3</span></span>
<span id="cb35-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    from </span></span>
<span id="cb35-11"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        tips</span></span>
<span id="cb35-12"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    group by 1</span></span>
<span id="cb35-13"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span>)</span>
<span id="cb35-14"></span>
<span id="cb35-15">tip_stats_by_time.show()</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>+------+---+------------------+-------+-------------------+
|  time|  n|           avg_tip|med_tip|       pct_tip_gt_3|
+------+---+------------------+-------+-------------------+
|Dinner|176| 3.102670454545455|    3.0|0.44886363636363635|
| Lunch| 68|2.7280882352941176|    2.2|0.27941176470588236|
+------+---+------------------+-------+-------------------+
</code></pre>
</div>
</div>
</section>
</section>
<section id="visualization-with-pyspark" class="level2">
<h2 class="anchored" data-anchor-id="visualization-with-pyspark">Visualization with PySpark</h2>
<p>There aren’t any tools for visualization included in PySpark. But that’s no problem, because we can just use the <code>toPandas()</code> method on a PySpark dataframe to pull data back into pandas. Once we have a pandas dataframe, we can happily build visualizations as usual. Of course, if your PySpark dataframe is huge, you wouldn’t want to use <code>toPandas()</code> directly, because PySpark will attempt to read the entire contents of its huge dataframe into memory. Instead, it’s best to use PySpark to generate aggregations of your data for plotting or to pull only a sample of your full data into pandas.</p>
<div id="cell-55" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># read aggregated pyspark dataframe into pandas for plotting</span></span>
<span id="cb37-2">plot_pdf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tip_stats_by_time.toPandas()</span>
<span id="cb37-3">plot_pdf.plot.bar(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'time'</span>, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'avg_tip'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'med_tip'</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/hello-pyspark/hello-pyspark_files/figure-html/cell-21-output-1.png" class="img-fluid figure-img" alt="Figure showing a bar plot of average and median tips by time"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>So that’s a wrap on our crash course in working with PySpark. You now have a good idea of what pyspark is and how to get started manipulating dataframes with it. Stay tuned for a future post on PySpark’s companion ML library MLlib. In the meantime, may no dataframe be too large for you ever again.</p>


</section>

 ]]></description>
  <category>python</category>
  <category>PySpark</category>
  <category>tutorial</category>
  <guid>https://randomrealizations.com/posts/hello-pyspark/</guid>
  <pubDate>Tue, 22 Jun 2021 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/hello-pyspark/guiones_wave.jpeg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>How Gradient Boosting Does Gradient Descent</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/how-gradient-boosting-does-gradient-descent/</link>
  <description><![CDATA[ 





<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/how-gradient-boosting-does-gradient-descent/main.jpg" class="img-fluid figure-img"></p>
<figcaption>A whiteboard session at Playa Pelada</figcaption>
</figure>
</div>
<p>In the last two posts, we learned the basics of <a href="../../posts/gradient-boosting-machine-from-scratch/">gradient boosting machines</a> and the <a href="../../posts/get-down-with-gradient-descent/">gradient descent algorithm</a>. But we still haven’t explicitly addressed what puts the “gradient” in gradient boosting. It turns out that gradient boosting models are using a sort of gradient descent to minimize their loss function; according to <a href="https://statweb.stanford.edu/~jhf/ftp/trebst.pdf">Friedman’s classic paper</a>, they’re doing gradient descent in “function space”. If you’re like me, and this is your first encounter with this idea, then the phrase “gradient descent in function space” is going to sound a little, ahem, mysterious. No worries, friends; we’re about to make sense of it all.</p>
<p>Understanding the underlying mechanics of gradient boosting as a form of gradient descent will empower us to train our models with custom loss functions. This opens up many interesting possibilities including doing not only regression and classification, but also predicting quantiles, prediction intervals, and even the conditional probability distribution of the response variable.</p>
<section id="generalized-intuition-for-gradient-boosting" class="level2">
<h2 class="anchored" data-anchor-id="generalized-intuition-for-gradient-boosting">Generalized intuition for gradient boosting</h2>
<p>In my earlier post on <a href="../../posts/gradient-boosting-machine-from-scratch/">building a gradient boosting model from scratch</a>, we established the intuition for how gradient boosting works in a regression problem. In this post we’re going to generalize the ideas we encountered in the regression context, so check out the earlier post if you’re not already familiar with gradient boosting for regression. In the following sections we’ll build up the intuition for gradient boosting in general terms, and then we’ll be able to state the gradient boosting algorithm in a form that can fit models to customized loss functions.</p>
<section id="the-loss-function" class="level3">
<h3 class="anchored" data-anchor-id="the-loss-function">The loss function</h3>
<p>You recall that we measure how well a model fits data by using a <em>loss function</em> that yields small values when a model fits well. “Training” essentially means finding the model that minimizes our loss function. A loss function takes the correct target values and the predicted target values, and it returns a scalar loss score. For example, in the last post on gradient descent we used a mean squared error (MSE) loss</p>
<p><img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%20%5Chat%7B%5Cmathbf%7By%7D%7D)%20=%20%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(y_i%20-%20%5Chat%7By%7D_i)%5E2%20"></p>
<p>where we express the correct targets and predicted values as the vector arguments <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D=%5By_1,y_2,%5Cdots,y_n%5D"> and <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cmathbf%7By%7D%7D=%5B%5Chat%7By%7D_1,%5Chat%7By%7D_2,%5Cdots,%5Chat%7By%7D_n%5D"> respectively.</p>
</section>
<section id="which-way-to-nudge-a-prediction-to-get-a-better-model" class="level3">
<h3 class="anchored" data-anchor-id="which-way-to-nudge-a-prediction-to-get-a-better-model">Which way to nudge a prediction to get a better model</h3>
<p>Now, let’s say we have a model <img src="https://latex.codecogs.com/png.latex?F(%5Cmathbf%7BX%7D)=%5Cmathbf%7B%5Chat%7By%7D%7D"> that we want to improve. One approach is that we could figure out whether each prediction <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> needed to be higher or lower to get a better loss score. We could then nudge each prediction in the right direction, thereby decreasing our model’s loss score.</p>
<p>To figure out whether we should increase or decrease a particular prediction <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> (and by how much), we can compute the partial derivative of the loss function with respect to that prediction. Recall the partial derivative just tells us the rate of change in a function when we change one of its arguments. Since we want to make the loss <img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)"> decrease, we can use the negative partial derivative of the loss function with respect to a given prediction to help us choose the right nudge for that prediction.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Ctext%7Bnudge%20for%20%7D%20%5Chat%7By%7D_i%20=%20-%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_i%7D"></p>
<p>Sometimes it can get a little intense when there are partial derivatives flying around, but it doesn’t have to be that way. Remember that in practice <img src="https://latex.codecogs.com/png.latex?-%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_i%7D"> is just an expression that evaluates to a number like 2.7 or -0.5, and here it’s telling us how to nudge <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> to decrease our loss score.</p>
<p>The intuition is that if <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_i%7D"> is negative, then increasing the prediction <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> will make the loss decrease. We then notice that the negative of the partial derivative tells us whether to increase or decrease <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i">. For example, if <img src="https://latex.codecogs.com/png.latex?-%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_i%7D"> is positive, then <em>increasing</em> the prediction <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> will make the loss decrease; whereas if <img src="https://latex.codecogs.com/png.latex?-%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_i%7D"> is negative, then <em>decreasing</em> the prediction <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> will make the loss decrease.</p>
<p>Since we’ll want to find the right nudge for each of the <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i">’s, we can use the negative gradient of the loss function <img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)"> with respect to the vector argument <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cmathbf%7By%7D%7D"> to get the vector of all the partial derivatives. Let’s call this vector of desired nudge values <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D%20=%20-%5Cnabla_%7B%5Chat%7B%5Cmathbf%7By%7D%7D%7D%20L(%5Cmathbf%7By%7D,%20%5Chat%7B%5Cmathbf%7By%7D%7D)%20=%20%5Cleft%20%5B%20-%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_1%7D,%20-%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_2%7D,%20%5Ccdots,%20-%5Cfrac%7B%5Cpartial%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)%7D%7B%5Cpartial%20%5Chat%7By%7D_n%7D%5Cright%20%5D"></p>
</section>
<section id="nudging-predictions-in-the-right-direction" class="level3">
<h3 class="anchored" data-anchor-id="nudging-predictions-in-the-right-direction">Nudging predictions in the right direction</h3>
<p>Great, now that we know we should nudge each prediction in the direction of the negative partial derivative of the loss with respect to that prediction, we need to figure out how to do the actual nudging. Remember that we already have an initial model <img src="https://latex.codecogs.com/png.latex?F(%5Cmathbf%7BX%7D)=%5Cmathbf%7B%5Chat%7By%7D%7D">.</p>
<p>At this point we might be tempted to simply add the vector of nudge values to our predictions to get better predictions.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bwe%20might%20be%20tempted%20to%20try%20%7D%20%5Cmathbf%7B%5Chat%7By%7D%7D_%7B%5Ctext%7Bnew%7D%7D%20=%20%5Cmathbf%7B%5Chat%7By%7D%7D%20+%20%5Cmathbf%7Br%7D"></p>
<p>Sure, based on our reasoning in the previous section, plugging the vector of nudged predictions into the loss function would yield a lower loss score.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D%20+%20%5Cmathbf%7Br%7D)%20%5Cle%20L(%5Cmathbf%7By%7D,%5Cmathbf%7B%5Chat%7By%7D%7D)"></p>
<p>The problem is that this will only work for in-sample data, because we only know the nudge values for the cases which are present in the training dataset. In order for our model to generalize to unseen test data, we need a way to get the nudge values for new observations of the independent variables. So how can we do that?</p>
<p>Well what if we fit another model <img src="https://latex.codecogs.com/png.latex?h(%5Cmathbf%7BX%7D)"> that used our same features <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D"> to predict our desired nudge values <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D">, and then we added that new model to our original model <img src="https://latex.codecogs.com/png.latex?F(%5Cmathbf%7BX%7D)">. For a given prediction the nudge model <img src="https://latex.codecogs.com/png.latex?h(%5Cmathbf%7BX%7D)"> would essentially return an approximation of the desired nudge, so adding it would push the prediction in the right direction to decrease the loss function. Furthermore, the nudge model can return predictions of the nudges for out-of-sample cases which are not present in the training dataset. Since both the initial model <img src="https://latex.codecogs.com/png.latex?F(%5Cmathbf%7BX%7D)"> and the nudge model <img src="https://latex.codecogs.com/png.latex?h(%5Cmathbf%7BX%7D)"> are functions of our features <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D">, we can add the two functions to get an updated model that can generalize beyond the training data.</p>
<p><img src="https://latex.codecogs.com/png.latex?F_%7B%5Ctext%7Bnew%7D%7D%20(%5Cmathbf%7BX%7D)%20=%20F(%5Cmathbf%7BX%7D)%20+%20h(%5Cmathbf%7BX%7D)"></p>
</section>
</section>
<section id="a-generalized-gradient-boosting-algorithm" class="level2">
<h2 class="anchored" data-anchor-id="a-generalized-gradient-boosting-algorithm">A generalized gradient boosting algorithm</h2>
<p>Ok, let’s put these pieces of intuition together to create a more general gradient boosting algorithm recipe.</p>
<p>We begin with training data <img src="https://latex.codecogs.com/png.latex?(%5Cmathbf%7By%7D,%20%5Cmathbf%7BX%7D)"> where <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D"> is a length-<img src="https://latex.codecogs.com/png.latex?n"> vector of target values, and <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D"> is an <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20p"> matrix with <img src="https://latex.codecogs.com/png.latex?n"> observations of <img src="https://latex.codecogs.com/png.latex?p"> features. We also have a differentiable loss function <img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D)">, a “learning rate” hyperparameter <img src="https://latex.codecogs.com/png.latex?%5Ceta">, and a fixed number of model iterations <img src="https://latex.codecogs.com/png.latex?M">.</p>
<p>We create an initial model <img src="https://latex.codecogs.com/png.latex?F_0(%5Cmathbf%7BX%7D)"> that predicts a constant value. We choose the constant value that would give the best loss score.</p>
<p><img src="https://latex.codecogs.com/png.latex?F_0(%5Cmathbf%7BX%7D)%20=%20%5Cunderset%7Bc%7D%7B%5Coperatorname%7Bargmin%7D%7D%20L(%5Cmathbf%7By%7D,%20c)"></p>
<p>Then we iteratively update the initial model with <img src="https://latex.codecogs.com/png.latex?M"> nudge models.</p>
<p>For <img src="https://latex.codecogs.com/png.latex?m"> in 0 to <img src="https://latex.codecogs.com/png.latex?M-1">:</p>
<ul>
<li>Compute current composite model predictions <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Chat%7By%7D%7D_%7Bm%7D%20=%20F_%7Bm%7D(%5Cmathbf%7BX%7D)">.</li>
<li>Compute the desired nudge values given by the negative gradient of the loss function with respect to each prediction <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D_m%20=%20-%20%5Cnabla_%7B%5Cmathbf%7B%5Chat%7By%7D%7D_m%7D%20L%20(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D_m)">.</li>
<li>Fit a weak model (e.g.&nbsp;shallow decision tree) <img src="https://latex.codecogs.com/png.latex?h_%7Bm%7D(%5Cmathbf%7BX%7D)"> that predicts the nudge values <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D_%7Bm%7D"> using features <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D">.</li>
<li>Update the composite model.</li>
</ul>
<p><img src="https://latex.codecogs.com/png.latex?F_%7Bm+1%7D(%5Cmathbf%7BX%7D)%20=%20F_%7Bm%7D(%5Cmathbf%7BX%7D)%20+%20%5Ceta%20h_%7Bm%7D(%5Cmathbf%7BX%7D)"></p>
<p>After <img src="https://latex.codecogs.com/png.latex?M"> iterations, we are left with the final composite model <img src="https://latex.codecogs.com/png.latex?F_M(%5Cmathbf%7BX%7D)">.</p>
</section>
<section id="wait-in-what-sense-is-this-doing-gradient-descent" class="level2">
<h2 class="anchored" data-anchor-id="wait-in-what-sense-is-this-doing-gradient-descent">Wait, in what sense is this doing gradient descent?</h2>
<p>In my <a href="../../posts/get-down-with-gradient-descent/">previous post</a>, we learned how to use gradient descent to iteratively update model parameters to find a model that minimizes the loss function. We could write the update rule as</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Cmathbf%7B%5Ctheta%7D_%7Bt+1%7D%20=%20%5Cmathbf%7B%5Ctheta%7D_%7Bt%7D%20+%20%5Ceta%20(%20-%20%5Cnabla_%7B%5Cmathbf%7B%5Ctheta%7D%7D%20L(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D_%7B%5Cmathbf%7B%5Ctheta%7D_%7Bt%7D%7D)%20)%20"></p>
<p>where the predictions <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Chat%7By%7D%7D"> depend on the model parameters <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Ctheta%7D">, and we’re trying to find the value of the parameter vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Ctheta%7D"> that minimizes the loss function <img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D_%7B%5Cmathbf%7B%5Ctheta%7D_%7Bt%7D%7D)">, so we nudge the vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Ctheta%7D_t"> by the negative gradient of <img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D_%7B%5Cmathbf%7B%5Ctheta%7D_%7Bt%7D%7D)"> with respect to <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Ctheta%7D_t">. Compare that with the boosting model update rule we obtained in the previous section.</p>
<p><img src="https://latex.codecogs.com/png.latex?F_%7Bm+1%7D(%5Cmathbf%7BX%7D)%20=%20F_%7Bm%7D(%5Cmathbf%7BX%7D)%20+%20%5Ceta%20h_%7Bm%7D(%5Cmathbf%7BX%7D)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?h_%7Bm%7D(%5Cmathbf%7BX%7D)%20%5Capprox%20-%20%5Cnabla_%7B%5Cmathbf%7B%5Chat%7By%7D%7D_m%7D%20L%20(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D_m)">.</p>
<p>If we replace <img src="https://latex.codecogs.com/png.latex?F(%5Cmathbf%7BX%7D)"> with its prediction vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Chat%7By%7D%7D">, and we replace the nudge model <img src="https://latex.codecogs.com/png.latex?h(%5Cmathbf%7BX%7D)"> with the negative gradient of the loss function (which it approximates), the likeness to the parameter gradient descent update rule becomes more obvious.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Chat%7By%7D%7D_%7Bm+1%7D%20%5Capprox%20%5Cmathbf%7B%5Chat%7By%7D%7D_m%20+%20%5Ceta%20(-%20%5Cnabla_%7B%5Cmathbf%7B%5Chat%7By%7D%7D_m%7D%20L%20(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D_m))"></p>
<p>Indeed, gradient boosting is performing gradient descent to obtain a good model by minimizing a loss function. But there are a couple of key differences between gradient boosting and the parameter gradient descent that we discussed in the previous post.</p>
</section>
<section id="gradient-boosting-versus-parameter-gradient-descent" class="level2">
<h2 class="anchored" data-anchor-id="gradient-boosting-versus-parameter-gradient-descent">Gradient boosting versus parameter gradient descent</h2>
<p>The generic gradient boosting algorithm outlined above implies two key differences from parameter gradient descent.</p>
<ol type="1">
<li>Instead of nudging parameters, we nudge each individual prediction, thus instead of taking the gradient of loss with respect to the parameters, we take the gradient with respect to the predictions.</li>
<li>Instead of directly adding the negative gradient to our current parameter values, we create a functional approximation of the negative gradient and add that to our model. Our functional approximation is just a crappy model that tries to use the model features to predict the negative gradient of the loss with respect to our current model predictions.</li>
</ol>
<p>The true genius of the gradient boosting algorithm is in chasing the negative gradient of the loss with crappy models, rather than using it to directly update our predictions. If we just directly added the negative gradient of the loss to our predictions, and plugged them into the loss function we could get a lower loss score, but our updated model would be useless since it couldn’t make predictions on new out-of-sample data. Instead we train a crappy model to predict the negative gradient of the loss with respect to the current model predictions, thus we can iteratively update our composite model by adding these crappy models to it.</p>
</section>
<section id="gradient-boosting-is-gradient-descent-in-function-space-a.k.a.-prediction-space" class="level2">
<h2 class="anchored" data-anchor-id="gradient-boosting-is-gradient-descent-in-function-space-a.k.a.-prediction-space">Gradient boosting is gradient descent in function space, a.k.a. prediction space</h2>
<p>Let’s address the statement in <a href="https://statweb.stanford.edu/~jhf/ftp/trebst.pdf">Friedman’s classic paper</a> that gradient boosting is doing gradient descent in function space. Again we’ll use parameter gradient descent as a basis for comparison.</p>
<p>In parameter gradient descent, we have a vector of parameter values which, when plugged into the loss function, return some loss score. At each step of gradient descent, we compute the negative gradient of the loss function with respect to each parameter; that tells us which way to nudge each parameter value to achieve a lower loss score. We then add this vector of parameter nudge values to our previous parameter vector to get the new parameter vector. We could view this sequence of successive parameter vectors as a trajectory passing through <em>parameter space</em>, the space spanned by all possible parameter values. Therefore parameter gradient descent operates in parameter space.</p>
<p>In contrast, when we do gradient boosting, at each step we have a model, a.k.a. a function, that maps feature values to predictions. Given our training dataset, this model yields predictions which can be plugged into our loss function to get a loss score. At each boosting iteration, we compute the negative gradient of the loss with respect to each of the predictions; that tells us which way to nudge each prediction to achieve a lower loss score. We then create a function (a crappy model) that takes feature values and returns an approximation of the corresponding prediction’s nudge value. We then add this crappy model (a function) to our current composite model (also a function) to get the new composite model (you guessed it; also a function). And so by analogy with parameter vectors in parameter space, we can view this sequence of successive model functions as a trajectory passing through <em>function space</em>, the space spanned by all possible functions that map feature values to predictions. Therefore, gradient boosting does gradient descent in function space.</p>
<p>If this talk about function space still feels a little abstract, you could just use the same substitution trick we used above and swap the model <img src="https://latex.codecogs.com/png.latex?F(%5Cmathbf%7BX%7D)"> for its predictions <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7B%5Chat%7By%7D%7D"> which is just a vector of numbers. The target values for our nudge models are given by the negative gradient of the loss with respect to this prediction vector. From here, we can see that each time we add a new nudge model to our composite model, we get a new prediction vector. We can view this sequence of successive prediction vectors as a trajectory passing through <em>prediction space</em>, the space spanned by all possible prediction vector values. Therefore we can also say that gradient boosting does gradient descent in prediction space.</p>
</section>
<section id="so-why-did-we-fit-the-crappy-models-to-the-residuals-in-our-regression-gbm" class="level2">
<h2 class="anchored" data-anchor-id="so-why-did-we-fit-the-crappy-models-to-the-residuals-in-our-regression-gbm">So why did we fit the crappy models to the residuals in our regression GBM?</h2>
<p>In my first post on [gradient boosting machines](/gradient-boosting-machine-from-scratch, in the interest of simplicity I left one key aspect of the problem unaddressed, that is, what loss function were we using to train that GBM? It turns out that because of the way we built our GBM, without knowing it we were actually using a mean squared error (MSE) loss function.</p>
<p><img src="https://latex.codecogs.com/png.latex?L(%5Cmathbf%7By%7D,%20%5Chat%7B%5Cmathbf%7By%7D%7D)%20=%20%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(y_i%20-%20%5Chat%7By%7D_i)%5E2%20"></p>
<p>If the GBM was using gradient descent to find a <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cmathbf%7By%7D%7D"> vector that minimized this loss function, then at each iteration it would have to nudge the current <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cmathbf%7By%7D%7D"> by the negative gradient of the loss function with respect to <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cmathbf%7By%7D%7D">, i.e.&nbsp;<img src="https://latex.codecogs.com/png.latex?-%5Cnabla_%7B%5Chat%7B%5Cmathbf%7By%7D%7D%7D%20L(%5Cmathbf%7By%7D,%20%5Chat%7B%5Cmathbf%7By%7D%7D)">. Since our loss function takes a length <img src="https://latex.codecogs.com/png.latex?n"> vector of predictions <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5Cmathbf%7By%7D%7D"> as input, the gradient will be a length-<img src="https://latex.codecogs.com/png.latex?n"> vector of partial derivatives with respect to each of the predictions <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i">. Let’s start by taking the negative partial derivative with respect to a particular prediction <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_j">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Barray%7D%7Brcl%7D%0A-%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20%5Chat%7By%7D_j%7D%20L(%5Cmathbf%7By%7D,%20%5Cmathbf%7B%5Chat%7By%7D%7D)%0A%20%20%20%20&amp;%20=%20&amp;%20-%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20%5Chat%7By%7D_j%7D%20%5Cleft%20(%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(y_i%20-%20%5Chat%7By%7D_i)%5E2%20%5Cright%20)%20%5C%5C%0A%20%20%20%20&amp;%20=%20&amp;%20-%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20%5Chat%7By%7D_j%7D%20%5Cleft%20(%20%5Cfrac%7B1%7D%7Bn%7D%20(y_j%20-%20%5Chat%7By%7D_j)%5E2%20%5Cright%20)%20%5C%5C%0A%20%20%20%20&amp;%20=%20&amp;%20-%5Cfrac%7B1%7D%7Bn%7D%20(2)(y_j%20-%20%5Chat%7By%7D_j)%20%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20%5Chat%7By%7D_j%7D%20(y_j%20-%20%5Chat%7By%7D_j)%20%5C%5C%0A%20%20%20%20&amp;%20=%20&amp;%20%5Cfrac%7B2%7D%7Bn%7D%20(y_j%20-%20%5Chat%7By%7D_j)%20%5C%5C%0A%5Cend%7Barray%7D%0A"></p>
<p>It turns out that the negative partial derivative of the MSE loss function with respect to a particular prediction <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> is proportional to the residual <img src="https://latex.codecogs.com/png.latex?y_i%20-%20%5Chat%7By%7D_i">! This is a pretty intuitive result, because if we nudge a prediction by it’s residual, we’ll end up with the correct target value.</p>
<p>We can go ahead and write the nudge vector as</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Br%7D%20=%20-%5Cnabla_%7B%5Chat%7B%5Cmathbf%7By%7D%7D%7D%20L(%5Cmathbf%7By%7D,%20%5Chat%7B%5Cmathbf%7By%7D%7D)%20=%20%5Cfrac%7B2%7D%7Bn%7D(%5Cmathbf%7By%7D%20-%20%5Chat%7B%5Cmathbf%7By%7D%7D)"></p>
<p>which is proportional to the residual vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7By%7D%20-%20%5Chat%7B%5Cmathbf%7By%7D%7D">. This means that when we use the mean squared error loss function, our nudge values are given by the current model residuals, and therefore each new crappy model targets the previous model’s residuals.</p>
<p>And this result brings us full circle, back to our original intuition from the first GBM post about chasing residuals with crappy models. Now we see that intuitive idea is just a special case of the more general and, dare I say, even more beautiful idea of chasing the negative gradient of the loss function with crappy models.</p>
</section>
<section id="key-takeaways" class="level2">
<h2 class="anchored" data-anchor-id="key-takeaways">Key Takeaways</h2>
<p>We covered a lot of conceptual ground in this post, so let’s recap the key ideas.</p>
<ol type="1">
<li>Gradient boosting can use gradient descent to minimize any differentiable loss function in service of creating a good final model.</li>
<li>There are two key differences between gradient boosting and parameter gradient descent:
<ul>
<li>In gradient boosting, we nudge prediction values rather than parameter values, so to find the desired nudge values, we take the negative gradient of the loss function with respect to the predictions.</li>
<li>In gradient boosting, we nudge our predictions by adding a crappy model that approximates the nudge values, rather than adding the nudge values directly to the predictions.</li>
</ul></li>
<li>Gradient boosting does gradient descent in function space. But since the model predictions are just numeric vectors, and since we take the gradient of the loss function with respect to the prediction vector, it’s also valid and probably easier to think of gradient boosting as gradient descent in prediction space.</li>
<li>We saw that iteratively fitting crappy models to the previous model residuals, as we did in the regression GBM from scratch post, is just a special case of fitting crappy models to the negative gradient of the loss function (in this case the mean squared error loss).</li>
</ol>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>Phew, there it is, how gradient boosting models do gradient descent in function space. Understanding how the general form of gradient boosting works opens up the possibility for us to use any differentiable loss function for model training. That is pretty exciting because it means that we can get a lot of mileage out of this one class of learning algorithms. Stay tuned for more on some of the awesome things we can do with these ideas in future posts!</p>
<p>There are a couple of resources I found to be super helpful while researching the content in this post. Definitely check them out if you want to read more about gradient boosting and gradient descent.</p>
<p><a href="https://explained.ai/gradient-boosting/">How to explain gradient boosting</a> by Terence Parr and Jeremy Howard</p>
<p><a href="http://nicolas-hug.com/blog/gradient_boosting_descent">Understanding Gradient Boosting as Gradient Descent</a> by Nicolas Hug</p>


</section>

 ]]></description>
  <category>gradient boosting</category>
  <guid>https://randomrealizations.com/posts/how-gradient-boosting-does-gradient-descent/</guid>
  <pubDate>Tue, 27 Apr 2021 07:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/how-gradient-boosting-does-gradient-descent/thumbnail.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Get Down with Gradient Descent</title>
  <dc:creator>Matt Bowers</dc:creator>
  <link>https://randomrealizations.com/posts/get-down-with-gradient-descent/</link>
  <description><![CDATA[ 





<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/gd_get_down.png" title="dancer getting down" class="img-fluid"></p>
<p>Ahh, gradient descent. It’s probably one of the most ubiquitous algorithms used in data science, but you’re unlikely to see it being celebrated in the limelight of the Kaggle podium. Rather than taking center stage, gradient descent operates under the hood, powering the training for a wide range of models including deep neural networks, gradient boosting trees, generalized linear models, and mixed effects models. Getting an intuition for the algorithm will reveal how model fitting actually works and help us to see the common thread connecting a wide range of seemingly unrelated models. In this post we’ll get the intuition for gradient descent with a <em>fresh</em> analogy, develop the mathematical formulation, and ground our understanding by using it to train ourselves a linear regression model.</p>
<section id="intuition" class="level2">
<h2 class="anchored" data-anchor-id="intuition">Intuition</h2>
<p>Before we dive into the intuition for gradient descent itself, let’s get a high-level view of why it’s useful in <em>training</em> or <em>fiting</em> a model. Training a model basically means finding the model parameter values that make the model fit a given dataset well. We measure how well a model fits data using a special function variously called a <em>loss</em> or <em>cost</em> or <em>objective</em> function. A loss function takes the dataset and the model as arguments and returns a number that tells us how well our model fits the data. Therefore training is an optimization problem in which we search for the model parameter values that result in the minimum value of the loss function. Enter <em>gradient descent</em>.</p>
<p>Gradient descent is a numerical optimization technique that helps us find the inputs that yield the minimum value of a function. Since most explanations of the gradient descent algorithm seem to use a story about hikers being lost in some foggy mountains, we’re going to try out a new analogy.</p>
<p>Let’s say you’re at a concert. Remember those? They’re these things that used to happen where people played music and everyone danced and had a great time.</p>
<blockquote class="blockquote">
<p><strong><em>NOTE:</em></strong> Chiming in here in 2023 from a sort-of-post COVID 19 world, happily I can report that concerts and live music are back!</p>
</blockquote>
<p>Now suppose at this concert there’s a dance floor which has become a bit sweltering from copious amounts of “getting down”. But the temperature isn’t quite uniform; maybe there’s a cool spot from a ceiling fan somewhere.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/gd_dance_floor.png" title="dance floor" class="img-fluid figure-img"></p>
<figcaption>dance floor</figcaption>
</figure>
</div>
<p>Let’s get ourselves to that cool spot using the following procedure.</p>
<ol type="1">
<li>From our current location, figure out which direction feels coolest.</li>
<li>Take a step (or simply shimmy) in that direction.</li>
<li>Repeat steps 1 and 2 until we reach the coolest spot on the dance floor.</li>
</ol>
<p>The crux of this procedure is figuring out, at each step, which direction yields the greatest temperature reduction. Our skin is pretty sensitive to temperature, so we can just use awareness of body sensation to sense which direction feels coolest. Luckily, we have a mathematical equivalent to our skin’s ability to sense local variation in temperature.</p>
<section id="determine-which-way-to-go" class="level3">
<h3 class="anchored" data-anchor-id="determine-which-way-to-go">Determine which way to go</h3>
<p>Let <img src="https://latex.codecogs.com/png.latex?f(x,y)"> be the temperature on the dance floor at position <img src="https://latex.codecogs.com/png.latex?(x,y)">. The direction of fastest decrease in temperature is going to be given by some vector in our <img src="https://latex.codecogs.com/png.latex?(x,y)"> space, e.g.,</p>
<p>[vector component in <img src="https://latex.codecogs.com/png.latex?x"> direction, vector component in <img src="https://latex.codecogs.com/png.latex?y"> direction]</p>
<p>Turns out that the gradient of a function evaluated at a particular location yields a vector that points in the direction of fastest <em>increase</em> in the function, pretty similar to what we’re looking for. The gradient of <img src="https://latex.codecogs.com/png.latex?f(x,y)"> is given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Cnabla%20f(x,y)%20=%20%5Cleft%20%5B%20%5Cfrac%7B%5Cpartial%20f(x,y)%7D%7B%5Cpartial%20x%7D,%20%5Cfrac%7B%5Cpartial%20f(x,y)%7D%7B%5Cpartial%20y%7D%20%5Cright%20%5D%20"></p>
<p>The components of the gradient vector are the partial derivatives of our function <img src="https://latex.codecogs.com/png.latex?f(x,y)">, evaluated at the point <img src="https://latex.codecogs.com/png.latex?(x,y)">. These partial derivatives just tell us the slope of <img src="https://latex.codecogs.com/png.latex?f(x,y)"> in the <img src="https://latex.codecogs.com/png.latex?x"> and <img src="https://latex.codecogs.com/png.latex?y"> directions respectively. The intuition is that if <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20f(x,y)%7D%7B%5Cpartial%20x%7D"> is a large positive number, then moving in the positive <img src="https://latex.codecogs.com/png.latex?x"> direction will make <img src="https://latex.codecogs.com/png.latex?f(x,y)"> increase a lot, whereas if <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20f(x,y)%7D%7B%5Cpartial%20x%7D"> is a large negative number, then moving in the <em>negative</em> <img src="https://latex.codecogs.com/png.latex?x"> direction will make <img src="https://latex.codecogs.com/png.latex?f(x,y)"> increase a lot.</p>
<p>It’s not too hard to see that the direction of fastest decrease is actually just the exact opposite direction from that of fastest increase. Since we can point a vector in the opposite direction by negating its component values, our direction of fastest temperature decrease will be given by the negative gradient of the temperature field <img src="https://latex.codecogs.com/png.latex?-%5Cnabla%20f(x,y)">.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/gd_local_change.png" class="img-fluid figure-img"></p>
<figcaption>dance floor with hot and cold sides</figcaption>
</figure>
</div>
</section>
<section id="take-a-step-in-the-right-direction" class="level3">
<h3 class="anchored" data-anchor-id="take-a-step-in-the-right-direction">Take a step in the right direction</h3>
<p>Now that we have our direction vector, we’re ready to take a step toward the cool part of the dance floor. To do this, we’ll just add our direction vector to our current position. The update rule would look like this.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Bx_%5Ctext%7Bnext%7D,%20y_%5Ctext%7Bnext%7D%5D%20=%20%5Bx_%5Ctext%7Bprev%7D,%20y_%5Ctext%7Bprev%7D%5D%20-%20%5Cnabla%20f%20(x_%5Ctext%7Bprev%7D,%20y_%5Ctext%7Bprev%7D)%20=%20%5Bx_%5Ctext%7Bprev%7D,%20y_%5Ctext%7Bprev%7D%5D%20-%20%20%5Cleft%20%5B%20%5Cfrac%7B%5Cpartial%20f%20(x_%5Ctext%7Bprev%7D,%20y_%5Ctext%7Bprev%7D)%7D%7B%5Cpartial%20x%7D,%20%5Cfrac%7B%5Cpartial%20f%20(x_%5Ctext%7Bprev%7D,%20y_%5Ctext%7Bprev%7D)%7D%7B%5Cpartial%20y%7D%20%5Cright%20%5D%20"></p>
<p>If we iteratively apply this update rule, we’ll end up tracing a trajectory through the <img src="https://latex.codecogs.com/png.latex?(x,y)"> space on the dance floor and we’ll eventually end up at the coolest spot!</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/gd_trajectory.png" class="img-fluid figure-img"></p>
<figcaption>dance floor with trajectory from hot side to cool side</figcaption>
</figure>
</div>
<p>Great success!</p>
</section>
</section>
<section id="general-formulation" class="level2">
<h2 class="anchored" data-anchor-id="general-formulation">General Formulation</h2>
<p>Let’s generalize a bit to get to the form of gradient descent you’ll see in references like <a href="https://en.wikipedia.org/wiki/Gradient_descent">the wikipedia article</a>.</p>
<p>First we modify our update equation above to handle functions with more than two arguments. We’ll use a bold <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D"> to indicate a vector of inputs <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D%20=%20%5Bx_1,x_2,%5Cdots,x_p%5D">. Our function <img src="https://latex.codecogs.com/png.latex?f(%5Cmathbf%7Bx%7D):%20%5Cmathbb%7BR%7D%5Ep%20%5Cmapsto%20%5Cmathbb%7BR%7D"> maps a <img src="https://latex.codecogs.com/png.latex?p"> dimensional input to a scalar output.</p>
<p>Second, instead of displacing our current location with the negative gradient vector itself, we’ll first rescale it with a learning rate parameter. This helps address any issues with units on inputs versus outputs. Imagine the input could range between 0 and 1, but the output ranged from 0 to 1,000. We would need to rescale the partial derivatives so the update step doesn’t send us way too far off in input space.</p>
<p>Finally, we’ll index our updates with <img src="https://latex.codecogs.com/png.latex?t=0,1,%5Cdots">. We’ll run for some prespecified number of iterations or we’ll stop the procedure once the change in <img src="https://latex.codecogs.com/png.latex?f(%5Cmathbf%7Bx%7D)"> is sufficiently small from one iteration to the next. Our update equation will look like this.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D_%7Bt+1%7D%20=%20%5Cmathbf%7Bx%7D_t%20-%20%5Ceta%20%5Cnabla%20f%20(%20%5Cmathbf%7Bx%7D_t)%20"></p>
<p>In pseudocode we could write it like this.</p>
<pre><code># gradient descent
x = initial_value_of_x 
for t in range(n_iterations):  # or some other convergence condition
    x -= learning_rate * gradient_of_f(x)</code></pre>
<p>Now let’s see how this algorithm gets used to train models.</p>
</section>
<section id="training-a-linear-regression-model-with-gradient-descent" class="level2">
<h2 class="anchored" data-anchor-id="training-a-linear-regression-model-with-gradient-descent">Training a Linear Regression Model with Gradient Descent</h2>
<p>To get the intuition for how we use gradient descent to train models, let’s use it to train a linear regression model. Note that we wouldn’t actually use gradient descent to train a linear model in real life since there is an exact <a href="https://en.wikipedia.org/wiki/Ordinary_least_squares">analytical solution</a> for the best-fit parameter values.</p>
<p>Anyway, in the simple linear regression problem we have numerical feature <img src="https://latex.codecogs.com/png.latex?x"> and numerical target <img src="https://latex.codecogs.com/png.latex?y">, and we want to find a model of the form</p>
<p><img src="https://latex.codecogs.com/png.latex?F(x)%20=%20%5Calpha%20+%20%5Cbeta%20x"></p>
<p>This model has two parameters, <img src="https://latex.codecogs.com/png.latex?%5Calpha"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta">. Here “training” means finding the parameter values that make <img src="https://latex.codecogs.com/png.latex?F(x)"> fit our <img src="https://latex.codecogs.com/png.latex?y"> data best. We measure how well, or really how poorly, our model fits the data by using a <em>loss function</em> that yields a small value when a model fits well. Ordinary least squares is so named because it uses mean squared error as its loss function.</p>
<p><img src="https://latex.codecogs.com/png.latex?L(y,%20F(x))%20=%20%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(y_i%20-%20F(x_i))%5E2%20%20=%20%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(y_i%20-%20(%5Calpha%20+%20%5Cbeta%20x_i))%5E2%20"></p>
<p>The loss function <img src="https://latex.codecogs.com/png.latex?L"> takes four arguments: <img src="https://latex.codecogs.com/png.latex?x">, <img src="https://latex.codecogs.com/png.latex?y">, <img src="https://latex.codecogs.com/png.latex?%5Calpha">, and <img src="https://latex.codecogs.com/png.latex?%5Cbeta">. But since <img src="https://latex.codecogs.com/png.latex?x"> and <img src="https://latex.codecogs.com/png.latex?y"> are fixed given our dataset, we could write the loss as <img src="https://latex.codecogs.com/png.latex?L(%5Calpha,%20%5Cbeta%20%7C%20x,%20y)"> to emphasize that <img src="https://latex.codecogs.com/png.latex?%5Calpha"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> are the only free parameters. So we’re looking for the following.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cunderset%7B%5Calpha,%5Cbeta%7D%7B%5Coperatorname%7Bargmin%7D%7D%20~%20L(%5Calpha,%5Cbeta%7Cx,y)%20"></p>
<p>That’s right, we’re looking for the values of <img src="https://latex.codecogs.com/png.latex?%5Calpha"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> that minimize scalar-valued function <img src="https://latex.codecogs.com/png.latex?L(%5Calpha,%20%5Cbeta)">. Sounds familiar huh?</p>
<p>To solve this minimization problem with gradient descent, we can use the following update rule.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5B%5Calpha_%7Bt+1%7D,%20%5Cbeta_%7Bt+1%7D%5D%20=%20%5B%5Calpha_%7Bt%7D,%20%5Cbeta_%7Bt%7D%5D%20-%20%5Ceta%20%5Cnabla%20L(%5Calpha_t,%20%5Cbeta_t%20%7C%20x,%20y)%20"></p>
<p>To get the gradient <img src="https://latex.codecogs.com/png.latex?%5Cnabla%20L(%5Calpha,%5Cbeta%7Cx,y)">, we need the partial derivatives of <img src="https://latex.codecogs.com/png.latex?L"> with respect to <img src="https://latex.codecogs.com/png.latex?%5Calpha"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta">. Since <img src="https://latex.codecogs.com/png.latex?L"> is just a big sum, it’s easy to calculate the derivatives.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Cfrac%7B%5Cpartial%20L(%5Calpha,%20%5Cbeta)%7D%7B%5Cpartial%20%5Calpha%7D%20=%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20-2%20(y_i%20-%20(%5Calpha%20+%20%5Cbeta%20x_i))%20"> <img src="https://latex.codecogs.com/png.latex?%20%5Cfrac%7B%5Cpartial%20L(%5Calpha,%20%5Cbeta)%7D%7B%5Cpartial%20%5Cbeta%7D%20=%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20-2x_i%20(y_i%20-%20(%5Calpha%20+%20%5Cbeta%20x_i))%20"></p>
<p>Great! We’ve got everything we need to implement gradient descent to train an ordinary least squares model. Everything except data that is.</p>
<section id="toy-data" class="level3">
<h3 class="anchored" data-anchor-id="toy-data">Toy Data</h3>
<p>Let’s make a friendly little linear dataset where <img src="https://latex.codecogs.com/png.latex?%5Calpha=-10"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta=2">, i.e.</p>
<p><img src="https://latex.codecogs.com/png.latex?%20y%20=%20-10%20+%202x%20+%20%5Ctext%7Bnoise%7D"></p>
<div id="cell-16" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np </span>
<span id="cb2-2"></span>
<span id="cb2-3">alpha_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb2-4">beta_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-5"></span>
<span id="cb2-6">rng <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.default_rng(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb2-7">x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)</span>
<span id="cb2-8">y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> alpha_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> beta_true<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rng.normal(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x.shape)</span></code></pre></div></div>
</div>
<div id="cell-17" class="cell" data-execution_count="12">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/get-down_files/figure-html/cell-4-output-1.png" class="img-fluid figure-img" alt="Figure showing a scatterplot of x and y data with y increasing linearly in x"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="implementation" class="level3">
<h3 class="anchored" data-anchor-id="implementation">Implementation</h3>
<p>Our implementation will use a function to compute the gradient of the loss function. Since we have two parameters, we’ll use length-2 arrays to hold their values and their partial derivatives. At each iteration, we update the parameter values by subtracting the rescaled partial derivatives.</p>
<div id="cell-20" class="cell" data-scrolled="true" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"></span>
<span id="cb3-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># linear regression using gradient descent </span></span>
<span id="cb3-3"></span>
<span id="cb3-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> gradient_of_loss(parameters, x, y):</span>
<span id="cb3-5">    alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parameters[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb3-6">    beta <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parameters[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb3-7">    partial_alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.mean(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> beta<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>x)))</span>
<span id="cb3-8">    partial_beta <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.mean(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> beta<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>x)))</span>
<span id="cb3-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.array([partial_alpha, partial_beta])</span>
<span id="cb3-10"></span>
<span id="cb3-11">learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.02</span></span>
<span id="cb3-12">parameters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>]) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># initial values of alpha and beta</span></span>
<span id="cb3-13"></span>
<span id="cb3-14"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>):</span>
<span id="cb3-15">    partial_derivatives <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gradient_of_loss(parameters, x, y)</span>
<span id="cb3-16">    parameters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> learning_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> partial_derivatives</span>
<span id="cb3-17">    </span>
<span id="cb3-18">parameters</span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="13">
<pre><code>array([-10.07049616,   2.03559051])</code></pre>
</div>
</div>
<p>We can see the loss function decreasing throughout the 500 iterations.</p>
<div id="cell-23" class="cell" data-scrolled="true" data-execution_count="15">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/get-down_files/figure-html/cell-7-output-1.png" class="img-fluid figure-img" alt="Figure showing the loss function decreasing with each iteration"></p>
</figure>
</div>
</div>
</div>
<p>And we can visualize the loss function as a contour plot over <img src="https://latex.codecogs.com/png.latex?(%5Calpha,%5Cbeta)"> space. The blue points show the trajectory our gradient descent followed as it shimmied from the initial position to the coolest spot in <img src="https://latex.codecogs.com/png.latex?(%5Calpha,%20%5Cbeta)"> space where the loss function is nice and small.</p>
<div id="cell-25" class="cell" data-scrolled="true" data-execution_count="16">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/get-down_files/figure-html/cell-8-output-1.png" class="img-fluid figure-img" alt="Figure showing contour plot of the loss function and a trace moving toward the minimum"></p>
</figure>
</div>
</div>
</div>
<p>Our gradient descent settles in a spot pretty close to <img src="https://latex.codecogs.com/png.latex?(-10,%202)"> in <img src="https://latex.codecogs.com/png.latex?(%5Calpha,%5Cbeta)"> space, which gives us the final fitted model below.</p>
<div id="cell-28" class="cell" data-scrolled="true" data-execution_count="18">
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="https://randomrealizations.com/posts/get-down-with-gradient-descent/get-down_files/figure-html/cell-10-output-1.png" class="img-fluid figure-img" alt="Figure showing the original x and y data along with our fitted line"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="wrapping-up" class="level2">
<h2 class="anchored" data-anchor-id="wrapping-up">Wrapping Up</h2>
<p>There you have it, gradient descent explained with a fresh new analogy having nothing whatsoever to do with foggy mountains, plus an implemented example fitting a linear model. While we often see gradient descent used to train models by performing an optimization in parameter space, as in generalized linear models and neural networks, there are other ways to use this powerful technique to train models. In particular, we’ll soon see how our beloved gradient boosting tree models use gradient descent in <em>prediction space</em>, rather than parameter space. Stay tuned for that mind bender in a future post.</p>


</section>

 ]]></description>
  <category>gradient boosting</category>
  <guid>https://randomrealizations.com/posts/get-down-with-gradient-descent/</guid>
  <pubDate>Fri, 22 Jan 2021 08:00:00 GMT</pubDate>
  <media:content url="https://randomrealizations.com/posts/get-down-with-gradient-descent/thumbnail.png" medium="image" type="image/png" height="108" width="144"/>
</item>
</channel>
</rss>
