<?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>Ray Wang</title>
<link>https://changruiraywang.com/blog/</link>
<atom:link href="https://changruiraywang.com/blog/index.xml" rel="self" type="application/rss+xml"/>
<description>Writing makes an exact man.
</description>
<generator>quarto-1.9.36</generator>
<lastBuildDate>Sun, 16 Aug 2026 04:00:00 GMT</lastBuildDate>
<item>
  <title>Survival Analysis - Part 5 - Tree-based Models</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2026-08-16-survival-trees/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>The methods covered in earlier parts of this series — the Cox Proportional Hazards (CPH) model and the Accelerated Failure Time (AFT) model — are parametric or semi-parametric in nature. They impose structure on how covariates relate to survival time: the Cox model assumes a multiplicative effect on the hazard that remains constant over time; AFT models assume a specific distributional form for the error. When these assumptions hold, these models are efficient and interpretable. When they don’t, estimates can be badly biased and hard to diagnose.</p>
<p>Tree-based methods offer a powerful alternative. They make no assumptions about the functional form of covariate effects and naturally capture non-linearities — at the cost of some interpretability. Ensemble methods like random forests and gradient boosting further stabilize these estimates by aggregating over many trees.</p>
<p>This post covers two tree-based approaches to survival analysis. The first is the Random Survival Forest (RSF), which extends the standard random forest to the survival setting by adapting the splitting criterion and terminal node estimation to handle censored outcomes. The second is XGBoost, which can incorporate the Cox partial likelihood and the AFT likelihood directly into its loss-function-minimizing framework.</p>
</section>
<section id="random-survival-forest-rsf" class="level2">
<h2 class="anchored" data-anchor-id="random-survival-forest-rsf">Random Survival Forest (RSF)</h2>
<p>Like the standard random forest algorithm, RSF grows trees out of bootstrap samples with replacement from the original data. When growing trees, RSF uses the log-rank statistic.</p>
<section id="log-rank-statistic" class="level3">
<h3 class="anchored" data-anchor-id="log-rank-statistic">Log-rank Statistic</h3>
<p>The log-rank statistic is originally used for a non-parametric test for comparing two survival curves. It can be thought of as a series of chi-square tests for group difference done at each observed event time. For example, for the i-th event time, we can put the data in the following contingency table:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Event/Group</th>
<th>1</th>
<th>0</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Event</td>
<td><img src="https://latex.codecogs.com/png.latex?d_%7B1i%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?d_%7B0i%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?d_i"></td>
</tr>
<tr class="even">
<td>No Event</td>
<td><img src="https://latex.codecogs.com/png.latex?n_%7B1i%7D-d_%7B1i%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?n_%7B0i%7D-d_%7B0i%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?n_i-d_i"></td>
</tr>
<tr class="odd">
<td>At Risk</td>
<td><img src="https://latex.codecogs.com/png.latex?n_%7B1i%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?n_%7B0i%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?n_i"></td>
</tr>
</tbody>
</table>
<p>The expected number of event in group 1 (or 0), assuming the survival function is the same in each of the two groups (i.e., the null hypothesis is true), is:</p>
<p><img src="https://latex.codecogs.com/png.latex?E(d_%7B1i%7D)%20=%20e_%7B1i%7D%20=%20n_%7B1i%7D%5Cfrac%7Bd_i%7D%7Bn_i%7D"></p>
<p>The total observed-minus-expected for event in group 1, summed across all event times, is:</p>
<p><img src="https://latex.codecogs.com/png.latex?U%20=%20%5Csum_%7Bi=1%7D%5E%7Bm%7D(d_%7B1i%7D-e_%7B1i%7D)"></p>
<p>The variance of <img src="https://latex.codecogs.com/png.latex?U"> is:</p>
<p><img src="https://latex.codecogs.com/png.latex?V_%7B1i%7D%20=%20%5Cfrac%7Bn_%7B1i%7Dn_%7B0i%7Dd_i(n_i-d_i)%7D%7Bn_i%5E2(n_i-1)%7D"></p>
<p>The log-rank test statistic is:</p>
<p><img src="https://latex.codecogs.com/png.latex?Q%20=%20%5Cfrac%7B%5B%5Csum_%7Bi=1%7D%5E%7Bm%7D(d_%7B1i%7D-e_%7B1i%7D)%5D%5E2%7D%7B%5Csum_%7Bi=1%7D%5E%7Bm%7DV_%7B1i%7D%7D"></p>
<p>The bigger the log-rank statistic is, the more different two survival functions.</p>
<p>With RSF, left leaf and right leaf at the next split are treated as group 1 and group 0 as in the example above. Then RSF chooses the split that results in the largest log-rank statistic.</p>
</section>
<section id="terminal-node-chf-estimation-and-ensemble-averaging" class="level3">
<h3 class="anchored" data-anchor-id="terminal-node-chf-estimation-and-ensemble-averaging">Terminal Node CHF Estimation and Ensemble Averaging</h3>
<p>Once a tree is fully grown, each terminal node receives a Nelson-Aalen estimate of the cumulative hazard function (CHF):</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D(t)%20=%20%5Csum_%7Bt_j%20%5Cleq%20t%7D%20%5Cfrac%7Bd_j%7D%7Bn_j%7D"></p>
<p>One thing worth noting is that some terminal nodes might end up with only a few events as a result of splitting, producing a sparse staircase with just few steps — a coarse and unstable estimate. As a guard against estimating CHF’s from too few event data, the RSF algorithm has a parameter <img src="https://latex.codecogs.com/png.latex?d_0"> (controlled by <code>nodesize</code> in <code>randomForestSRC</code>, default <code>15</code>) that defines the required minimal number of unique events.</p>
<p>Within the same tree, each terminal node’s CHF is a step function defined only at event times within that node. Two nodes will generally have different sets of event times. In other words, each tree generates an estimate for each of the event times. When there are <img src="https://latex.codecogs.com/png.latex?B"> trees, there are B estimates for each of the event times. RSF collects and averages all estimates for each event time.</p>
</section>
<section id="out-of-bag-error" class="level3">
<h3 class="anchored" data-anchor-id="out-of-bag-error">Out-of-Bag Error</h3>
<p>For each tree <img src="https://latex.codecogs.com/png.latex?b">, the OOB subjects (those excluded from the bootstrap sample) are dropped down tree <img src="https://latex.codecogs.com/png.latex?b"> to obtain their terminal-node CHF. The ensemble OOB CHF for subject <img src="https://latex.codecogs.com/png.latex?i"> aggregates predictions from only the trees in which <img src="https://latex.codecogs.com/png.latex?i"> was OOB:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Chat%7BH%7D%5E%7B%5Cmathrm%7BOOB%7D%7D_e(t%20%5Cmid%20%5Cmathbf%7Bx%7D_i)%20=%20%5Cfrac%7B1%7D%7B%7C%5C%7Bb%20:%20i%0A%20%20%5Cin%20%5Cmathrm%7BOOB%7D_b%5C%7D%7C%7D%20%5Csum_%7Bb:%5C,i%20%5Cin%20%5Cmathrm%7BOOB%7D_b%7D%0A%20%20%5Chat%7BH%7D%5Eb_%7B%5Cmathrm%7Bnode%7D(%5Cmathbf%7Bx%7D_i,%5C,b)%7D(t)%0A"></p>
<p>This provides an honest estimate of prediction error without requiring a held-out test set, analogous to cross-validation but at zero additional computational cost since the OOB sample is a by-product of bootstrap sampling.</p>
<p>The OOB prediction error is measured by Harrell’s C-index or the integrated Brier score, both evaluated on the OOB ensemble CHF.</p>
</section>
<section id="how-rsf-makes-predictions" class="level3">
<h3 class="anchored" data-anchor-id="how-rsf-makes-predictions">How RSF Makes Predictions</h3>
<p>When making predictions for a new patient, RSF follows these steps:</p>
<ol type="1">
<li>Drop the new case down every tree — it follows the split rules at each node until it lands in a terminal node. Each terminal node contains a cumulative hazard function for the cases that fell into it.</li>
<li>Retrieve that node’s cumulative hazard function <img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D_b(t)"> from tree <img src="https://latex.codecogs.com/png.latex?b"></li>
<li>Average across all <img src="https://latex.codecogs.com/png.latex?B"> trees to get the ensemble cumulative hazard: <img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D(t)%20=%20%5Cfrac%7B1%7D%7BB%7D%20%5Csum_%7Bb=1%7D%5E%7BB%7D%20%5Chat%7BH%7D_b(t)"></li>
</ol>
<p>The ensemble survival function is recovered as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7BS%7D(t%20%5Cmid%20%5Cmathbf%7Bx%7D)%20=%20%5Cexp%5C!%5Cleft(-%5Chat%7BH%7D(t%20%5Cmid%5Cmathbf%7Bx%7D)%5Cright)"></p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Worked example: predicting survival for a new patient
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p><strong>Training data (simplified)</strong></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>ID</th>
<th>Age</th>
<th>Comorbidity Score</th>
<th>Time</th>
<th>Event</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>65</td>
<td>3</td>
<td>12</td>
<td>1</td>
</tr>
<tr class="even">
<td>2</td>
<td>72</td>
<td>7</td>
<td>8</td>
<td>1</td>
</tr>
<tr class="odd">
<td>3</td>
<td>58</td>
<td>2</td>
<td>24</td>
<td>0 (censored)</td>
</tr>
<tr class="even">
<td>4</td>
<td>80</td>
<td>9</td>
<td>5</td>
<td>1</td>
</tr>
<tr class="odd">
<td>5</td>
<td>61</td>
<td>4</td>
<td>18</td>
<td>1</td>
</tr>
</tbody>
</table>
<p><strong>New patient: Age = 70, Comorbidity = 6</strong></p>
<p>After growing 3 trees on bootstrap samples, the new patient lands in a terminal node in each:</p>
<ul>
<li><strong>Tree 1</strong> → node containing IDs {2, 4} — events at <img src="https://latex.codecogs.com/png.latex?t%20=%205,%208"></li>
<li><strong>Tree 2</strong> → node containing IDs {1, 2} — events at <img src="https://latex.codecogs.com/png.latex?t%20=%208,%2012"></li>
<li><strong>Tree 3</strong> → node containing IDs {2, 4, 5} — events at <img src="https://latex.codecogs.com/png.latex?t%20=%205,%208,%2018"></li>
</ul>
<p><strong>Nelson-Aalen estimate for each node</strong></p>
<p>Tree 1 node {2, 4}:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?t"></th>
<th><img src="https://latex.codecogs.com/png.latex?d_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?n_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?d_i%20/%20n_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D(t)"></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>5</td>
<td>1</td>
<td>2</td>
<td>0.500</td>
<td>0.500</td>
</tr>
<tr class="even">
<td>8</td>
<td>1</td>
<td>1</td>
<td>1.000</td>
<td>1.500</td>
</tr>
</tbody>
</table>
<p>Tree 2 node {1, 2}:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?t"></th>
<th><img src="https://latex.codecogs.com/png.latex?d_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?n_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?d_i%20/%20n_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D(t)"></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>8</td>
<td>1</td>
<td>2</td>
<td>0.500</td>
<td>0.500</td>
</tr>
<tr class="even">
<td>12</td>
<td>1</td>
<td>1</td>
<td>1.000</td>
<td>1.500</td>
</tr>
</tbody>
</table>
<p>Tree 3 node {2, 4, 5}:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?t"></th>
<th><img src="https://latex.codecogs.com/png.latex?d_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?n_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?d_i%20/%20n_i"></th>
<th><img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D(t)"></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>5</td>
<td>1</td>
<td>3</td>
<td>0.333</td>
<td>0.333</td>
</tr>
<tr class="even">
<td>8</td>
<td>1</td>
<td>2</td>
<td>0.500</td>
<td>0.833</td>
</tr>
<tr class="odd">
<td>18</td>
<td>1</td>
<td>1</td>
<td>1.000</td>
<td>1.833</td>
</tr>
</tbody>
</table>
<p><strong>Average pointwise across trees</strong> (carrying forward when no jump at that time):</p>
<table class="caption-top table">
<colgroup>
<col style="width: 5%">
<col style="width: 9%">
<col style="width: 9%">
<col style="width: 9%">
<col style="width: 26%">
<col style="width: 39%">
</colgroup>
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?t"></th>
<th>Tree 1</th>
<th>Tree 2</th>
<th>Tree 3</th>
<th>Ensemble <img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D(t)"></th>
<th><img src="https://latex.codecogs.com/png.latex?%5Chat%7BS%7D(t)%20=%20e%5E%7B-%5Chat%7BH%7D(t)%7D"></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>5</td>
<td>0.500</td>
<td>0.000</td>
<td>0.333</td>
<td>0.278</td>
<td>0.757</td>
</tr>
<tr class="even">
<td>8</td>
<td>1.500</td>
<td>0.500</td>
<td>0.833</td>
<td>0.944</td>
<td>0.389</td>
</tr>
<tr class="odd">
<td>12</td>
<td>1.500</td>
<td>1.500</td>
<td>0.833</td>
<td>1.278</td>
<td>0.279</td>
</tr>
<tr class="even">
<td>18</td>
<td>1.500</td>
<td>1.500</td>
<td>1.833</td>
<td>1.611</td>
<td>0.200</td>
</tr>
</tbody>
</table>
<p>This patient has an estimated survival probability of ~76% at month 5, falling to ~39% by month 8 and ~20% by month 18.</p>
</div>
</div>
</div>
<p>For more information on RSF, check the official <a href="https://www.randomforestsrc.org/articles/survival.html">R Vignette</a></p>
</section>
</section>
<section id="xgboost" class="level2">
<h2 class="anchored" data-anchor-id="xgboost">XGBoost</h2>
<p>The standard XGBoost tree method can be applied to both Cox PH (CPH) model and Accelerated Failure Time (AFT) model. The power of XGBoost method lies in the fact that the general framework does not change. All we need to do is find the proper loss function.</p>
<p>The standard loss function of the XGBoost tree per the <a href="https://arxiv.org/abs/1603.02754">Xgboost paper</a> is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell%5E%7B(t)%7D%20=%20%5Csum%5E%7Bn%7D_%7Bi=1%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_t(x_i))+%5Cdfrac%7B1%7D%7B2%7D%5Clambda%5Csum%5EJ_%7Bj=1%7Df%5E2_j(x)+%5Cgamma%20T"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cell"> is the loss function, <img src="https://latex.codecogs.com/png.latex?f_j(x)"> is the prediction for leaf j and <img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7B1%7D%7B2%7D%5Clambda%5Csum%5EJ_%7Bj=1%7Df%5E2_j(x)"> is the L2 regularization term.</p>
<p>With second-degree Taylor expansion of the first summation term, we get the loss function:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell%5E%7B(t)%7D%20=%20%5Csum%5E%7Bn%7D_%7Bi=1%7D%5B%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D)%20+%20g_i%20f_t(x_i)%20+%20%5Cdfrac%7B1%7D%7B2%7Dh_i%20f%5E2_t(x_i)%5D+%5Cdfrac%7B1%7D%7B2%7D%5Clambda%5Csum%5EJ_%7Bj=1%7Df%5E2_j(x)+%5Cgamma%20T"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?g_i%20=%20%5Cdfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7D"> is the gradient of the loss function with respect to the current prediction and <img src="https://latex.codecogs.com/png.latex?h_i%20=%20%5Cdfrac%7B%5Cpartial%5E2%20%5Cell%7D%7B%5Cpartial%20(%5Chat%7By%7D_i%5E%7B(t-1)%7D)%5E2%7D"> is the hessian of the loss function with respect to the current prediction.</p>
<p>The optimal output for leaf <img src="https://latex.codecogs.com/png.latex?j"> is:</p>
<p><img src="https://latex.codecogs.com/png.latex?f_j%5E*(x)%20=%20-%5Cdfrac%7B%5Csum_%7Bi%5Cin%20j%7Dg_i%7D%7B%5Csum_%7Bi%5Cin%20j%7Dh_i+%5Clambda%7D"></p>
<p>The splitting rule is the same as the standard setting: <img src="https://latex.codecogs.com/png.latex?%0AGain%20=%20%5Cdfrac%7B1%7D%7B2%7D%5Cleft%5B%5Cdfrac%7B(%5Csum_%7Bi%5Cin%20j_L%7Dg_i)%5E2%7D%7B%5Csum_%7Bi%5Cin%20j_L%7Dh_i+%5Clambda%7D+%5Cdfrac%7B(%5Csum_%7Bi%5Cin%20j_R%7Dg_i)%5E2%7D%7B%5Csum_%7Bi%5Cin%20j_R%7Dh_i+%5Clambda%7D-%5Cdfrac%7B(%5Csum_%7Bi%5Cin%20j%7Dg_i)%5E2%7D%7B%5Csum_%7Bi%5Cin%20j%7Dh_i+%5Clambda%7D%5Cright%5D%20-%20%5Cgamma%0A"></p>
<p>Therefore, all we need to do is to get the corresponding gradients <img src="https://latex.codecogs.com/png.latex?g_i"> and Hessians <img src="https://latex.codecogs.com/png.latex?h_i"> for the CPH model and AFT model.</p>
<section id="cox-proportional-hazards-model" class="level3">
<h3 class="anchored" data-anchor-id="cox-proportional-hazards-model">Cox Proportional Hazards Model</h3>
<p>With the CPH model, the linear combination of covariates - <img src="https://latex.codecogs.com/png.latex?%5Ceta=%5Cbeta_1X_1+%5Cbeta_2X_2+...+%5Cbeta_pX_p"> represents the log hazard ratio. Each leaf output represents an increment from the current ensemble’s log hazard ratio for any subject landing in that leaf.</p>
<p>The loss function of the CPH model is built upon the partial likelihood: <img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BPartial%20Likelihood%7D%20=%20%5Cprod%5Climits_%7B%5Ctext%7Bobserved%20event%20time%7D%7D%5Cfrac%7B%5Cexp(%5Ceta_%7Bi%7D)%7D%7B%5Cdisplaystyle%5Csum_%7B%5Cmathcal%7BR%7D(t_j)%7D%20%5Cexp(%5Ceta_%7Bi%7D)%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Ceta_%7Bij%7D=%5Cbeta_1X_%7B1i%7D+%5Cbeta_2X_%7B2i%7D+...+%5Cbeta_pX_%7Bpi%7D"> is the linear combination of covariates for subject i;</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BR%7D(t_j)"> is the risk set at time j.</p>
<p>XGBoost’s loss function is the negative partial log-likelihood:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell%20=%20-%20%5Csum_%7B%5Ctext%7Bobserved%20events%7D%7D%5Cleft%5B%5Ceta_%7Bi%7D%20-%20%5Clog%5Csum_%7B%5Cmathcal%7BR%7D(t_j)%7D%5Cexp(%5Ceta_%7Bi%7D)%5Cright%5D"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Ceta_%7Bi%7D"> represents the linear combination of covariates for subject i .</p>
<p>The <strong>gradient</strong> for subject i is:</p>
<p><img src="https://latex.codecogs.com/png.latex?g_i%20=%20%5Cfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Ceta_i%7D%20=%20-%5Cdelta_i%20+%20%5Csum_%7B%5Cmathcal%7BR%7D(t_j)%7D%20w_i(t_j)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cdelta_i"> is 1 if i had the event, 0 if censored;</p>
<p><img src="https://latex.codecogs.com/png.latex?w_%7Bi%7D(t_j)%20=%20%5Cfrac%7Be%5E%7B%5Ceta_%7Bi%7D%7D%7D%7B%5Csum_%7Bk%20%5Cin%20%5Cmathcal%7BR%7D(t_j)%7D%20e%5E%7B%5Ceta_%7Bk%7D%7D%7D"></p>
<p>The <strong>hessian</strong> for subject i is: <img src="https://latex.codecogs.com/png.latex?%0Ah_i%20=%20%5Cfrac%7B%5Cpartial%5E2%20%5Cell%7D%7B%5Cpartial%20%5Ceta_i%5E2%7D%20=%20%5Csum_%7Bk%20%5Cin%20%5Cmathcal%7BR%7D(t_j)%7D%20w_i(t_j)%5Cbigl(1%20-%20w_i(t_j)%5Cbigr)%0A"></p>
<div class="callout callout-style-default callout-note callout-titled" title="Gradient and Hessian Derivation">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Gradient and Hessian Derivation
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>Expanding the brackets, we write the equation above as two terms:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell%20=%20%5Cunderbrace%7B-%5Csum_%7B%5Ctext%7Bobserved%20events%7D%7D%20%5Ceta_%7Bi%7D%7D_%7B%5Ctext%7BTerm%20A%7D%7D+%20%5Cunderbrace%7B%5Csum_%7B%5Ctext%7Bobserved%20events%7D%7D%5Clog%5Csum_%7B%5Cmathcal%7BR%7D(t_i)%7D%5Cexp(%5Ceta_%7Bi%7D)%7D_%7B%5Ctext%7BTerm%20B%7D%7D"></p>
<p>Differentiating Term A with respect to <img src="https://latex.codecogs.com/png.latex?%5Ceta_i"> is straightforward:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20%5Ceta_%7Bi%7D%7D%5Cleft%5B-%5Csum_%7B%5Ctext%7Bobserved%20events%7D%7D%20%5Ceta_%7Bi%7D%5Cright%5D%20=%5Cdelta_i"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cdelta_i=1"> if event, 0 otherwise.</p>
<p>Differentiating Term B with respect to <img src="https://latex.codecogs.com/png.latex?%5Ceta_i"> requires chain rule:</p>
<p>For a single event time <img src="https://latex.codecogs.com/png.latex?t_i">, define:</p>
<p><img src="https://latex.codecogs.com/png.latex?S_i%20=%20%5Csum_%7B%5Cmathcal%7BR%7D(t_j)%7D%5Cexp(%5Ceta_%7Bi%7D)"></p>
<p>Then we have:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20%5Ceta_%7Bi%7D%7D%5Clog%20S_i%20%20=%20%5Cfrac%7B%5Cpartial%20%5Clog%20S_i%7D%7B%5Cpartial%20S_i%7D%5Ccdot%5Cfrac%7B%5Cpartial%20S_i%7D%7B%5Cpartial%20%5Ceta_%7Bi%7D%7D%0A=%5Cfrac%7B1%7D%7BS_i%7D%5Ccdot%20exp(%5Ceta_%7Bi%7D)%0A=%5Cfrac%7Bexp(%5Ceta_%7Bi%7D)%7D%7B%5Csum_%7B%5Cmathcal%7BR%7D(t_i)%7D%5Cexp(%5Ceta_%7Bi%7D)%7D%0A"></p>
<p>We now sum over all event times:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Cpartial%5C,%5Ctext%7BTerm%20B%7D%7D%7B%5Cpartial%20%5Ceta_%7Bi%7D%7D%20=%20%5Csum_%7B%5Ctext%7Bevent%20times%7D%7D%20%5Cfrac%7Bexp(%5Ceta_%7Bi%7D)%7D%7B%5Csum_%7B%5Cmathcal%7BR%7D(t_j)%7D%5Cexp(%5Ceta_%7Bi%7D)%7D%0A"></p>
<p>Adding Term A and Term B and we get the gradient <img src="https://latex.codecogs.com/png.latex?g_i">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Ag_i%20=%20-%5Cdelta_i%20+%5Csum_%7B%5Ctext%7Bevent%20times%7D%7D%20w_%7Bi%7D(t_j)%0A"></p>
<p>For Hessian <img src="https://latex.codecogs.com/png.latex?h_i">, we take the derivative with respect to <img src="https://latex.codecogs.com/png.latex?%5Ceta_%7Bi%7D"> again:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Ah_i%20=%20%5Cfrac%7B%5Cpartial%20%5Cfrac%7Bexp(%5Ceta_%7Bi%7D)%7D%7B%5Csum_%7B%5Cmathcal%7BR%7D(t_j)%7D%5Cexp(%5Ceta_%7Bi%7D)%7D%7D%7B%5Cpartial%20%5Ceta_i%7D%0A"></p>
<p>We can proceed to get the result with the quotient rule.</p>
</div>
</div>
</div>
<section id="how-xgboost-cph-model-makes-predictions" class="level4">
<h4 class="anchored" data-anchor-id="how-xgboost-cph-model-makes-predictions">How XGBoost CPH Model Makes Predictions</h4>
<p>The gradient and Hessian of XGBoost CPH model are derived by taking the derivative of the log-likelihood with respect to <img src="https://latex.codecogs.com/png.latex?%5Ceta_i">. Therefore, the output of XGBoost CPH model the log relative hazard ratio.</p>
<p>The process of making predictions with the XGBoost CPH model involves the following steps:</p>
<ol type="1">
<li>Run XGBoost to get <img src="https://latex.codecogs.com/png.latex?%5Chat%7Bf%7D(x_i)"> for all training observations</li>
<li>Use the Breslow estimator on the training data with those risk scores to estimate <img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D_0(t)"></li>
<li>Repeat steps 1-4 for any new observations: 3.1 Drop a new observation - <img src="https://latex.codecogs.com/png.latex?x_%5Ctext%7Bnew%7D"> through all <img src="https://latex.codecogs.com/png.latex?B"> trees; sum the leaf values → <img src="https://latex.codecogs.com/png.latex?%5Chat%7Bf%7D(x_%5Ctext%7Bnew%7D)"> 3.2 Exponentiate to get the hazard ratio: <img src="https://latex.codecogs.com/png.latex?e%5E%7B%5Chat%7Bf%7D(x_%5Ctext%7Bnew%7D)%7D"> 3.3 Multiply the precomputed Breslow baseline: <img src="https://latex.codecogs.com/png.latex?%5Chat%7BH%7D(t%20%5Cmid%20x_%5Ctext%7Bnew%7D)%20=%20%5Chat%7BH%7D_0(t)%20%5Ccdot%20e%5E%7B%5Chat%7Bf%7D(x_%5Ctext%7Bnew%7D)%7D"> 3.4 Survival probability: <img src="https://latex.codecogs.com/png.latex?%5Chat%7BS%7D(t)%20=%20e%5E%7B-%5Chat%7BH%7D(t%20%5Cmid%20x_%5Ctext%7Bnew%7D)%7D"></li>
</ol>
</section>
</section>
<section id="accelerated-failure-time-aft-model" class="level3">
<h3 class="anchored" data-anchor-id="accelerated-failure-time-aft-model">Accelerated Failure Time (AFT) Model</h3>
<p>Since the full distribution of event times is being modeled with AFT models, we are able to construct the full likelihood of the dataset given a distribution like the typical maximum likelihood estimation procedure. For observed event times, the PDF of the distribution is used; For censored cases, the survival function is used instead. The likelihood for a parametric survival model is:</p>
<p><img src="https://latex.codecogs.com/png.latex?L%20=%20%5Cprod%5En_%7Bi:%20uncensored%7Df(t_i)%5Ccdot%5Cprod%5En_%7Bi:censored%7DS(t_i)"></p>
<p>Taking logarithm, we get:</p>
<p><img src="https://latex.codecogs.com/png.latex?log(L)%20=%20%5Csum%5En_%7Bi:uncensored%7Dlogf(t_i)+%5Csum%5En_%7Bi:censored%7DlogS(t_i)"></p>
<p>Since <img src="https://latex.codecogs.com/png.latex?%5Clambda(t)=%5Cfrac%7Bf(t)%7D%7BS(t)%7D"></p>
<p>The equation above can be written as: <img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5Clog(L)%20&amp;=%20%5Csum%5En_%7Bi:%5Ctext%7Buncensored%7D%7D%5Clog%5Clambda(t_i)+%5Csum%5En_%7Bi:%5Ctext%7Buncensored%7D%7D%5Clog%20S(t_i)+%5Csum%5En_%7Bi:%5Ctext%7Bcensored%7D%7D%5Clog%20S(t_i)%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Csum%5En_%7Bi:%5Ctext%7Buncensored%7D%7D%5Clog%5Clambda(t_i)+%5Csum_i%5En%20%5Clog%20S(t_i)%20%5C%5C%0A%20%20%20%20%20%20%20%20&amp;=%20%5Csum%5En_%7Bi:%5Ctext%7Buncensored%7D%7D%5Clog%5Clambda(t_i)-%5Csum_i%5En%20%5CLambda(t_i)%0A%5Cend%7Balign*%7D%0A"></p>
<p>The equation has two parts per subject: the instantaneous hazard at the event time <img src="https://latex.codecogs.com/png.latex?%5Clambda(t_i)"> - this term is 0 when the subject is censored, and the cumulative hazard up to their observed time <img src="https://latex.codecogs.com/png.latex?%5CLambda(t_i)">.</p>
<p>The <strong>gradient</strong> and <strong>hessian</strong> for subject i, depending on their censoring status, is summarized in the following table:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 15%">
<col style="width: 40%">
<col style="width: 45%">
</colgroup>
<thead>
<tr class="header">
<th></th>
<th>Gradient <img src="https://latex.codecogs.com/png.latex?g_i"></th>
<th>Hessian <img src="https://latex.codecogs.com/png.latex?h_i"></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Right-censored</strong></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7B%5Cphi(z_i)%7D%7B%5Csigma%5C,%5Cbar%5CPhi(z_i)%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7B%5Cphi(z_i)%7D%7B%5Csigma%5E2%7D%5C!%5Cleft%5B%5Cdfrac%7B-z_i%7D%7B%5Cbar%5CPhi(z_i)%7D+%5Cdfrac%7B%5Cphi(z_i)%7D%7B%5Cbar%5CPhi(z_i)%5E2%7D%5Cright%5D"></td>
</tr>
<tr class="even">
<td><strong>Event</strong></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7Bf_Z'(z_i)%7D%7B%5Csigma%20f_Z(z_i)%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7Bf_Z'(z_i)%5E2%20-%20f_Z(z_i)%5C,f_Z''(z_i)%7D%7B%5Csigma%5E2%20f_Z(z_i)%5E2%7D"></td>
</tr>
</tbody>
</table>
<p>where <img src="https://latex.codecogs.com/png.latex?z_i%20=%20%5Cfrac%7B%5Clog%20t_i%20-%20F(x_i)%7D%7B%5Csigma%7D">, and <img src="https://latex.codecogs.com/png.latex?%5CPhi"> is the CDF of the error distribution specified for the AFT model.</p>
<div class="callout callout-style-default callout-note callout-titled" title="Gradient and Hessian Derivation">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Gradient and Hessian Derivation
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>With the AFT model, the log-time is being modeled as the response of a linear regression:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Clog%20t_i%20=%20F(x_i)%20+%20%5Csigma%20%5Cvarepsilon_i,%20%5Cqquad%20%5Cvarepsilon_i%20%5Csim%20f_Z"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?F(x_i)"> is the linear predictor <img src="https://latex.codecogs.com/png.latex?%5Cbeta%5E%5Ctop%20x">, <img src="https://latex.codecogs.com/png.latex?f_Z"> is the error distribution (normal, logistic, or Extreme); <img src="https://latex.codecogs.com/png.latex?%5Csigma"> is a fixed scale parameter.</p>
<p>XGBoost minimizes the negative log likelihood.</p>
<p>Let <img src="https://latex.codecogs.com/png.latex?z_i%20=%20%5Cfrac%7B%5Clog%20t_i%20-%20F(x_i)%7D%7B%5Csigma%7D">, and <img src="https://latex.codecogs.com/png.latex?%5CPhi"> is the CDF of the error distribution, we can get the gradients and hessian for censored and uncensored subjects respectively:</p>
<p>For <strong>Right-censored subjects</strong>, the individual loss function is :</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell_i%20=%20-%20log(l_i)%20=%20%5CLambda(t_i)%20=%20logS(t_i)%20=%20log(1-%5CPhi(z_i))"></p>
<p>By the chain rule, the gradient is:</p>
<p><img src="https://latex.codecogs.com/png.latex?g_i%20=%20%5Cfrac%7B%5Cpartial%20%5Cell_i%7D%7B%5Cpartial%20F(x_i)%7D%20=%5Cfrac%7B%5Cpartial%20%5Cell_i%7D%7B%5Cpartial%20%5CPhi(z_i)%7D%20%5Ccdot%20%5Cfrac%7B%5Cpartial%20%5CPhi(z_i)%7D%7B%5Cpartial%20z_i%7D%5Ccdot%20%5Cfrac%7B%5Cpartial%20z_i%7D%7B%5Cpartial%20F(x_i)%7D"></p>
<p>Term by term, we have:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20%5Cell_i%7D%7B%5Cpartial%20%5CPhi(z_i)%7D=-%5Cfrac%7B1%7D%7B1-%5CPhi(z_i)%7D"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20%5CPhi(z_i)%7D%7B%5Cpartial%20z_i%7D%20=%20%5Cphi(z_i)"> where <img src="https://latex.codecogs.com/png.latex?%5Cphi(z_i)"> is the pdf of the error distribution.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20z_i%7D%7B%5Cpartial%20F(x_i)%7D=%5Cfrac%7B%5Cpartial%20%5Cfrac%7B%5Clog%20t_i%20-%20F(x_i)%7D%7B%5Csigma%7D%7D%7B%5Cpartial%20F(x_i)%7D%20=%20-%5Cfrac%7B1%7D%7B%5Csigma%7D"></p>
<p>That is:</p>
<p><img src="https://latex.codecogs.com/png.latex?g_i%20=%20%5Cfrac%7B%5Cphi(z_i)%7D%7B%5Csigma(1-%5CPhi(z_i))%7D"></p>
<p>For Hessian, differentiating <img src="https://latex.codecogs.com/png.latex?g_i"> using the quotient rule and <img src="https://latex.codecogs.com/png.latex?%5Cphi'(z)%20=%20-z%5Cphi(z)">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Cpartial%20g_i%7D%7B%5Cpartial%20z_i%7D%20=%20-%5Cfrac%7B1%7D%7B%5Csigma%7D%20%5Ccdot%0A%5Cfrac%7B-z_i%5Cphi(z_i)%5Cbar%5CPhi(z_i)%20+%20%5Cphi(z_i)%5E2%7D%7B%5Cbar%5CPhi(z_i)%5E2%7D%20=%0A%5Cfrac%7B%5Cphi(z_i)%7D%7B%5Csigma%7D%5Cleft%5B%5Cfrac%7Bz_i%7D%7B%5Cbar%5CPhi(z_i)%7D%20-%0A%5Cfrac%7B%5Cphi(z_i)%7D%7B%5Cbar%5CPhi(z_i)%5E2%7D%5Cright%5D%0A"></p>
<p>Multiplying by <img src="https://latex.codecogs.com/png.latex?%5Cpartial%20z_i/%5Cpartial%20F(x_i)%20=%20-1/%5Csigma">:</p>
<p><img src="https://latex.codecogs.com/png.latex?h_i%20=%20%5Cfrac%7B%5Cphi(z_i)%7D%7B%5Csigma%5E2%7D%5Cleft%5B%5Cfrac%7B-z_i%7D%7B%5Cbar%5CPhi(z_i)%7D%20+%5Cfrac%7B%5Cphi(z_i)%7D%7B%5Cbar%5CPhi(z_i)%5E2%7D%5Cright%5D"></p>
<p>For <strong>Uncensored subjects</strong>, the loss is <img src="https://latex.codecogs.com/png.latex?%5Cell_i%20=%20-%20log(l_i)%20=%20-%5Clog%20%5Clambda(t_i)%20+%20%5CLambda(t_i)%20=%20-%5Clog%20%5Cfrac%7Bf(t_i)%7D%7BS(t_i)%7D%20-%20logS(t_i)%20=%20-logf(t_i)"></p>
<p>Like the censored cases, we want to get <img src="https://latex.codecogs.com/png.latex?z_i"> in the equation through some relationship.</p>
<p>Since <img src="https://latex.codecogs.com/png.latex?z_i%20=%20%5Cfrac%7B%5Clog%20t_i%20-%20F(x_i)%7D%7B%5Csigma%7D">, through variable transformation, we have:</p>
<p><img src="https://latex.codecogs.com/png.latex?f_T(t)%20=%20f_Z(z)%5Cfrac%7Bdz%7D%7Bdt%7D"></p>
<p>which gives:</p>
<p><img src="https://latex.codecogs.com/png.latex?f_T(t)%20=%20f_Z(z)%5Cfrac%7Bdz%7D%7Bdt%7D%20=%20f_Z(z)%5Cdfrac%7B1%7D%7B%5Csigma%20t_i%7D"></p>
<p>Now the individual loss becomes: <img src="https://latex.codecogs.com/png.latex?%5Cell_i%20=%20-logf(t_i)%20=-logf_Z(z)+log%5Csigma%20+log%20t_i"></p>
<p>With chain rule, we get:</p>
<p><img src="https://latex.codecogs.com/png.latex?g_i%20=%20%5Cfrac%7B%5Cpartial%20%5Cell_i%7D%7B%5Cpartial%20F(x_i)%7D%0A=%20%5Cfrac%7B%5Cpartial%20-logf_Z(z_i)+log%5Csigma%20+log%20t_i%7D%7B%5Cpartial%20%5C,%20f(z_i)%7D%20%5Ccdot%20%5Cfrac%7B%5Cpartial%5C,%20f(z_i)%7D%7B%5Cpartial%20z_i%7D%5Ccdot%5Cfrac%7B%5Cpartial%20z_i%7D%7B%5Cpartial%20F(x_i)%7D%0A=%20%5Cfrac%7Bf'_Z(z_i)%7D%7B%5Csigma%20f_Z(z_i)%7D%0A"></p>
<p>For <strong>Hessian</strong>, differentiating <img src="https://latex.codecogs.com/png.latex?g_i%20=%20f_Z'(z_i)/%5B%5Csigma%20f_Z(z_i)%5D"> via the chain rule and quotient rule:</p>
<p><img src="https://latex.codecogs.com/png.latex?h_i%20=%20%5Cfrac%7B%5Cpartial%20g_i%7D%7B%5Cpartial%20F(x_i)%7D=%5Cfrac%7B%5Cpartial%20g_i%7D%7Bz_i%7D%5Ccdot%5Cfrac%7B%5Cpartial%20z_i%7D%7B%5Cpartial%20F(x_i)%7D%0A=%20%5Cfrac%7Bf_Z'(z_i)%5E2%20-%20f_Z(z_i)%5C,f_Z''(z_i)%7D%7B%5Csigma%5E2%5C,%20f_Z(z_i)%5E2%7D%0A"></p>
</div>
</div>
</div>
<section id="how-xgboost-aft-model-makes-predictions" class="level4">
<h4 class="anchored" data-anchor-id="how-xgboost-aft-model-makes-predictions">How XGBoost AFT Model Makes Predictions</h4>
<p>The XGBoost AFT model predicts <img src="https://latex.codecogs.com/png.latex?%5Chat%7Bf%7D(x)%20=%20%5Cmathbb%7BE%7D%5B%5Clog%20T%20%5Cmid%20x%5D"> — the expected log event time. For the AFT model, XGBoost follows these steps to make predictions for a new observation:</p>
<ol type="1">
<li>Drop <img src="https://latex.codecogs.com/png.latex?x_%5Ctext%7Bnew%7D"> through all <img src="https://latex.codecogs.com/png.latex?B"> trees; sum the leaf values → <img src="https://latex.codecogs.com/png.latex?%5Chat%7Bf%7D(x_%5Ctext%7Bnew%7D)"></li>
<li>Evaluate <img src="https://latex.codecogs.com/png.latex?%5Chat%7BS%7D(t)%20=%201%20-%20F_%5Cepsilon%5C!%5Cleft(%5Cfrac%7B%5Clog%20t%20-%20%5Chat%7Bf%7D(x_%5Ctext%7Bnew%7D)%7D%7B%5Csigma%7D%5Cright)"> using the chosen distribution’s CDF</li>
</ol>
</section>
</section>
</section>
<section id="python-package-parameters-reference" class="level2">
<h2 class="anchored" data-anchor-id="python-package-parameters-reference">Python Package Parameters Reference</h2>
<p>In Python, the random survival forest algorithm is implemented through RandomSurvivalForest of the sksurv package (<code>sksurv.ensemble</code>). The standard xgb function from the xgboost package can be used to implement the CPH and AFT model with their parameters set up accordingly.</p>
<section id="random-survival-forest" class="level3">
<h3 class="anchored" data-anchor-id="random-survival-forest">Random Survival Forest</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 22%">
<col style="width: 15%">
<col style="width: 63%">
</colgroup>
<thead>
<tr class="header">
<th>Parameter</th>
<th>Default</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>n_estimators</code></td>
<td><code>100</code></td>
<td>Number of trees <img src="https://latex.codecogs.com/png.latex?B"></td>
</tr>
<tr class="even">
<td><code>min_samples_leaf</code></td>
<td><code>15</code></td>
<td>Minimum number of unique deaths per terminal node; analogous to <code>nodesize</code> in R</td>
</tr>
<tr class="odd">
<td><code>max_features</code></td>
<td><code>"sqrt"</code></td>
<td>Features considered at each split; analogous to <code>mtry</code>. Accepts <code>"sqrt"</code>, <code>"log2"</code>, int, or float</td>
</tr>
<tr class="even">
<td><code>n_jobs</code></td>
<td><code>1</code></td>
<td>Parallel jobs for fitting and prediction; <code>-1</code> uses all cores</td>
</tr>
<tr class="odd">
<td><code>oob_score</code></td>
<td><code>False</code></td>
<td>Whether to compute OOB Harrell’s C-index after fitting; accessible via <code>oob_score_</code></td>
</tr>
<tr class="even">
<td><code>random_state</code></td>
<td><code>None</code></td>
<td>Random seed for reproducibility</td>
</tr>
<tr class="odd">
<td><code>max_depth</code></td>
<td><code>None</code></td>
<td>Maximum tree depth; <code>None</code> = grow until <code>min_samples_leaf</code> is reached</td>
</tr>
<tr class="even">
<td><code>min_samples_split</code></td>
<td><code>6</code></td>
<td>Minimum samples required to split an internal node</td>
</tr>
<tr class="odd">
<td><code>max_leaf_nodes</code></td>
<td><code>None</code></td>
<td>Maximum number of terminal nodes; <code>None</code> = unlimited</td>
</tr>
</tbody>
</table>
<p><strong>Label format</strong>: <code>y</code> must be a structured array with fields <code>(event: bool, time: float)</code>. Predictions are accessed via:</p>
<ul>
<li><code>rsf.predict(X)</code> — returns risk scores (expected number of events)</li>
<li><code>rsf.predict_cumulative_hazard_function(X)</code> — returns per-subject CHF step functions</li>
<li><code>rsf.predict_survival_function(X)</code> — returns per-subject survival function step functions</li>
</ul>
</section>
<section id="xgboost-with-cox-proportional-hazards" class="level3">
<h3 class="anchored" data-anchor-id="xgboost-with-cox-proportional-hazards">XGBoost with Cox Proportional Hazards</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Parameter</th>
<th>Value</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>objective</code></td>
<td><code>"survival:cox"</code></td>
<td></td>
</tr>
<tr class="even">
<td><code>eval_metric</code></td>
<td><code>"cox-nloglik"</code></td>
<td>Negative partial log-likelihood</td>
</tr>
<tr class="odd">
<td><strong>Label format</strong></td>
<td>Positive = event time; Negative = censored time</td>
<td>e.g.&nbsp;<code>-5.3</code> means censored at <img src="https://latex.codecogs.com/png.latex?t=5.3"></td>
</tr>
</tbody>
</table>
</section>
<section id="xgboost-with-accelerated-failure-time" class="level3">
<h3 class="anchored" data-anchor-id="xgboost-with-accelerated-failure-time">XGBoost with Accelerated Failure Time</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Parameter</th>
<th>Value</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>objective</code></td>
<td><code>"survival:aft"</code></td>
<td></td>
</tr>
<tr class="even">
<td><code>eval_metric</code></td>
<td><code>"aft-nloglik"</code></td>
<td>Negative AFT log-likelihood</td>
</tr>
<tr class="odd">
<td><code>aft_loss_distribution</code></td>
<td><code>"normal"</code>, <code>"logistic"</code>, <code>"extreme"</code></td>
<td>Error distribution <img src="https://latex.codecogs.com/png.latex?f_Z">; <code>"extreme"</code> gives the Weibull/Gumbel</td>
</tr>
<tr class="even">
<td><code>aft_loss_distribution_scale</code></td>
<td>float (default <code>1.0</code>)</td>
<td>Fixed scale parameter <img src="https://latex.codecogs.com/png.latex?%5Csigma"></td>
</tr>
</tbody>
</table>
</section>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>Tree-based methods extend the survival analysis toolkit in two important ways. First, they relax the structural assumptions of Cox PH and AFT models — no proportional hazards, no fixed distributional form — letting the data determine how covariates relate to survival time. Second, they are better suited to capture non-linear relationship in the data and thus tend to generate better results at prediction tasks. In the next part of the series, we will see various models in code, examine model assumptions, and compare the predictive performance.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li><p>F. E. Harrell Jr.&nbsp;<a href="https://link.springer.com/book/10.1007/978-3-319-19425-7">Regression Modeling Strategies: With Applications to Linear Models, Logistic and Ordinal Regression, and Survival Analysis.</a> Springer, 2015.</p></li>
<li><p>H. Ishwaran and U. B. Kogalur. <a href="https://www.randomforestsrc.org/articles/survival.html">Random Forests for Survival, Regression, and Classification (RF-SRC).</a> R package vignette.</p></li>
<li><p>XGBoost Documentation. <a href="https://xgboost.readthedocs.io/en/stable/tutorials/aft_survival_analysis.html">Survival Analysis with Accelerated Failure Time.</a></p></li>
<li><p>W. Fu, S. Simonetti, H. Kjellström. <a href="https://arxiv.org/abs/2006.04920">Survival Regression with Accelerated Failure Time Model in XGBoost.</a> arXiv:2006.04920, 2020.</p></li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Survival Analysis - Part 5 - Tree-Based
Models.”</span> August 16. <a href="https://changruiraywang.com/blog/2026-08-16-survival-trees/">https://changruiraywang.com/blog/2026-08-16-survival-trees/</a>.
</div></div></section></div> ]]></description>
  <category>Statistics</category>
  <category>Machine Learning</category>
  <guid>https://changruiraywang.com/blog/2026-08-16-survival-trees/</guid>
  <pubDate>Sun, 16 Aug 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2026-08-16-survival-trees/sidebar.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Survival Analysis - Part 2 - Parametric Distributions</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2026-08-02-survival-parametric/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction---parametric-distributions" class="level2">
<h2 class="anchored" data-anchor-id="introduction---parametric-distributions">Introduction - Parametric Distributions</h2>
<p>Non-parametric methods are useful for estimating survival functions and hazard functions without making any assumptions about the underlying distribution of event times. However, in many cases, we may wish to gain more insight into the distribution, e.g.&nbsp;describing quantiles, and make predictions about future events. Parametric methods assume that the event times follow a specific probability distribution, and we can use this assumption to estimate the parameters of the distribution and make inferences about the survival function and hazard function.</p>
<p>There are several commonly used parametric distributions in survival analysis, including the exponential, Weibull, log-normal, log-logistic, and Gompertz distributions. Each of these distributions has its own characteristics and assumptions, and the choice of distribution depends on the nature of the data and the research question. In this post, we will discuss the properties of these parametric distributions, and how to assess the goodness-of-fit of the chosen distribution to the observed data.</p>
</section>
<section id="exponential-distribution" class="level2">
<h2 class="anchored" data-anchor-id="exponential-distribution">Exponential Distribution</h2>
<p>With its origin in the theory of Poisson processes, the exponential distribution is often used to model the time until the first event occurs. The exponential distribution is the simplest parametric survival model as it is characterized by a constant hazard rate, <img src="https://latex.codecogs.com/png.latex?%5Clambda">, which means that the probability of an event occurring in the next instant is independent of how long the subject has already survived. This property makes the exponential distribution a useful model for certain types of time-to-event data, such as the time until failure of a mechanical component or the time until death in a population with a constant mortality rate.</p>
<p>The probability density function (PDF) of the exponential distribution is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?f(t)%20=%20%5Clambda%20e%5E%7B-%5Clambda%20t%7D,%20%5Cquad%20t%20%5Cgeq%200"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Clambda%20%3E%200"> is the rate parameter.</p>
<div id="cell-fig-exp-dist" class="cell" data-execution_count="1">
<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> 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> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-3"></span>
<span id="cb1-4">rates <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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.0</span>]</span>
<span id="cb1-5">t <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;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>)</span>
<span id="cb1-6"></span>
<span id="cb1-7">fig, axes <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;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</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;">8</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>))</span>
<span id="cb1-8"></span>
<span id="cb1-9">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb1-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> lam <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> rates:</span>
<span id="cb1-11">    ax.plot(t, lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t), label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lambda=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>lam<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-12">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Probability Density Function"</span>)</span>
<span id="cb1-13">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb1-14"></span>
<span id="cb1-15">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb1-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> lam <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> rates:</span>
<span id="cb1-17">    ax.plot(t, np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t), label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lambda=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>lam<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-18">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Survival Function"</span>)</span>
<span id="cb1-19">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb1-20"></span>
<span id="cb1-21">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb1-22"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> lam <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> rates:</span>
<span id="cb1-23">    ax.plot(t, np.full_like(t, lam), label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lambda=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>lam<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-24">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hazard Function (constant)"</span>)</span>
<span id="cb1-25">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"h(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb1-26"></span>
<span id="cb1-27">plt.tight_layout()</span>
<span id="cb1-28">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-exp-dist" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-exp-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-exp-dist-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-1" title="Figure&nbsp;1: Exponential distribution: PDF, survival, and hazard for varying \lambda"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/index_files/figure-html/fig-exp-dist-output-1.png" width="770" height="221" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-exp-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Exponential distribution: PDF, survival, and hazard for varying <img src="https://latex.codecogs.com/png.latex?%5Clambda">
</figcaption>
</figure>
</div>
</div>
</div>
<p>The survival function is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?S(t)%20=%20e%5E%7B-%5Clambda%20t%7D,%20%5Cquad%20t%20%5Cgeq%200"></p>
<p>The hazard function is constant and given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?h(t)%20=%20%5Clambda,%20%5Cquad%20t%20%5Cgeq%200"></p>
<p>The fact that the hazard function is constant implies that the exponential distribution is not suitable for modeling survival data with changing hazard rates over time. To account for such cases, we need parametric distributions whose hazard functions can vary over time, such as the Weibull, log-normal, log-logistic, and Gompertz distributions.</p>
</section>
<section id="weibull-distribution" class="level2">
<h2 class="anchored" data-anchor-id="weibull-distribution">Weibull Distribution</h2>
<p>The Weibull distribution is a versatile continuous probability distribution that can model a wide range of hazard rate behaviors. It can be viewed as a generalization of the exponential distribution, and it is often used in reliability engineering and survival analysis to model the time until failure of a system or component.</p>
<p>The probability density function (PDF) of the Weibull distribution is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?f(t)%20=%20%5Clambda%20%5Cnu%20t%5E%7B%5Cnu%20-%201%7D%5Cexp%5Cleft(-%5Clambda%20t%5E%5Cnu%5Cright),%20%5Cquad%20t%20%5Cgeq%200"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Clambda"> is the scale parameter and <img src="https://latex.codecogs.com/png.latex?%5Cnu"> is the shape parameter.</p>
<div id="cell-fig-weibull-dist" 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> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb2-3"></span>
<span id="cb2-4">lam <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="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fix scale parameter</span></span>
<span id="cb2-5">nus <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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.0</span>]       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shape parameters to compare</span></span>
<span id="cb2-6">t <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="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 class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># start slightly above 0 to avoid t^(nu-1) blowup for nu&lt;1</span></span>
<span id="cb2-7"></span>
<span id="cb2-8">fig, axes <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;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</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;">8</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>))</span>
<span id="cb2-9"></span>
<span id="cb2-10">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb2-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> nu <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> nus:</span>
<span id="cb2-12">    pdf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> nu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>(nu <span 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(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>nu)</span>
<span id="cb2-13">    ax.plot(t, pdf, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\n</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">u=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>nu<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb2-14">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Weibull PDF ($</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;">lambda=1$)"</span>)</span>
<span id="cb2-15">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb2-16"></span>
<span id="cb2-17">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb2-18"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> nu <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> nus:</span>
<span id="cb2-19">    S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>nu)</span>
<span id="cb2-20">    ax.plot(t, S, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\n</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">u=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>nu<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb2-21">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Weibull Survival Function ($</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;">lambda=1$)"</span>)</span>
<span id="cb2-22">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb2-23"></span>
<span id="cb2-24">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb2-25"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> nu <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> nus:</span>
<span id="cb2-26">    h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> nu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>(nu <span 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-27">    ax.plot(t, h, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\n</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">u=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>nu<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb2-28">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Weibull Hazard Function ($</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;">lambda=1$)"</span>)</span>
<span id="cb2-29">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"h(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb2-30"></span>
<span id="cb2-31">plt.tight_layout()</span>
<span id="cb2-32">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-weibull-dist" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-weibull-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-weibull-dist-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2" title="Figure&nbsp;2: Weibull distribution: PDF, survival, and hazard for varying \nu"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/index_files/figure-html/fig-weibull-dist-output-1.png" width="790" height="220" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-weibull-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Weibull distribution: PDF, survival, and hazard for varying <img src="https://latex.codecogs.com/png.latex?%5Cnu">
</figcaption>
</figure>
</div>
</div>
</div>
<p>As the illustrative plot shows above, the Weibull distribution can model increasing, decreasing, or constant hazard rates depending on the value of the shape parameter <img src="https://latex.codecogs.com/png.latex?%5Cnu">. When <img src="https://latex.codecogs.com/png.latex?%5Cnu%20=%201">, the Weibull distribution reduces to the exponential distribution, and the hazard function is constant. When <img src="https://latex.codecogs.com/png.latex?%5Cnu%20%3C%201">, the hazard function decreases over time. When <img src="https://latex.codecogs.com/png.latex?%5Cnu%20%3E%201"> (early-failure/infant mortality), the hazard function increases over time (aging/wear-out). This flexibility makes the Weibull distribution a popular choice for modeling survival data with varying hazard rates.</p>
<p>The survival function of the Weibull distribution is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?S(t)%20=%20%5Cexp%5Cleft(-%5Clambda%20t%5E%5Cnu%5Cright),%20%5Cquad%20t%20%5Cgeq%200"></p>
<p>The hazard function is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?h(t)%20=%20%5Clambda%20%5Cnu%20t%5E%7B%5Cnu%20-%201%7D,%20%5Cquad%20t%20%5Cgeq%200"></p>
<section id="different-parameterizations-of-weibull-distribution" class="level3">
<h3 class="anchored" data-anchor-id="different-parameterizations-of-weibull-distribution">Different Parameterizations of Weibull Distribution</h3>
<p>This parameterization is usually called the ‘rate’ parameterization. The Weibull distribution can also be parameterized in terms of a scale parameter <img src="https://latex.codecogs.com/png.latex?%5Csigma"> and a shape parameter <img src="https://latex.codecogs.com/png.latex?k">, where <img src="https://latex.codecogs.com/png.latex?%5Csigma%20=%20%5Clambda%5E%7B-1/%5Cnu%7D"> and <img src="https://latex.codecogs.com/png.latex?k%20=%20%5Cnu">. Specifically, the survival function is formulated as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cexp%5Cleft(-%5Cleft(%5Cfrac%7Bt%7D%7B%5Csigma_%7B%5Ctext%7Btrue%7D%7D%7D%5Cright)%5Ea%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?a"> is the shape parameter and <img src="https://latex.codecogs.com/png.latex?%5Csigma_%7B%5Ctext%7Btrue%7D%7D"> is the scale parameter.</p>
<p>The two parameterizations can be confusing enough, to make things worse, different software packages in R and Python use different greek letters to mean the same parameter.</p>
<p>To make it clear across parameterizations and packages, the table below maps the relationship:</p>
<div id="tbl-weibull-param" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-weibull-param-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;1: Weibull parameterizations across common software conventions. The shape parameter is written <img src="https://latex.codecogs.com/png.latex?%5Cnu"> throughout, since it is the same quantity in every convention — only the scale changes.
</figcaption>
<div aria-describedby="tbl-weibull-param-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 15%">
<col style="width: 15%">
<col style="width: 25%">
<col style="width: 15%">
<col style="width: 15%">
<col style="width: 15%">
</colgroup>
<thead>
<tr class="header">
<th>Convention</th>
<th>Form</th>
<th style="text-align: center;">Shape (<img src="https://latex.codecogs.com/png.latex?%5Cnu">)</th>
<th>Scale</th>
<th>Get shape</th>
<th>Get scale</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Table I (this blog)</td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cexp(-%5Clambda%20t%5E%5Cnu)"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cnu"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Clambda"> — <em>not</em> a true scale; <img src="https://latex.codecogs.com/png.latex?%5Clambda%20=%20%5Csigma_%7B%5Ctext%7Btrue%7D%7D%5E%7B-%5Cnu%7D"></td>
<td>—</td>
<td>—</td>
</tr>
<tr class="even">
<td><code>rweibull</code> / <code>lifelines</code></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cexp%5Cleft(-(t/%5Csigma_%7B%5Ctext%7Btrue%7D%7D)%5E%5Cnu%5Cright)"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cnu"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Csigma_%7B%5Ctext%7Btrue%7D%7D"> (genuine scale)</td>
<td>Py: <code>WeibullFitter().fit().rho_</code><br>R: <code>rweibull(shape=)</code></td>
<td>Py: <code>WeibullFitter().fit().lambda_</code><br>R: <code>rweibull(scale=)</code></td>
</tr>
<tr class="odd">
<td><code>survreg</code> (K&amp;P, pre-transform)</td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cexp%5Cleft(-(%5Clambda_%7BKP%7D%5C,t)%5E%5Cnu%5Cright)"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cnu"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Clambda_%7BKP%7D"> — a rate multiplying <img src="https://latex.codecogs.com/png.latex?t">; internal only</td>
<td>not user-facing</td>
<td>not user-facing</td>
</tr>
<tr class="even">
<td><code>survreg</code> (reported output)</td>
<td><img src="https://latex.codecogs.com/png.latex?(%5Calpha,%5Csigma)"> on <img src="https://latex.codecogs.com/png.latex?%5Clog%20t">, <img src="https://latex.codecogs.com/png.latex?%5Cnu=1/%5Csigma"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?1/%5Csigma"></td>
<td><img src="https://latex.codecogs.com/png.latex?e%5E%7B%5Calpha%7D"> (equals <img src="https://latex.codecogs.com/png.latex?%5Csigma_%7B%5Ctext%7Btrue%7D%7D">)</td>
<td>R: <code>1/fit$scale</code></td>
<td>R: <code>exp(coef(fit))</code></td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
</section>
<section id="graphical-assessment-of-weibull-fit" class="level3">
<h3 class="anchored" data-anchor-id="graphical-assessment-of-weibull-fit">Graphical Assessment of Weibull Fit</h3>
<p>The Weibull distribution has an important property that allows us to assess the goodness-of-fit of the distribution to the observed data. If the event times follow a Weibull distribution, then the following transformation of the survival function should yield a linear relationship:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AS(t)%20=%20%5Cexp%5Cleft(-%5Clambda%20t%5E%5Cnu%5Cright)%20%5Cimplies%20%5Cln(-%5Cln(S(t)))%20=%20%5Cln(%5Clambda)+%5Cnu%20%5Cln(t)%0A"></p>
<p>If we use the Kaplan-Meier estimate of the survival function <img src="https://latex.codecogs.com/png.latex?S(t)">, this property allows for a graphical evaluation of the appropriateness of a Weibull model by plotting the log negative log of the Kaplan-Meier estimate of the survival function against the log of time. If the points fall approximately along a straight line, then the Weibull distribution is a reasonable fit for the data.</p>
</section>
</section>
<section id="gompertz-distribution" class="level2">
<h2 class="anchored" data-anchor-id="gompertz-distribution">Gompertz Distribution</h2>
<p>Even though the Weibull distribution with a <img src="https://latex.codecogs.com/png.latex?%5Cnu"> greater than 1 can model increasing hazard rates, the hazard growth is polynomial. The Gompertz distribution is another parametric distribution that can model hazard rates that grow exponentially over time, and it is often used in demography and actuarial science to model human mortality.</p>
<p>The probability density function (PDF) of the Gompertz distribution is given by: <img src="https://latex.codecogs.com/png.latex?%0Af(t)%20=%20%5Clambda%20e%5E%7B%5Calpha%20t%7D%20%5Cexp%5C!%5Cleft(-%5Cfrac%7B%5Clambda%7D%7B%5Calpha%7D%5Cleft(e%5E%7B%5Calpha%20t%7D%20-%201%5Cright)%5Cright)%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Clambda"> is the scale parameter and <img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the shape parameter.</p>
<p>The survival function of the Gompertz distribution is given by: <img src="https://latex.codecogs.com/png.latex?%0AS(t)%20=%20%5Cexp%5C!%5Cleft(-%5Cfrac%7B%5Clambda%7D%7B%5Calpha%7D%5Cleft(e%5E%7B%5Calpha%20t%7D%20-%201%5Cright)%5Cright)%0A"></p>
<p>The hazard function is given by: <img src="https://latex.codecogs.com/png.latex?%0Ah(t)%20=%20%5Clambda%20e%5E%7B%5Calpha%20t%7D%0A"></p>
<p>With <img src="https://latex.codecogs.com/png.latex?%5Calpha%20%3E%200">, the hazard function increases exponentially over time.</p>
<p>To see the two different growth patterns, consider the hazard functions of the Weibull and Gompertz distributions: <img src="https://latex.codecogs.com/png.latex?%0Ah(t)%20=%20%5Clambda%20%5Cnu%20t%5E%7B%5Cnu%20-%201%7D%0A"></p>
<p>This is <img src="https://latex.codecogs.com/png.latex?t"> raised to a fixed power.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Ah(t)%20=%20%5Clambda%20e%5E%7B%5Calpha%20t%7D%0A"></p>
<p>Here <img src="https://latex.codecogs.com/png.latex?t"> sits in the exponent. As <img src="https://latex.codecogs.com/png.latex?t"> increases by a fixed amount, <img src="https://latex.codecogs.com/png.latex?h(t)"> gets multiplied by a fixed factor <img src="https://latex.codecogs.com/png.latex?e%5E%7B%5Calpha%7D">, rather than just increasing by some additive/polynomial amount.</p>
<p>Let’s visualize some Gompertz distributions with different values of the shape parameter <img src="https://latex.codecogs.com/png.latex?%5Calpha">.</p>
<div id="cell-fig-gompertz-dist" 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="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> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb3-2"><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-3"></span>
<span id="cb3-4">lam <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="cb3-5">alphas <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="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 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.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>]</span>
<span id="cb3-6">t <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="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="cb3-7"></span>
<span id="cb3-8">fig, axes <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;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</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;">8</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>))</span>
<span id="cb3-9"></span>
<span id="cb3-10">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb3-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> alpha <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> alphas:</span>
<span id="cb3-12">    H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (lam <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> (np.exp(alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> 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>
<span id="cb3-13">    pdf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.exp(alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>H)</span>
<span id="cb3-14">    ax.plot(t, pdf, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\a</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lpha=</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="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>
<span id="cb3-15">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Gompertz PDF ($</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;">lambda=1$)"</span>)</span>
<span id="cb3-16">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb3-17"></span>
<span id="cb3-18">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb3-19"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> alpha <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> alphas:</span>
<span id="cb3-20">    H <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (lam <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> (np.exp(alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> 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>
<span id="cb3-21">    S <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>H)</span>
<span id="cb3-22">    ax.plot(t, S, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\a</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lpha=</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="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>
<span id="cb3-23">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Gompertz Survival Function ($</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;">lambda=1$)"</span>)</span>
<span id="cb3-24">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb3-25"></span>
<span id="cb3-26">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb3-27"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> alpha <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> alphas:</span>
<span id="cb3-28">    h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.exp(alpha <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t)</span>
<span id="cb3-29">    ax.plot(t, h, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\a</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lpha=</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="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>
<span id="cb3-30">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Gompertz Hazard Function ($</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;">lambda=1$)"</span>)</span>
<span id="cb3-31">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"h(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb3-32"></span>
<span id="cb3-33">plt.tight_layout()</span>
<span id="cb3-34">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-gompertz-dist" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-gompertz-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-gompertz-dist-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3" title="Figure&nbsp;3: Gompertz distribution: PDF, survival, and hazard for varying \alpha"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/index_files/figure-html/fig-gompertz-dist-output-1.png" width="809" height="220" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-gompertz-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Gompertz distribution: PDF, survival, and hazard for varying <img src="https://latex.codecogs.com/png.latex?%5Calpha">
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="log-normal-distribution" class="level2">
<h2 class="anchored" data-anchor-id="log-normal-distribution">Log-Normal Distribution</h2>
<p>The log-normal distribution is often used to model survival data with non-monotonic hazard rates, where the hazard rate initially increases and then decreases over time. This property makes the log-normal distribution suitable for modeling survival data with a peak hazard rate, such as the time until failure of a mechanical component that experiences wear and tear over time.</p>
<p>The log-normal distribution is obtained by taking the logarithm of a normally distributed random variable. We apply the logarithm transformation to event time <img src="https://latex.codecogs.com/png.latex?T"> and assume the new variable <img src="https://latex.codecogs.com/png.latex?Y%20=%20%5Cln(T)"> follows a normal distribution with mean <img src="https://latex.codecogs.com/png.latex?%5Cmu"> and standard deviation <img src="https://latex.codecogs.com/png.latex?%5Csigma">: <img src="https://latex.codecogs.com/png.latex?%5Clog(T)%20%5Csim%20N(%5Cmu,%20%5Csigma%5E2)">.</p>
<p>The probability density function (PDF) of the log-normal distribution is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?f(t)%20=%20%5Cfrac%7B1%7D%7Bt%5Csigma%5Csqrt%7B2%5Cpi%7D%7D%20%5Cexp%5Cleft(-%5Cfrac%7B(%5Cln%20t%20-%20%5Cmu)%5E2%7D%7B2%5Csigma%5E2%7D%5Cright),%20%5Cquad%20t%20%3E%200"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cmu"> and <img src="https://latex.codecogs.com/png.latex?%5Csigma"> are the mean and standard deviation of the underlying normal distribution.</p>
<p>The survival function is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?S(t)%20=%201%20-%20%5CPhi%5Cleft(%5Cfrac%7B%5Cln%20t%20-%20%5Cmu%7D%7B%5Csigma%7D%5Cright)%20=%20%5Cunderbrace%7B%5CPhi%5Cleft(-%5Cfrac%7B%5Cln%20t%20-%20%5Cmu%7D%7B%5Csigma%7D%5Cright)%7D_%7B%5Ctext%7Bsymmetry%20of%20standard%20normal%20CDF%7D%7D,%20%5Cquad%20t%20%3E%200"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5CPhi"> is the cumulative distribution function of the standard normal distribution.</p>
<p>The hazard function is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?h(t)%20=%20%5Cfrac%7Bf(t)%7D%7BS(t)%7D%20=%20%5Cfrac%7B%5Cphi%5Cleft(%5Cdfrac%7B%5Clog%20t%20-%20%5Cmu%7D%7B%5Csigma%7D%5Cright)%7D%7Bt%5Csigma%5C,%20%5CPhi%5Cleft(-%5Cdfrac%7B%5Clog%20t%20-%20%5Cmu%7D%7B%5Csigma%7D%5Cright)%7D"></p>
<div id="cell-fig-lognormal-dist" 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="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> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb4-2"><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="cb4-3"><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> norm</span>
<span id="cb4-4"></span>
<span id="cb4-5">mu <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.0</span></span>
<span id="cb4-6">sigmas <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>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>]</span>
<span id="cb4-7">t <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="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>)</span>
<span id="cb4-8"></span>
<span id="cb4-9">fig, axes <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;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</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;">8</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>))</span>
<span id="cb4-10"></span>
<span id="cb4-11">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb4-12"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> sigma <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> sigmas:</span>
<span id="cb4-13">    pdf <span 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> (t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.sqrt(<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> np.pi))) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(np.log(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu) <span 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 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> 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="cb4-14">    ax.plot(t, pdf, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\s</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">igma=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>sigma<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb4-15">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Log-normal PDF ($</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;">mu=0$)"</span>)</span>
<span id="cb4-16">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb4-17"></span>
<span id="cb4-18">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb4-19"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> sigma <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> sigmas:</span>
<span id="cb4-20">    z <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (np.log(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sigma</span>
<span id="cb4-21">    S <span 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> norm.cdf(z)</span>
<span id="cb4-22">    ax.plot(t, S, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\s</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">igma=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>sigma<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb4-23">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Log-normal Survival Function ($</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;">mu=0$)"</span>)</span>
<span id="cb4-24">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb4-25"></span>
<span id="cb4-26">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb4-27"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> sigma <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> sigmas:</span>
<span id="cb4-28">    z <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (np.log(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sigma</span>
<span id="cb4-29">    S <span 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> norm.cdf(z)</span>
<span id="cb4-30">    h <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> norm.pdf(z) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> S)</span>
<span id="cb4-31">    ax.plot(t, h, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\s</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">igma=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>sigma<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb4-32">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Log-normal Hazard Function ($</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;">mu=0$)"</span>)</span>
<span id="cb4-33">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"h(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb4-34"></span>
<span id="cb4-35">plt.tight_layout()</span>
<span id="cb4-36">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-lognormal-dist" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-lognormal-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-lognormal-dist-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-4" title="Figure&nbsp;4: Log-normal distribution: PDF, survival, and hazard for varying \sigma"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/index_files/figure-html/fig-lognormal-dist-output-1.png" width="806" height="220" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-lognormal-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Log-normal distribution: PDF, survival, and hazard for varying <img src="https://latex.codecogs.com/png.latex?%5Csigma">
</figcaption>
</figure>
</div>
</div>
</div>
<section id="graphical-assessment-of-log-normal-fit" class="level3">
<h3 class="anchored" data-anchor-id="graphical-assessment-of-log-normal-fit">Graphical Assessment of Log-Normal Fit</h3>
<p>If the event times follow a log-normal distribution, then the following transformation of the survival function should yield a linear relationship:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5CPhi%5E%7B-1%7D(S(t))%20=%20%5Cfrac%7B%5Cmu%20-%20%5Cln(t)%7D%7B%5Csigma%7D%20=%20-%5Cfrac%7B1%7D%7B%5Csigma%7D%5Cln(t)%20+%20%5Cfrac%7B%5Cmu%7D%7B%5Csigma%7D%0A"></p>
<p>That is, if we plot the inverse of the standard normal CDF of the Kaplan-Meier estimate of the survival function against the logarithm of time, we should see a linear relationship if the log-normal distribution is a reasonable fit for the data.</p>
</section>
</section>
<section id="log-logistic-distribution" class="level2">
<h2 class="anchored" data-anchor-id="log-logistic-distribution">Log-Logistic Distribution</h2>
<p>A cousin of the log-normal distribution is the log-logistic distribution, which is obtained by taking the logarithm of a logistic distributed random variable. We apply the logarithm transformation to event time <img src="https://latex.codecogs.com/png.latex?T"> and assume the new variable <img src="https://latex.codecogs.com/png.latex?Y%20=%20%5Cln(T)"> follows a logistic distribution with location parameter <img src="https://latex.codecogs.com/png.latex?%5Cmu"> and scale parameter <img src="https://latex.codecogs.com/png.latex?%5Csigma">: <img src="https://latex.codecogs.com/png.latex?%5Clog(T)%20%5Csim%20Logistic(%5Cmu,%20%5Csigma)">.</p>
<p>The log logistic distribution can be thought of a flexible alternative to the log-normal distribution, as it can not only model non-monotonic hazard rates, but also has a closed-form expression for its survival function and hazard function without having to rely on <img src="https://latex.codecogs.com/png.latex?%5CPhi">, making it more tractable for optimization and interpretation.</p>
<p>The probability density function (PDF) of the log-logistic distribution is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?f(t)%20=%20%5Cfrac%7B(%5Cbeta/%5Calpha)(t/%5Calpha)%5E%7B%5Cbeta-1%7D%7D%7B(1+(t/%5Calpha)%5E%5Cbeta)%5E2%7D,%20%5Cquad%20t%20%3E%200"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the scale parameter and <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> is the shape parameter.</p>
<p>The survival function is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?S(t)%20=%20%5Cfrac%7B1%7D%7B1+(t/%5Calpha)%5E%5Cbeta%7D,%20%5Cquad%20t%20%3E%200"></p>
<p>The hazard function is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?h(t)%20=%20%5Cfrac%7B(%5Cbeta/%5Calpha)(t/%5Calpha)%5E%7B%5Cbeta-1%7D%7D%7B1+(t/%5Calpha)%5E%5Cbeta%7D"></p>
<p>Below is an illustrative plot of the log-logistic distribution with different values of the shape parameter <img src="https://latex.codecogs.com/png.latex?%5Cbeta">. As we can see, the log-logistic distribution can model increasing, decreasing, or non-monotonic hazard rates depending on the value of <img src="https://latex.codecogs.com/png.latex?%5Cbeta">.</p>
<div id="cell-fig-loglogistic-dist" class="cell" data-execution_count="5">
<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> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb5-2"><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="cb5-3"></span>
<span id="cb5-4">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;">1.0</span></span>
<span id="cb5-5">betas <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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.0</span>]</span>
<span id="cb5-6">t <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="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>)</span>
<span id="cb5-7"></span>
<span id="cb5-8">fig, axes <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;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</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;">8</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>))</span>
<span id="cb5-9"></span>
<span id="cb5-10">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb5-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> beta <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> betas:</span>
<span id="cb5-12">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> alpha</span>
<span id="cb5-13">    pdf <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> alpha) <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>(beta <span 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;">1</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>beta) <span 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-14">    ax.plot(t, pdf, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\b</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">eta=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>beta<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb5-15">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Log-logistic PDF ($</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;">alpha=1$)"</span>)</span>
<span id="cb5-16">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb5-17"></span>
<span id="cb5-18">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb5-19"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> beta <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> betas:</span>
<span id="cb5-20">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> alpha</span>
<span id="cb5-21">    S <span 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;">1</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>beta)</span>
<span id="cb5-22">    ax.plot(t, S, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\b</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">eta=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>beta<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb5-23">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Log-logistic Survival Function ($</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;">alpha=1$)"</span>)</span>
<span id="cb5-24">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb5-25"></span>
<span id="cb5-26">ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb5-27"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> beta <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> betas:</span>
<span id="cb5-28">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> alpha</span>
<span id="cb5-29">    h <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> alpha) <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>(beta <span 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;">1</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>beta)</span>
<span id="cb5-30">    ax.plot(t, h, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\b</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">eta=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>beta<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;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb5-31">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Log-logistic Hazard Function ($</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;">alpha=1$)"</span>)</span>
<span id="cb5-32">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"h(t)"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> ax.legend()</span>
<span id="cb5-33"></span>
<span id="cb5-34">plt.tight_layout()</span>
<span id="cb5-35">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-loglogistic-dist" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-loglogistic-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-loglogistic-dist-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-5" title="Figure&nbsp;5: Log-logistic distribution: PDF, survival, and hazard for varying \beta"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/index_files/figure-html/fig-loglogistic-dist-output-1.png" width="806" height="220" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-loglogistic-dist-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;5: Log-logistic distribution: PDF, survival, and hazard for varying <img src="https://latex.codecogs.com/png.latex?%5Cbeta">
</figcaption>
</figure>
</div>
</div>
</div>
<section id="graphical-assessment-of-log-logistic-fit" class="level3">
<h3 class="anchored" data-anchor-id="graphical-assessment-of-log-logistic-fit">Graphical Assessment of Log-Logistic Fit</h3>
<p>To graphically assess the goodness-of-fit of the log-logistic distribution to the observed data, we can use a similar approach as for the Weibull and log-normal distributions. If the event times follow a log-logistic distribution, then the following transformation of the survival function should yield a linear relationship:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AS(t)%20=%20%5Cfrac%7B1%7D%7B1+(t/%5Calpha)%5E%5Cbeta%7D%20%5Cimplies%20%5Cln(%5Cdfrac%7B1-S(t)%7D%7BS(t)%7D)%20=%20%5Cbeta%20%5Cln(t)%20-%20%5Cbeta%20%5Cln(%5Calpha)%0A"></p>
<p>That is, if we plot the logit of the Kaplan-Meier estimate of the survival function against the logarithm of time, we should see a linear relationship if the log-logistic distribution is a reasonable fit for the data.</p>
<p>We can now compare all four parametric distributions (Weibull, Gompertz, log-normal, and log-logistic) in one table.</p>
<div id="tbl-dists" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-dists-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;2: Characterization of the exponential, Weibull, Gompertz, log-normal, and log-logistic distributions.
</figcaption>
<div aria-describedby="tbl-dists-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 10%">
<col style="width: 17%">
<col style="width: 17%">
<col style="width: 17%">
<col style="width: 17%">
<col style="width: 17%">
</colgroup>
<thead>
<tr class="header">
<th>Characteristic</th>
<th style="text-align: center;">Exponential</th>
<th style="text-align: center;">Weibull</th>
<th style="text-align: center;">Gompertz</th>
<th style="text-align: center;">Log-normal</th>
<th style="text-align: center;">Log-logistic</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Parameter</td>
<td style="text-align: center;">Scale <img src="https://latex.codecogs.com/png.latex?%5Clambda%20%3E%200"></td>
<td style="text-align: center;">Scale <img src="https://latex.codecogs.com/png.latex?%5Clambda%20%3E%200"><br>Shape <img src="https://latex.codecogs.com/png.latex?%5Cnu%20%3E%200"></td>
<td style="text-align: center;">Scale <img src="https://latex.codecogs.com/png.latex?%5Clambda%20%3E%200"><br>Shape <img src="https://latex.codecogs.com/png.latex?-%5Cinfty%20%3C%20%5Calpha%20%3C%20%5Cinfty"></td>
<td style="text-align: center;">Location <img src="https://latex.codecogs.com/png.latex?-%5Cinfty%20%3C%20%5Cmu%20%3C%20%5Cinfty"><br>Scale <img src="https://latex.codecogs.com/png.latex?%5Csigma%20%3E%200"></td>
<td style="text-align: center;">Scale <img src="https://latex.codecogs.com/png.latex?%5Calpha%20%3E%200"><br>Shape <img src="https://latex.codecogs.com/png.latex?%5Cbeta%20%3E%200"></td>
</tr>
<tr class="even">
<td>Hazard function</td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?h_0(t)%20=%20%5Clambda"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?h_0(t)%20=%20%5Clambda%20%5Cnu%20t%5E%7B%5Cnu-1%7D"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?h_0(t)%20=%20%5Clambda%20e%5E%7B%5Calpha%20t%7D"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?h(t)%20=%20%5Cdfrac%7B%5Cphi%5Cleft(%5Cfrac%7B%5Clog%20t%20-%20%5Cmu%7D%7B%5Csigma%7D%5Cright)%7D%7Bt%5Csigma%5C,%5CPhi%5Cleft(-%5Cfrac%7B%5Clog%20t%20-%20%5Cmu%7D%7B%5Csigma%7D%5Cright)%7D"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?h(t)%20=%20%5Cdfrac%7B(%5Cbeta/%5Calpha)(t/%5Calpha)%5E%7B%5Cbeta-1%7D%7D%7B1+(t/%5Calpha)%5E%5Cbeta%7D"></td>
</tr>
<tr class="odd">
<td>Cumulative hazard</td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?H_0(t)%20=%20%5Clambda%20t"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?H_0(t)%20=%20%5Clambda%20t%5E%7B%5Cnu%7D"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?H_0(t)%20=%20%5Cdfrac%7B%5Clambda%7D%7B%5Calpha%7D%5Cleft(e%5E%7B%5Calpha%20t%7D%20-%201%5Cright)"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?H(t)%20=%20-%5Clog%5CPhi%5Cleft(-%5Cdfrac%7B%5Clog%20t%20-%20%5Cmu%7D%7B%5Csigma%7D%5Cright)"></td>
<td style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?H(t)%20=%20%5Clog%5Cleft(1+(t/%5Calpha)%5E%5Cbeta%5Cright)"></td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
<div class="callout callout-style-default callout-note callout-titled" title="Example Code of Graphical Assessment of GoF">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Example Code of Graphical Assessment of GoF
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div id="b57d4bbc" class="cell" data-execution_count="6">
<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="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> probability_plot(durations, event_observed, distribution, fitter<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>, ax<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-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb6-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Graphical goodness-of-fit assessment via a linearizing transform of S(t).</span></span>
<span id="cb6-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Points roughly linear =&gt; the distribution is plausible.</span></span>
<span id="cb6-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb6-6">    </span>
<span id="cb6-7">    _SPECS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb6-8">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weibull"</span>: (</span>
<span id="cb6-9">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> S: np.log(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>np.log(S)),</span>
<span id="cb6-10">            <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="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">log</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 class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">log </span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">hat S</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;">t</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">))</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>
<span id="cb6-11">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> f: (f.rho_, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>f.rho_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.log(f.lambda_)),   </span>
<span id="cb6-12">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> f: <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\n</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">u</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="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>rho_<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lambda</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="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>lambda_<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>f.rho_)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3g}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb6-13">        ),</span>
<span id="cb6-14">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lognormal"</span>: (</span>
<span id="cb6-15">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> S: norm.ppf(<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> S),</span>
<span id="cb6-16">            <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="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">Phi</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;">{-1}</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;">1-</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">hat S</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;">t</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">))</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>
<span id="cb6-17">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> f: (<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> f.sigma_, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>f.mu_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> f.sigma_),</span>
<span id="cb6-18">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> f: <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\m</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">u</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="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>mu_<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\s</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">igma</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="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>sigma_<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb6-19">        ),</span>
<span id="cb6-20">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loglogistic"</span>: (</span>
<span id="cb6-21">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> S: 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> S) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> S),</span>
<span id="cb6-22">            <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="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">log</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">left</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[(1-</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">hat S(t))/</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">hat S(t)</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\r</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ight]</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>
<span id="cb6-23">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> f: (f.beta_, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>f.beta_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.log(f.alpha_)),</span>
<span id="cb6-24">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> f: <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">fr"</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;">\a</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">lpha</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="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>f<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;">:.3f}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$\b</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">eta</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="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>beta_<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb6-25">        )</span>
<span id="cb6-26">    }</span>
<span id="cb6-27">    </span>
<span id="cb6-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> distribution <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> _SPECS:</span>
<span id="cb6-29">        <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="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Unknown distribution '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>distribution<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;">'. Choose from </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;">list</span>(_SPECS)<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="cb6-30">    ytrans, ylabel, line_params, label_fmt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _SPECS[distribution]</span>
<span id="cb6-31"></span>
<span id="cb6-32">    kmf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KaplanMeierFitter().fit(durations, event_observed)</span>
<span id="cb6-33">    sf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> kmf.survival_function_.reset_index()</span>
<span id="cb6-34">    sf.columns <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;">"t"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S"</span>]</span>
<span id="cb6-35">    sf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sf[(sf[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</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;">0</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> (sf[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S"</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;">0</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> (sf[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S"</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;">1</span>)]   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># guard log(0) / Phi^-1(0,1)</span></span>
<span id="cb6-36"></span>
<span id="cb6-37">    x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.log(sf[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>].values)</span>
<span id="cb6-38">    y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ytrans(sf[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S"</span>].values)</span>
<span id="cb6-39"></span>
<span id="cb6-40">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> ax <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>:</span>
<span id="cb6-41">        _, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(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;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb6-42">    ax.plot(x, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"o"</span>, ms<span 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>, 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.6</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;">"KM estimate"</span>)</span>
<span id="cb6-43"></span>
<span id="cb6-44">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> fitter <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</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;">None</span>:</span>
<span id="cb6-45">        slope, intercept <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> line_params(fitter)</span>
<span id="cb6-46">        xx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(x.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(), x.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb6-47">        ax.plot(xx, intercept <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> slope <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> xx, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r-"</span>, lw<span 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>, 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"fitted: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>label_fmt(fitter)<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="cb6-48"></span>
<span id="cb6-49">    ax.set_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="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">log t</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>
<span id="cb6-50">    ax.set_ylabel(ylabel)</span>
<span id="cb6-51">    ax.set_title(<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>distribution<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>capitalize()<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;"> Probability Plot"</span>)</span>
<span id="cb6-52">    ax.legend()</span>
<span id="cb6-53">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ax</span></code></pre></div></div>
</details>
</div>
</div>
</div>
</div>
</section>
</section>
<section id="statistical-goodness-of-fit-test" class="level2">
<h2 class="anchored" data-anchor-id="statistical-goodness-of-fit-test">Statistical Goodness-of-Fit Test</h2>
<p>In addition to graphical assessment, we can also perform a formal goodness-of-fit test to evaluate how well the chosen distribution fits the observed data.</p>
<p>The KS test is a widely used non-parametric goodness-of-fit test. It compares the empirical distribution function of the observed data with the cumulative distribution function of the fitted model. However, the standard KS test is not directly applicable to censored data, as it does not account for the censoring mechanism. To address this issue, we can use a modified version of the KS test that takes into account the censoring pattern in the data. For this blog,the modified KS test by the R package <a href="https://cran.r-project.org/package=GofCens">GofCens: Goodness-of-Fit Methods for Right-Censored Data.</a> is implemented in Python.</p>
<p>For implementation details, check out the notes below.</p>
<div class="callout callout-style-default callout-note callout-titled" title="Algorithm of KS Test for Right-censored Data">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Algorithm of KS Test for Right-censored Data
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>The steps for performing the modified KS test for censored data are as follows:</p>
<ol type="1">
<li>Get empirical (KM-based) CDF of original data</li>
<li>Fit model to original data → θ̂</li>
<li>Get modified KS statistic D_obs, comparing the KM-based empirical CDF (step 1) against the fitted model (step 2)</li>
<li>Repeat B times (e.g., B = 999): 4.1 Simulate event times from the fitted model (θ̂) 4.2 Simulate censoring times from the reverse-KM estimate of the censoring distribution (fit to the original data’s censoring pattern) 4.3 Build synthetic censored data: min(event, censor),event indicator 4.4 Refit the model on the synthetic data → θ̂^(b) 4.5 Get the synthetic data’s own KM-based empirical CDF, compute the modified KS statistic D^(b)</li>
<li>p-value = proportion of {D^(1), …, D^(B)} that are ≥ D_obs</li>
</ol>
</div>
</div>
</div>
<div class="callout callout-style-default callout-note callout-titled" title="GofCens Implementation of Modified KS Statistic">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>GofCens Implementation of Modified KS Statistic
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>The core challenge of the algorithm lies in step 3 to get the modified KS statistic defined per <a href="https://upcommons.upc.edu/server/api/core/bitstreams/fa25282f-4444-443e-b6a5-c4baf28cfe01/content">R package GofCens: Goodness-of-Fit Methods for Right-Censored Data.</a>:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Chat%7BD%7D_n%20=%20%5Csup_%7B0%5Cleq%20t%5Cleq%20t_m%7D%0A%20%20%5Chat%7BS%7D_n(t)%0A%20%20%5Ccdot%0A%20%20%5Cint_0%5Et%0A%20%20%20%20%5Cfrac%7BS_0(s;%5Ctheta%5E*)%7D%7B%5Chat%7BS%7D_n(s)%7D%0A%20%20%20%20%5C;%0A%20%20%20%20d%5C!%5Cleft%5B%5Chat%7B%5CLambda%7D_n(s)%20-%20%5CLambda_0(s;%5Ctheta%5E*)%5Cright%5D%0A"></p>
<p>Instead of direct evaluation, GofCens actually estimates the quantity by the following:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Chat%7BD%7D_n%20=%20%5Csqrt%7Bn%7D%5Csup_%7B0%5Cleq%20t%5Cleq%20t_m%7D%0A%20%20%5Cunderbrace%7B%5Chat%7BS%7D_n(t)%7D_%7B%5Cdisplaystyle%5Cfrac%7B%5Chat%7BS%7D_n(t)+S_0(t;%5Ctheta%5E*)%7D%7B2%7D%7D%0A%20%20%5Ccdot%0A%20%20%5Cint_0%5Et%0A%20%20%20%20%5Cunderbrace%7B%5Cfrac%7BS_0(s;%5Ctheta%5E*)%7D%7B%5Chat%7BS%7D_n(s)%7D%7D_%7B%5Cdisplaystyle%5Csqrt%7B%5Ctilde%7BG%7D(s%5E-)%7D%7D%0A%20%20%20%20%5C;%0A%20%20%20%20%5Cunderbrace%7Bd%5C!%5Cleft%5B%5Chat%7B%5CLambda%7D_n(s)-%5CLambda_0(s;%5Ctheta%5E*)%5Cright%5D%7D_%7B%5Cdisplaystyle%0A%20%20%20%20%20%20%5Clog%5Cfrac%7B%5Chat%7BS%7D_n(t_%7Bj-1%7D)%7D%7B%5Chat%7BS%7D_n(t_j)%7D%0A%20%20%20%20%20%20%5C;-%5C;%0A%20%20%20%20%20%20%5Clog%5Cfrac%7BS_0(t_%7Bj-1%7D;%5Ctheta%5E*)%7D%7BS_0(t_j;%5Ctheta%5E*)%7D%7D%0A"></p>
<table class="caption-top table">
<caption>Mapping of Equation (1) terms to <code>KScens</code> code</caption>
<colgroup>
<col style="width: 20%">
<col style="width: 25%">
<col style="width: 32%">
<col style="width: 23%">
</colgroup>
<thead>
<tr class="header">
<th>Equation (1) term</th>
<th>Math formula</th>
<th>Approximated Equation (1) term</th>
<th>R Code</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><img src="https://latex.codecogs.com/png.latex?d%5Chat%5CLambda_n(t_j)"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdisplaystyle%5Csum_%7Bk=0%7D%5E%7Bd_j-1%7D%5Cfrac%7B1%7D%7Br_j-k%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Clog%5Cdfrac%7B%5Chat%7BS%7D_n(t_%7Bj-1%7D)%7D%7B%5Chat%7BS%7D_n(t_j)%7D"></td>
<td><code>log(svbefor / survT$surv)</code></td>
</tr>
<tr class="even">
<td><img src="https://latex.codecogs.com/png.latex?d%5CLambda_0(t_j)"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5CLambda_0(t_j;%5Ctheta%5E*)-%5CLambda_0(t_%7Bj-1%7D;%5Ctheta%5E*)"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Clog%5Cdfrac%7BS_0(t_%7Bj-1%7D;%5Ctheta%5E*)%7D%7BS_0(t_j;%5Ctheta%5E*)%7D"></td>
<td><code>log(SofT0(prev) / SofT0(curr))</code></td>
</tr>
<tr class="odd">
<td><img src="https://latex.codecogs.com/png.latex?%5CDelta%5Ctilde%5CLambda_C(t_j)"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdisplaystyle%5Csum_%7Bk=0%7D%5E%7Bc_j-1%7D%5Cfrac%7B1%7D%7Br_j-d_j-k%7D"></td>
<td>—</td>
<td><code>aux2[i]</code></td>
</tr>
<tr class="even">
<td><img src="https://latex.codecogs.com/png.latex?%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cexp%5C!%5Cleft(-%5Cdisplaystyle%5Csum_%7Bi%3Cj%7D%5CDelta%5Ctilde%5CLambda_C(t_i)%5Cright)"></td>
<td>—</td>
<td><code>alfatj</code></td>
</tr>
<tr class="odd">
<td><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7B%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7B%5Cexp%5C!%5Cleft(-%5Cdisplaystyle%5Csum_%7Bi%3Cj%7D%5Csum_%7Bk=0%7D%5E%7Bc_i-1%7D%5Cfrac%7B1%7D%7Br_i-d_i-k%7D%5Cright)%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7BS_0(s)%7D%7B%5Chat%7BS%7D_n(s)%7D"></td>
<td><code>sqrt(alfatj)</code></td>
</tr>
<tr class="even">
<td><img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7BS_0(s)%7D%7B%5Chat%7BS%7D_n(s)%7D%5Ccdot%20d%5B%5Chat%5CLambda_n-%5CLambda_0%5D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7B%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)%7D%5Ccdot%5Cbigl(%5CDelta%5Chat%5CLambda_n(t_j)-%5CDelta%5CLambda_0(t_j)%5Cbigr)"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7B%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)%7D%5C!%5Cleft(%5Clog%5Cdfrac%7B%5Chat%7BS%7D_n(t_%7Bj-1%7D)%7D%7B%5Chat%7BS%7D_n(t_j)%7D-%5Clog%5Cdfrac%7BS_0(t_%7Bj-1%7D)%7D%7BS_0(t_j)%7D%5Cright)"></td>
<td><code>Btj - Atj</code></td>
</tr>
<tr class="odd">
<td><img src="https://latex.codecogs.com/png.latex?%5Cint_0%5E%7Bt_k%7D%5Cdfrac%7BS_0%7D%7B%5Chat%7BS%7D_n%7D%5C,d%5B%5Chat%5CLambda_n-%5CLambda_0%5D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdisplaystyle%5Csum_%7Bt_j%5Cleq%20t_k%7D%5Csqrt%7B%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)%7D%5Ccdot%5Cbigl(%5CDelta%5Chat%5CLambda_n-%5CDelta%5CLambda_0%5Cbigr)(t_j)"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdisplaystyle%5Csum_%7Bt_j%5Cleq%20t_k%7D%5Csqrt%7B%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)%7D%5C!%5Cleft(%5Clog%5Cdfrac%7B%5Chat%7BS%7D_n(t_%7Bj-1%7D)%7D%7B%5Chat%7BS%7D_n(t_j)%7D-%5Clog%5Cdfrac%7BS_0(t_%7Bj-1%7D)%7D%7BS_0(t_j)%7D%5Cright)"></td>
<td><code>Bvec[k] - Avec[k]</code></td>
</tr>
<tr class="even">
<td><img src="https://latex.codecogs.com/png.latex?%5Chat%7BS%7D_n(t)"></td>
<td><img src="https://latex.codecogs.com/png.latex?e%5E%7B-%5Chat%5CLambda_n(t)%7D"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7B%5Chat%7BS%7D_n(t)+S_0(t;%5Ctheta%5E*)%7D%7B2%7D"></td>
<td><code>(survT$surv + SofT0(stimes,...)) / 2</code></td>
</tr>
<tr class="odd">
<td><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bn%7D%5Ccdot%5Csup%7C%5Ccdot%7C"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bn%7D%5Cdisplaystyle%5Csup_%7B0%5Cleq%20t%5Cleq%20t_m%7D%7C%5Ccdot%7C"></td>
<td><img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bn%7D%5Ccdot%5Csup_%7Bt%7D%5Cleft%5Clvert%5Cdfrac%7B%5Chat%7BS%7D_n(t%5E-)+S_0(t)%7D%7B2%7D%5Ccdot%5Csum_%7Bt_j%5Cleq%20t%7D%5Csqrt%7B%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)%7D%5C,%5CDelta%5Cright%5Crvert"></td>
<td><code>sqrt(n) * max(abs(c(Yl, Y, Ym)))</code></td>
</tr>
</tbody>
</table>
<blockquote class="blockquote">
<p><strong>Key substitution.</strong> The inner weight <img src="https://latex.codecogs.com/png.latex?S_0(s)/%5Chat%7BS%7D_n(s)"> is replaced by <img src="https://latex.codecogs.com/png.latex?%5Csqrt%7B%5Ctilde%7BG%7D(t_%7Bj-1%7D%5E-)%7D"> (<code>sqrt(alfatj)</code>). This is the variance-stabilising choice: with <img src="https://latex.codecogs.com/png.latex?w=%5Csqrt%7BG%7D"> the asymptotic variance <img src="https://latex.codecogs.com/png.latex?%5Cint%20w%5E2%5C,d%5CLambda_0/(S%5Ccdot%20G)"> reduces to <img src="https://latex.codecogs.com/png.latex?%5Cint%20d%5CLambda_0/S">, removing <img src="https://latex.codecogs.com/png.latex?G"> entirely and making the Brownian bridge null distribution hold independently of the censoring pattern.</p>
</blockquote>
<p>The proof of the estimate involves stochastic calculus and goes beyond the scope of the blog. But here’s the exact R code and Python code.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">sumSurvT <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">survfit</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">Surv</span>(dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>times, dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cens) <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;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stype =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ctype =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb7-2">survT <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">times =</span> sumSurvT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>time, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">surv =</span> sumSurvT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>surv))</span>
<span id="cb7-3">stimes <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> survT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>time</span>
<span id="cb7-4">m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(stimes)</span>
<span id="cb7-5">svbefor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, survT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>surv[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>m])</span>
<span id="cb7-6">aux2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</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>m, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) {</span>
<span id="cb7-7">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (sumSurvT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n.censor[i] <span class="sc" 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-8">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</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> (sumSurvT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n.risk[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sumSurvT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n.event[i] <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;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(sumSurvT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n.censor[i] <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;">1</span>))))</span>
<span id="cb7-9">  } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> {</span>
<span id="cb7-10">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb7-11">  }</span>
<span id="cb7-12">})</span>
<span id="cb7-13">alfatj <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumsum</span>(aux2))[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>m])</span>
<span id="cb7-14">Atj <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, alfatj[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>m])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb7-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">SofT0</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, stimes[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>m]), alphahat, gammahat, muhat, betahat) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb7-16">        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">SofT0</span>(stimes, alphahat, gammahat, muhat, betahat))</span>
<span id="cb7-17">Atj[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.nan</span>(Atj)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb7-18">Avec <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumsum</span>(Atj)</span>
<span id="cb7-19">Btj <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, alfatj[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>m])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(svbefor <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> survT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>surv)</span>
<span id="cb7-20">Btj[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.nan</span>(Btj)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb7-21">Bvec <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumsum</span>(Btj)</span>
<span id="cb7-22">Yl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n) <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;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (svbefor <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">SofT0</span>(stimes, alphahat, gammahat, muhat, betahat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb7-23">  (Avec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, Bvec[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>m])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(Bvec <span class="sc" 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="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="cb7-24">Y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span>  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n) <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;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (survT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>surv <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">SofT0</span>(stimes, alphahat, gammahat, muhat, betahat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb7-25">  (Avec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Bvec) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(Bvec <span class="sc" 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="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="cb7-26">Ym <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n) <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;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (survT<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>surv[m] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">SofT0</span>(stimes[m], alphahat, gammahat, muhat,</span>
<span id="cb7-27">                                           betahat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (Avec[m] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Bvec[m])</span>
<span id="cb7-28">A <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(Yl, Y, Ym)))</span>
<span id="cb7-29"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(A)</span></code></pre></div></div>
<p>Now the Python re-implementation:</p>
<div id="0a5ea481" 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="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;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb8-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> lifelines <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> KaplanMeierFitter</span>
<span id="cb8-3"></span>
<span id="cb8-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> modified_ks_statistic(times, events, param_survival_fn):</span>
<span id="cb8-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb8-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Fleming et al. (1980) modified KS statistic for right-censored data,</span></span>
<span id="cb8-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    replicating GofCens::KScens (stype=2, ctype=2).</span></span>
<span id="cb8-8"></span>
<span id="cb8-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    times  : observed durations</span></span>
<span id="cb8-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    events : 1 = event, 0 = censored</span></span>
<span id="cb8-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    param_survival_fn : vectorized callable S0(t)</span></span>
<span id="cb8-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb8-13">    times <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(times, dtype<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>
<span id="cb8-14">    events <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(events, dtype<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;">int</span>)</span>
<span id="cb8-15">    n <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>(times)</span>
<span id="cb8-16"></span>
<span id="cb8-17">    et <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KaplanMeierFitter().fit(times, events).event_table</span>
<span id="cb8-18">    et <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[et.index <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="cb8-19">    stimes   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et.index.values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb8-20">    n_risk   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"at_risk"</span>].values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb8-21">    n_event  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"observed"</span>].values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb8-22">    n_censor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"censored"</span>].values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb8-23">    m <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>(stimes)</span>
<span id="cb8-24"></span>
<span id="cb8-25">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Nelson-Aalen, Fleming-Harrington tie correction (ctype=2) ---</span></span>
<span id="cb8-26">    dH <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([</span>
<span id="cb8-27">        np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</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> (n_risk[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.arange(n_event[i]))) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_event[i] <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="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="cb8-28">        <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>(m)</span>
<span id="cb8-29">    ])</span>
<span id="cb8-30">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># stype=2: S_hat = exp(-H_hat) -- strictly positive, unlike product-limit</span></span>
<span id="cb8-31">    surv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>np.cumsum(dH))</span>
<span id="cb8-32">    svbefor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>], surv[:<span 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="cb8-33"></span>
<span id="cb8-34">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- estimated censoring survival G_hat(t_{j-1}) ---</span></span>
<span id="cb8-35">    denom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n_risk <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_event</span>
<span id="cb8-36">    hazard_incre <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros(m)</span>
<span id="cb8-37">    <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>(m):</span>
<span id="cb8-38">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_censor[i] <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="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> denom[i] <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="cb8-39">            d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> denom[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.arange(n_censor[i])</span>
<span id="cb8-40">            hazard_incre[i] <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>(<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> d[d <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="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">any</span>(d <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="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="cb8-41">    G_hat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>], np.cumsum(hazard_incre)))[:<span 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="cb8-42"></span>
<span id="cb8-43">    w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>], G_hat[:<span 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="cb8-44"></span>
<span id="cb8-45">    S0_s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(param_survival_fn(stimes), dtype<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>
<span id="cb8-46">    S0_p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(param_survival_fn(np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>], stimes[:<span 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>]))), dtype<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>
<span id="cb8-47"></span>
<span id="cb8-48">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> safe_log_ratio(num, den):</span>
<span id="cb8-49">        out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros_like(num)</span>
<span id="cb8-50">        ok <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (num <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="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> (den <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="cb8-51">        out[ok] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.log(num[ok] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> den[ok])</span>
<span id="cb8-52">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out</span>
<span id="cb8-53"></span>
<span id="cb8-54">    Avec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.cumsum(w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> safe_log_ratio(S0_p, S0_s))     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># parametric H0</span></span>
<span id="cb8-55">    Bvec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.cumsum(w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> safe_log_ratio(svbefor, surv))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># empirical  H_hat</span></span>
<span id="cb8-56"></span>
<span id="cb8-57">    ind <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (Bvec <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>).astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb8-58">    Yl <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (svbefor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> S0_s) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (Avec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>], Bvec[:<span 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> ind</span>
<span id="cb8-59">    Y  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (surv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> S0_s) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (Avec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Bvec) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ind</span>
<span id="cb8-60">    Ym <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (surv[<span 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> S0_s[<span 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> (Avec[<span 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> Bvec[<span 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="cb8-61"></span>
<span id="cb8-62">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(np.concatenate((Yl, Y, [Ym])))))</span></code></pre></div></div>
</details>
</div>
</div>
</div>
</div>
<div class="callout callout-style-default callout-note callout-titled" title="Python Implementation of Modified KS Test">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-4-contents" aria-controls="callout-4" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Python Implementation of Modified KS Test
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-4" class="callout-4-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div id="02e45ad8" 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="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;">"""</span></span>
<span id="cb9-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">Full modified Kolmogorov-Smirnov test for right-censored data,</span></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">replicating GofCens::KScens (Besalu et al. 2025, The R Journal 17(3)).</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb9-5"><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="cb9-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> lifelines <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> (KaplanMeierFitter, ExponentialFitter, WeibullFitter,LogNormalFitter, LogLogisticFitter)</span>
<span id="cb9-7"><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> norm</span>
<span id="cb9-8"></span>
<span id="cb9-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ---------------------------------------------------------------- Step 2</span></span>
<span id="cb9-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fit_distribution(durations, event_observed, distribution):</span>
<span id="cb9-11">    dist_register <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb9-12">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'exponential'</span>: ExponentialFitter(),</span>
<span id="cb9-13">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'weibull'</span>: WeibullFitter(),</span>
<span id="cb9-14">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lognormal'</span>: LogNormalFitter(),</span>
<span id="cb9-15">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'loglogistic'</span>: LogLogisticFitter(),</span>
<span id="cb9-16">    }</span>
<span id="cb9-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> distribution <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> dist_register:</span>
<span id="cb9-18">        <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="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Unknown distribution '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>distribution<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;">'. Choose from </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;">list</span>(dist_register)<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-19">    fitter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dist_register[distribution]</span>
<span id="cb9-20">    fitter.fit(durations<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>durations, event_observed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>event_observed)</span>
<span id="cb9-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> fitter</span>
<span id="cb9-22"></span>
<span id="cb9-23"></span>
<span id="cb9-24"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _S0_from_fitter(fitter):</span>
<span id="cb9-25">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Any fitted lifelines univariate fitter already knows its own S(t)."""</span></span>
<span id="cb9-26">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> t: fitter.survival_function_at_times(np.asarray(t, dtype<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>)).values</span>
<span id="cb9-27"></span>
<span id="cb9-28"></span>
<span id="cb9-29"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ---------------------------------------------------------------- Step 3</span></span>
<span id="cb9-30"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> modified_ks_statistic(times, events, param_survival_fn):</span>
<span id="cb9-31">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb9-32"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Fleming et al. (1980) modified KS statistic for right-censored data,</span></span>
<span id="cb9-33"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    replicating GofCens::KScens (stype=2, ctype=2).</span></span>
<span id="cb9-34"></span>
<span id="cb9-35"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    times  : observed durations</span></span>
<span id="cb9-36"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    events : 1 = event, 0 = censored</span></span>
<span id="cb9-37"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    param_survival_fn : vectorized callable S0(t)</span></span>
<span id="cb9-38"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb9-39">    times <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(times, dtype<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>
<span id="cb9-40">    events <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(events, dtype<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;">int</span>)</span>
<span id="cb9-41">    n <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>(times)</span>
<span id="cb9-42"></span>
<span id="cb9-43">    et <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KaplanMeierFitter().fit(times, events).event_table</span>
<span id="cb9-44">    et <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[et.index <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="cb9-45">    stimes   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et.index.values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb9-46">    n_risk   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"at_risk"</span>].values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb9-47">    n_event  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"observed"</span>].values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb9-48">    n_censor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> et[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"censored"</span>].values.astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb9-49">    m <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>(stimes)</span>
<span id="cb9-50"></span>
<span id="cb9-51">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Nelson-Aalen, Fleming-Harrington tie correction (ctype=2) ---</span></span>
<span id="cb9-52">    dH <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([</span>
<span id="cb9-53">        np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</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> (n_risk[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.arange(n_event[i]))) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_event[i] <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="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="cb9-54">        <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>(m)</span>
<span id="cb9-55">    ])</span>
<span id="cb9-56">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># stype=2: S_hat = exp(-H_hat) -- strictly positive, unlike product-limit</span></span>
<span id="cb9-57">    surv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>np.cumsum(dH))</span>
<span id="cb9-58">    svbefor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>], surv[:<span 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-59"></span>
<span id="cb9-60">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- estimated censoring survival G_hat(t_{j-1}) ---</span></span>
<span id="cb9-61">    denom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n_risk <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_event</span>
<span id="cb9-62">    hazard_incre <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros(m)</span>
<span id="cb9-63">    <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>(m):</span>
<span id="cb9-64">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n_censor[i] <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="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> denom[i] <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="cb9-65">            d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> denom[i] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.arange(n_censor[i])</span>
<span id="cb9-66">            hazard_incre[i] <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>(<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> d[d <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="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">any</span>(d <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="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="cb9-67">    G_hat <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>], np.cumsum(hazard_incre)))[:<span 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-68"></span>
<span id="cb9-69">    w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>], G_hat[:<span 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-70"></span>
<span id="cb9-71">    S0_s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(param_survival_fn(stimes), dtype<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>
<span id="cb9-72">    S0_p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(param_survival_fn(np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>], stimes[:<span 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>]))), dtype<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>
<span id="cb9-73"></span>
<span id="cb9-74">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> safe_log_ratio(num, den):</span>
<span id="cb9-75">        out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.zeros_like(num)</span>
<span id="cb9-76">        ok <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (num <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="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> (den <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="cb9-77">        out[ok] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.log(num[ok] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> den[ok])</span>
<span id="cb9-78">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out</span>
<span id="cb9-79"></span>
<span id="cb9-80">    Avec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.cumsum(w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> safe_log_ratio(S0_p, S0_s))     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># parametric H0</span></span>
<span id="cb9-81">    Bvec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.cumsum(w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> safe_log_ratio(svbefor, surv))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># empirical  H_hat</span></span>
<span id="cb9-82"></span>
<span id="cb9-83">    ind <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (Bvec <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>).astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>)</span>
<span id="cb9-84">    Yl <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (svbefor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> S0_s) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (Avec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.concatenate(([<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>], Bvec[:<span 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> ind</span>
<span id="cb9-85">    Y  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (surv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> S0_s) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (Avec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Bvec) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ind</span>
<span id="cb9-86">    Ym <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (surv[<span 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> S0_s[<span 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> (Avec[<span 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> Bvec[<span 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-87"></span>
<span id="cb9-88">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(np.concatenate((Yl, Y, [Ym])))))</span>
<span id="cb9-89"></span>
<span id="cb9-90"></span>
<span id="cb9-91"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ---------------------------------------------------------------- Step 4.1 / 4.2 helpers</span></span>
<span id="cb9-92"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _simulate_event_times(fitter, distribution, u):</span>
<span id="cb9-93">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Inverse-CDF draw from the fitted null, using each fitter's own parameterization."""</span></span>
<span id="cb9-94">    u <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(u, dtype<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>
<span id="cb9-95">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> distribution <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;">'exponential'</span>:</span>
<span id="cb9-96">        <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>fitter.lambda_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.log(u)</span>
<span id="cb9-97">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> distribution <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;">'weibull'</span>:</span>
<span id="cb9-98">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> fitter.lambda_ <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>np.log(u)) <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> fitter.rho_)</span>
<span id="cb9-99">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> distribution <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;">'lognormal'</span>:</span>
<span id="cb9-100">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.exp(fitter.mu_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> fitter.sigma_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> norm.ppf(<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> u))</span>
<span id="cb9-101">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> distribution <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;">'loglogistic'</span>:</span>
<span id="cb9-102">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> fitter.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> u) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> u) <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> fitter.beta_)</span>
<span id="cb9-103">    <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="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"No sampler registered for '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>distribution<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-104"></span>
<span id="cb9-105"></span>
<span id="cb9-106"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _sample_from_km(km_fitter, u):</span>
<span id="cb9-107">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Inverse-transform sampling from a fitted KaplanMeierFitter step function."""</span></span>
<span id="cb9-108">    surv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> km_fitter.survival_function_</span>
<span id="cb9-109">    t_grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> surv.index.values</span>
<span id="cb9-110">    S_vals <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> surv.iloc[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].values</span>
<span id="cb9-111">    target <span 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.asarray(u, dtype<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>
<span id="cb9-112">    idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.searchsorted(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>S_vals, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>target, side<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;">"left"</span>)</span>
<span id="cb9-113">    out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.full_like(target, np.inf, dtype<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>
<span id="cb9-114">    valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(t_grid)</span>
<span id="cb9-115">    out[valid] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> t_grid[idx[valid]]</span>
<span id="cb9-116">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out</span>
<span id="cb9-117"></span>
<span id="cb9-118"></span>
<span id="cb9-119"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ---------------------------------------------------------------- Steps 4-5</span></span>
<span id="cb9-120"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> ks_censored_test(durations, event_observed, distribution, B<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>, rng<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="cb9-121">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb9-122"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Modified KS test for right-censored data (Fleming et al. 1980 / GofCens::KScens).</span></span>
<span id="cb9-123"></span>
<span id="cb9-124"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns dict with D_obs, p_value, fitted params, and the bootstrap distribution.</span></span>
<span id="cb9-125"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb9-126">    durations <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(durations, dtype<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>
<span id="cb9-127">    event_observed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.asarray(event_observed, dtype<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;">int</span>)</span>
<span id="cb9-128">    n <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>(durations)</span>
<span id="cb9-129">    rng <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.default_rng() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> rng <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> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> rng</span>
<span id="cb9-130"></span>
<span id="cb9-131">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Step 2: fit null model, Step 3: observed statistic ---</span></span>
<span id="cb9-132">    fitter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fit_distribution(durations, event_observed, distribution)</span>
<span id="cb9-133">    S0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _S0_from_fitter(fitter)</span>
<span id="cb9-134">    D_obs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modified_ks_statistic(durations, event_observed, S0)</span>
<span id="cb9-135"></span>
<span id="cb9-136">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- reverse-KM estimate of the censoring distribution (fixed across replicates) ---</span></span>
<span id="cb9-137">    censKM <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KaplanMeierFitter().fit(durations, <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> event_observed)</span>
<span id="cb9-138"></span>
<span id="cb9-139">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Step 4: bootstrap ---</span></span>
<span id="cb9-140">    D_boot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.empty(B)</span>
<span id="cb9-141">    b <span 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-142">    attempts <span 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-143">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> B <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> attempts <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="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> B:</span>
<span id="cb9-144">        attempts <span 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-145">        u_t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rng.uniform(size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n)</span>
<span id="cb9-146">        u_c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> rng.uniform(size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n)</span>
<span id="cb9-147">        T_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _simulate_event_times(fitter, distribution, u_t)</span>
<span id="cb9-148">        C_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _sample_from_km(censKM, u_c)</span>
<span id="cb9-149">        X_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.minimum(T_b, C_b)</span>
<span id="cb9-150">        delta_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (T_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> C_b).astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)</span>
<span id="cb9-151"></span>
<span id="cb9-152">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> delta_b.<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;">&lt;</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;"># refit needs at least a couple of events</span></span>
<span id="cb9-153">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb9-154">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb9-155">            fitter_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fit_distribution(X_b, delta_b, distribution)</span>
<span id="cb9-156">            S0_b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _S0_from_fitter(fitter_b)</span>
<span id="cb9-157">            D_boot[b] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modified_ks_statistic(X_b, delta_b, S0_b)</span>
<span id="cb9-158">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span>:</span>
<span id="cb9-159">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb9-160">        b <span 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-161"></span>
<span id="cb9-162">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> B:</span>
<span id="cb9-163">        D_boot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> D_boot[:b]</span>
<span id="cb9-164"></span>
<span id="cb9-165">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Step 5: p-value (Besalu et al. 2025, matches paper's +1/+1 correction) ---</span></span>
<span id="cb9-166">    p_value <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>(D_obs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> D_boot) <span 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="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(D_boot) <span 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-167"></span>
<span id="cb9-168">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {</span>
<span id="cb9-169">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"D_obs"</span>: D_obs,</span>
<span id="cb9-170">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p_value"</span>: p_value,</span>
<span id="cb9-171">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"params"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(fitter.params_),</span>
<span id="cb9-172">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n_boot"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(D_boot),</span>
<span id="cb9-173">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"D_boot"</span>: D_boot,</span>
<span id="cb9-174">    }</span></code></pre></div></div>
</details>
</div>
</div>
</div>
</div>
</section>
<section id="case-study" class="level2">
<h2 class="anchored" data-anchor-id="case-study">Case Study</h2>
<p>We now apply the concepts discussed above to a real-world dataset which contains survival times and censoring information for patients with a specific medical condition. Three distributions, Weibull, Log-normal, and Log-logistic, are fit to the data, and their goodness-of-fit is assessed using both graphs and the modified KS test (p-value printed next to the plot title). According to the KS test results, Weibull and Log-normal don’t seem to be a good fit despite their moderate graphical fit. The Log-logistic distribution seems plausible.</p>
<div id="7213f60f" class="cell" data-execution_count="9">
<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="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> gof_assessment(durations, event_observed, distribution, B<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>, ax<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>, rng<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="cb10-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fit once, share</span></span>
<span id="cb10-3">    fitter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fit_distribution(durations, event_observed, distribution)</span>
<span id="cb10-4"></span>
<span id="cb10-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># KS test (uses fitter internally via ks_censored_test, but you could</span></span>
<span id="cb10-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># refactor to accept a pre-fitted fitter to avoid the second fit)</span></span>
<span id="cb10-7">    result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ks_censored_test(durations, event_observed, distribution, B<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>B, rng<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>rng)</span>
<span id="cb10-8"></span>
<span id="cb10-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># probability plot, passing the fitter so the theoretical line is drawn</span></span>
<span id="cb10-10">    ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> probability_plot(durations, event_observed, distribution, fitter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>fitter, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb10-11"></span>
<span id="cb10-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># annotate the plot with the p-value</span></span>
<span id="cb10-13">    ax.set_title(</span>
<span id="cb10-14">        <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>distribution<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>capitalize()<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;"> Probability Plot  "</span></span>
<span id="cb10-15">        <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"(KS p = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>result[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'p_value'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, n_boot=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>result[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'n_boot'</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="cb10-16">    )</span>
<span id="cb10-17"></span>
<span id="cb10-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ax</span></code></pre></div></div>
</details>
</div>
<div id="fig-gof-comparison" class="quarto-layout-panel">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-gof-comparison-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 33.3%;justify-content: flex-start;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="weibull_gof.png" class="lightbox" data-gallery="quarto-lightbox-gallery-6" title="Weibull"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/weibull_gof.png" class="img-fluid figure-img"></a></p>
<figcaption>Weibull</figcaption>
</figure>
</div>
</div>
<div class="quarto-layout-cell" style="flex-basis: 33.3%;justify-content: flex-start;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="lognormal_gof.png" class="lightbox" data-gallery="quarto-lightbox-gallery-7" title="Log-normal"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/lognormal_gof.png" class="img-fluid figure-img"></a></p>
<figcaption>Log-normal</figcaption>
</figure>
</div>
</div>
<div class="quarto-layout-cell" style="flex-basis: 33.3%;justify-content: flex-start;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="loglogistic_gof.png" class="lightbox" data-gallery="quarto-lightbox-gallery-8" title="Log-logistic"><img src="https://changruiraywang.com/blog/2026-08-02-survival-parametric/loglogistic_gof.png" class="img-fluid figure-img"></a></p>
<figcaption>Log-logistic</figcaption>
</figure>
</div>
</div>
</div>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-gof-comparison-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;6: Goodness-of-fit comparison: probability plots with KS test p-values
</figcaption>
</figure>
</div>
<p>It is worth noting that so far everything has been performed on the dataset level, no individual variables are considered yet. Passing a population-level goodness-of-fit test doesn’t guarantee the same result for the population’s subgroup based on the values of variables. That’s where we will pick next — building and validating Proportional Hazards (PH) and Accelerated Failure Time (AFT) models.</p>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In this post, we discussed several commonly used parametric distributions — exponential, Weibull, Gompertz, log-normal, and log-logistic, and applied both a graphical probability plot and a modified KS test.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li>F. E. Harrell Jr.&nbsp;<a href="https://link.springer.com/book/10.1007/978-3-319-19425-7">Regression Modeling Strategies: With Applications to Linear Models, Logistic and Ordinal Regression, and Survival Analysis.</a> Springer, 2015.</li>
<li>D. G. Kleinbaum, M. Klein. <a href="https://link.springer.com/book/10.1007/978-1-4419-6646-9">Survival Analysis: A Self-Learning Text, Third Edition.</a> Springer, 2012.</li>
<li>T. R. Fleming, J. R. O’Fallon, P. C. O’Brien, D. P. Harrington. <a href="https://doi.org/10.2307/2556114">Modified Kolmogorov-Smirnov test procedures with application to arbitrarily right-censored data.</a> Biometrics, 36(4), 607-625, 1980.</li>
<li>B. Efron. Censored data and the bootstrap. Journal of the American Statistical Association, 76(374), 312-319, 1981.</li>
<li>M. Besalú, K. Langohr, M. Francisco, A. Garcia-Fernández, G. Gómez Melis. <a href="https://upcommons.upc.edu/server/api/core/bitstreams/fa25282f-4444-443e-b6a5-c4baf28cfe01/content">R package GofCens: Goodness-of-Fit Methods for Right-Censored Data.</a> The R Journal, 17(3), 100-124, 2025.</li>
<li>K. Langohr, M. Besalú, M. Francisco, A. Garcia, G. Gómez. <a href="https://cran.r-project.org/package=GofCens">GofCens: Goodness-of-Fit Methods for Right-Censored Data.</a> R package, CRAN.</li>
<li>A. Garcia. <a href="https://github.com/ArnauGarciaGRBIO/GofCens">GofCens source repository.</a> GitHub.</li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Survival Analysis - Part 2 - Parametric
Distributions.”</span> August 2. <a href="https://changruiraywang.com/blog/2026-08-02-survival-parametric/">https://changruiraywang.com/blog/2026-08-02-survival-parametric/</a>.
</div></div></section></div> ]]></description>
  <category>Statistics</category>
  <guid>https://changruiraywang.com/blog/2026-08-02-survival-parametric/</guid>
  <pubDate>Sun, 02 Aug 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2026-08-02-survival-parametric/sidebar.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Survival Analysis - Part 1 - Fundamentals</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction---what-is-survival-analysis" class="level2">
<h2 class="anchored" data-anchor-id="introduction---what-is-survival-analysis">Introduction - What is Survival Analysis?</h2>
<p>In business analytics, we often need to answer questions about when an event is likely to occur. Take a subscription-based business, for instance — leadership might want to know things like:</p>
<ol type="1">
<li>How many customers are expected to churn in the next x days?</li>
<li>What is a given customer’s expected remaining ‘lifetime’ with the company?</li>
<li>Which customers are at the highest risk of leaving?</li>
<li>What’s the probability that a new customer stays subscribed for at least x days?</li>
<li>What is the expected lifetime of a new customer, or a new customer segment?</li>
</ol>
<p>These are all versions of the same underlying question: how long until something happens? That’s precisely what survival analysis is built to study — the expected duration of time until an event of interest occurs. Because so many real-world problems can be framed this way, survival analysis shows up across a wide range of domains — clinical prognosis, product reliability and failure testing, employee turnover, and customer churn, among others.</p>
<p>The dataset used to answer these questions is called <strong>time-to-event data</strong>, and the analysis is called <strong>survival analysis</strong>, or <strong>Time-to-Event Analysis</strong>. The word “survival” here refers to the time until the event occurs, not necessarily literal survival.</p>
</section>
<section id="time-to-event-data" class="level2">
<h2 class="anchored" data-anchor-id="time-to-event-data">Time-to-Event Data</h2>
<p>When working with time-to-event data, one often defines the <strong>beginning</strong> and <strong>end</strong> of the event of interest. For example, in subscription-based customer churn data, the beginning of the observation is a customer’s subscription date, and the end of their observation is when they cancel their subscription.</p>
<p>In most real-world cases, however, we don’t get to observe the beginning and end of the event for all instances. For example, when analyzing employee turnover and time to termination, we often get employees that are still active at the end of the analysis period, thus we don’t know when they will actually leave yet. We only know that their true event time is at least as long as some observed value — not the exact value itself. Such feature of time-to-event data is called <strong>censoring</strong>. When the true event time is not observed, we call the cases <strong>right-censored</strong>. When we don’t know the beginning date of an observation, we call those cases <strong>left-censored</strong>.</p>
<p>There are also cases where we wish to study a population that have already survived to a certain point, and we only observe those who have survived past that point. This is called <strong>truncation</strong>. For example, if we only analyze customers who have been subscribed for at least 6 months, then any customer who churns before 6 months is truncated from our dataset.</p>
<p>For this blog and series, we focus on right-censoring, assuming no left-censoring. For more information on censoring and truncation, check Klein and Moeschberger’s <a href="https://link.springer.com/book/10.1007/b97377">Survival Analysis: Techniques for Censored and Truncated Data.</a></p>
<section id="visualizing-time-to-event-data" class="level3">
<h3 class="anchored" data-anchor-id="visualizing-time-to-event-data">Visualizing Time-to-Event Data</h3>
<p>One way to visualize time-to-event data is to plot each individual’s observed duration: a horizontal line running from the beginning to their observed event time or censored time. The plot below uses synthetic data generated for a medical study where patients’ outcomes are tracked. The <strong>✕</strong> marks subjects whose line ends because they actually died — we observed their true event time exactly. The <strong>○</strong> marks subjects whose line ends for some other reason — the study ended, they were lost to follow-up, or they were discharged — while they were still alive.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="event_plot_all.png" class="lightbox" data-gallery="quarto-lightbox-gallery-1" title="Event plot: each line is one subject’s observed follow-up time, ending in either death (✕) or censoring (○)."><img src="https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/event_plot_all.png" width="500" height="600" alt="Event plot: each line is one subject’s observed follow-up time, ending in either death (✕) or censoring (○)." class="figure-img"></a></p>
<figcaption>Event plot: each line is one subject’s observed follow-up time, ending in either death (✕) or censoring (○).</figcaption>
</figure>
</div>
</section>
</section>
<section id="describing-event-time-distribution" class="level2">
<h2 class="anchored" data-anchor-id="describing-event-time-distribution">Describing Event Time Distribution</h2>
<p>In the language of statistics, the goal of survival analysis is to describe the distribution of time-to-event T. Think of the distribution of the observed length of the individual timelines on the event plot above. However, instead of studying the probability density function (PDF), survival analysis deals with functions derived from the PDF:</p>
<ul>
<li>Survival Function</li>
<li>Hazard Function</li>
<li>Cumulative Hazard Function</li>
</ul>
<section id="survival-function" class="level3">
<h3 class="anchored" data-anchor-id="survival-function">Survival Function</h3>
<p>The Survival Function is the probability that the event time T is greater than a specific value t:</p>
<p><img src="https://latex.codecogs.com/png.latex?S(t)%20=%20%5CPr(T%3Et)%20=%201%20-%20F(t)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?F(t)"> is the Cumulative Distribution Function of event time t.</p>
<p>One feature of the survival function is that it is a non-increasing function of time. As time goes on, the probability of surviving past that time decreases. The survival function starts at 1 (100% survival) at time 0 and approaches 0 as time goes to infinity.</p>
<p>The area under the survival function is called the <strong>expected lifetime</strong>, which is defined as: <img src="https://latex.codecogs.com/png.latex?%0AE%5BT%5D%20=%20%5Cint_0%5E%5Cinfty%20S(t)%5C,%20dt%0A"></p>
<p>It’s worth noting that <img src="https://latex.codecogs.com/png.latex?S(t)%20=%20P(T%20%3E%20t)"> is an unconditional probability — the probability of surviving past time <img src="https://latex.codecogs.com/png.latex?t">, measured from the very start.</p>
<p>In practice, survival analysis usually deals with subjects who have <em>already</em> survived up to some point, and we want to know their chances of continuing to survive further. This requires a conditional version of <img src="https://latex.codecogs.com/png.latex?S(t)">. Suppose a subject has survived up to time <img src="https://latex.codecogs.com/png.latex?s">. The probability that they survive to some later time <img src="https://latex.codecogs.com/png.latex?t%20%3E%20s"> is defined by conditional probability:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(T%20%3E%20t%20%5Cmid%20T%20%3E%20s)%20=%20%5Cfrac%7BP(T%20%3E%20t,%20T%20%3E%20s)%7D%7BP(T%20%3E%20s)%7D%0A"></p>
<p>Since <img src="https://latex.codecogs.com/png.latex?t%20%3E%20s">, the event <img src="https://latex.codecogs.com/png.latex?%5C%7BT%20%3E%20t%5C%7D"> already implies <img src="https://latex.codecogs.com/png.latex?%5C%7BT%20%3E%20s%5C%7D"> — if you’ve survived past <img src="https://latex.codecogs.com/png.latex?t">, you’ve certainly survived past <img src="https://latex.codecogs.com/png.latex?s"> too. So the joint event <img src="https://latex.codecogs.com/png.latex?%5C%7BT%20%3E%20t,%20T%20%3E%20s%5C%7D"> simplifies to just <img src="https://latex.codecogs.com/png.latex?%5C%7BT%20%3E%20t%5C%7D">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(T%20%3E%20t%20%5Cmid%20T%20%3E%20s)%20=%20%5Cfrac%7BP(T%20%3E%20t)%7D%7BP(T%20%3E%20s)%7D%20=%20%5Cfrac%7BS(t)%7D%7BS(s)%7D%0A"></p>
<p>This is the <strong>conditional survival property</strong>: the probability of surviving to time <img src="https://latex.codecogs.com/png.latex?t">, given survival to an earlier time <img src="https://latex.codecogs.com/png.latex?s">, is simply the ratio of the two unconditional survival probabilities. Intuitively, <img src="https://latex.codecogs.com/png.latex?S(s)"> represents “how much of the population is still at risk by time <img src="https://latex.codecogs.com/png.latex?s">,” and <img src="https://latex.codecogs.com/png.latex?S(t)"> represents “how much is still at risk by time <img src="https://latex.codecogs.com/png.latex?t">” — dividing one by the other rescales the probability to the population that’s actually still under observation at time <img src="https://latex.codecogs.com/png.latex?s">.</p>
</section>
<section id="hazard-function" class="level3">
<h3 class="anchored" data-anchor-id="hazard-function">Hazard Function</h3>
<p>Besides the distribution of time to event, we also need a function to describe how likely an event can occur at a certain point of time. The ‘risk’ of the event occurence might increase, remain constant, or decrease over time. In survival analysis, such function is called the Hazard Function, which is defined as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Clambda(t)%20=%20%5Clim_%7Bh%20%5Cto%200%7D%20%5Cfrac%7BP%5Cbig(%5Ctext%7Bevent%20in%20%7D%20%5Bt,%20t+h)%20%5Cmid%20%5Ctext%7Bno%20event%20in%20%7D%20%5B0,t)%5Cbig)%7D%7Bh%7D%0A"></p>
<p>The hazard function is a measure of the instant <strong>potential</strong> of an event occurring at time t, thus it can be graphed over time. Note that the hazard function can take on any shape to reflect the changing risk over time. The chart below illustrates four shapes of the hazard function.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="hazard_shapes.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2" title="Differenct Shapes of Hazard Function"><img src="https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/hazard_shapes.png" class="img-fluid figure-img" alt="Differenct Shapes of Hazard Function"></a></p>
<figcaption>Differenct Shapes of Hazard Function</figcaption>
</figure>
</div>
<p>With different assumptions on the shape of the hazard functions, different types of analysis can be performed. We will examine those techniques in more detail in later posts.</p>
<section id="hazard-function-and-poisson-process" class="level4">
<h4 class="anchored" data-anchor-id="hazard-function-and-poisson-process">Hazard Function and Poisson Process</h4>
<p>When I first learned about the hazard function, I was confused as to why it takes the form of a probability divided by a time interval. The limit of such ratio did not make complete sense to me. In most of the tutorials, the hazard function was introduced as a rate without much explanation on why it takes such form. After learning about Poisson Process, I realized the hazard function is actually equivalent to the rate parameter of the Poisson distribution.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<p>The hazard function arises from a Poisson process, a stochastic process that describes event occurrence. Given a stream of events that arrive at random times starting at <img src="https://latex.codecogs.com/png.latex?t=0">, let <img src="https://latex.codecogs.com/png.latex?N_t"> denote the number of arrivals that occur by time <img src="https://latex.codecogs.com/png.latex?t">, that is, the number of events in <img src="https://latex.codecogs.com/png.latex?%5B0,t%5D">. For instance, <img src="https://latex.codecogs.com/png.latex?N_t"> might be the number of text messages received up to time <img src="https://latex.codecogs.com/png.latex?t">. Intuitively speaking, a Poisson process can be thought of as a Poisson distribution with rate parameter <img src="https://latex.codecogs.com/png.latex?%5Clambda"> applied over a time period <img src="https://latex.codecogs.com/png.latex?t">. That is, for all <img src="https://latex.codecogs.com/png.latex?t%20%3E%200">, <img src="https://latex.codecogs.com/png.latex?N_t"> has a Poisson distribution with parameter <img src="https://latex.codecogs.com/png.latex?%5Clambda%20t">. The Poisson PMF gives the probability of exactly <img src="https://latex.codecogs.com/png.latex?k"> events in time <img src="https://latex.codecogs.com/png.latex?t">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(N(t)%20=%20k)%20=%20%5Cfrac%7B(%5Clambda%20t)%5Ek%20e%5E%7B-%5Clambda%20t%7D%7D%7Bk!%7D%0A"></p>
<p>When <img src="https://latex.codecogs.com/png.latex?k%20=%200">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(N(t)%20=%200)%20=%20%5Cfrac%7B(%5Clambda%20t)%5E0%20e%5E%7B-%5Clambda%20t%7D%7D%7B0!%7D%20=%20e%5E%7B-%5Clambda%20t%7D%0A"></p>
<p>To understand how <img src="https://latex.codecogs.com/png.latex?N_t"> behaves locally, consider a short interval of length <img src="https://latex.codecogs.com/png.latex?h">. Since a Poisson process has stationary increments, the count over any interval of length <img src="https://latex.codecogs.com/png.latex?h"> has the same distribution as <img src="https://latex.codecogs.com/png.latex?N(t)"> evaluated at <img src="https://latex.codecogs.com/png.latex?t%20=%20h">. So we can rewrite the above as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(N(h)%20=%200)%20=%20e%5E%7B-%5Clambda%20h%7D%0A"></p>
<p>Now take the Taylor series of <img src="https://latex.codecogs.com/png.latex?e%5E%7B-%5Clambda%20h%7D"> around <img src="https://latex.codecogs.com/png.latex?h%20=%200"> and group everything from the quadratic term onward:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Ae%5E%7B-%5Clambda%20h%7D%20=%201%20-%20%5Clambda%20h%20+%20%5Cunderbrace%7B%5Cleft(%5Cfrac%7B(%5Clambda%20h)%5E2%7D%7B2!%7D%20-%20%5Cfrac%7B(%5Clambda%20h)%5E3%7D%7B3!%7D%20+%20%5Ccdots%5Cright)%7D_%7B%5Ctext%7Bthis%20is%20%7D%20o(h)%7D%0A"></p>
<p>which gives:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(N(h)%20=%200)%20=%20e%5E%7B-%5Clambda%20h%7D%20=%201%20-%20%5Clambda%20h%20+%20o(h)%0A"></p>
<p>The “little-o of <img src="https://latex.codecogs.com/png.latex?h">” function, <img src="https://latex.codecogs.com/png.latex?o(h)">, means it shrinks faster than <img src="https://latex.codecogs.com/png.latex?h"> itself as <img src="https://latex.codecogs.com/png.latex?h%20%5Cto%200">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Clim_%7Bh%20%5Cto%200%7D%20%5Cfrac%7Bo(h)%7D%7Bh%7D%20=%200%0A"></p>
<p>When <img src="https://latex.codecogs.com/png.latex?k%20=%201">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(N(h)%20=%201)%20=%20e%5E%7B-%5Clambda%20h%7D%5Clambda%20h%20=%20(1%20-%20%5Clambda%20h%20+%20o(h))%5Clambda%20h%20=%20%5Clambda%20h%20-%20%5Clambda%5E2%20h%5E2%20+%20%5Clambda%20h%20%5Ccdot%20o(h)%0A"></p>
<p>It turns out that <img src="https://latex.codecogs.com/png.latex?%5Clambda%5E2%20h%5E2"> is also <img src="https://latex.codecogs.com/png.latex?o(h)">, since <img src="https://latex.codecogs.com/png.latex?%5Clim_%7Bh%20%5Cto%200%7D%20%5Cfrac%7B%5Clambda%5E2%20h%5E2%7D%7Bh%7D%20=%200">. Therefore, we have:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(N(h)%20=%201)%20=%20%5Clambda%20h%20+%20o(h)%0A"></p>
<p>Dividing both sides by <img src="https://latex.codecogs.com/png.latex?h"> and letting <img src="https://latex.codecogs.com/png.latex?h%20%5Cto%200">, we get:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Clim_%7Bh%20%5Cto%200%7D%5Cfrac%7BP(N(h)%20=%201)%7D%7Bh%7D%20=%20%5Clambda%20+%20%5Cunderbrace%7B%5Clim_%7Bh%20%5Cto%200%7D%5Cfrac%7Bo(h)%7D%7Bh%7D%7D_%7B0%7D%20=%20%5Clambda%0A"></p>
<p>This shows that <img src="https://latex.codecogs.com/png.latex?%5Clambda"> is actually the instantaneous rate of a single event occurring in an infinitesimally small window — which is what we’d want a “rate” to mean.</p>
<p>The formulation above assumes a constant rate <img src="https://latex.codecogs.com/png.latex?%5Clambda">, giving the same instantaneous probability of an event regardless of how much time has already elapsed. In many real applications, though, the instantaneous event rate does depend on how much time has passed — machines wear out, patients age, components fatigue, thus a time-varying rate <img src="https://latex.codecogs.com/png.latex?%5Clambda(t)">.</p>
<p>Formally, <img src="https://latex.codecogs.com/png.latex?%5Clambda(t)"> is defined as the instantaneous rate of an event occurring at time <img src="https://latex.codecogs.com/png.latex?t">, given that no event has occurred before <img src="https://latex.codecogs.com/png.latex?t">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Clambda(t)%20=%20%5Clim_%7Bh%20%5Cto%200%7D%20%5Cfrac%7BP%5Cbig(%5Ctext%7Bevent%20in%20%7D%20%5Bt,%20t+h)%20%5Cmid%20%5Ctext%7Bno%20event%20in%20%7D%20%5B0,t)%5Cbig)%7D%7Bh%7D%0A"></p>
<p>This conditional, instantaneous rate (risk of an event) is precisely the hazard function — and it’s this conditioning on survival up to time <img src="https://latex.codecogs.com/png.latex?t"> that distinguishes it from simply restating <img src="https://latex.codecogs.com/png.latex?%5Clambda">. In the constant-rate case, the hazard is flat: <img src="https://latex.codecogs.com/png.latex?%5Clambda(t)%20=%20%5Clambda"> for all <img src="https://latex.codecogs.com/png.latex?t">, recovering exactly the Poisson process we started with. In general, <img src="https://latex.codecogs.com/png.latex?%5Clambda(t)"> can rise, fall, or vary in shape over time, which is what makes it a flexible building block for modeling real event processes — failures, relapses, deaths — where risk changes over the course of the process.</p>
</div>
</div>
</div>
</section>
</section>
<section id="cumulative-hazard-function" class="level3">
<h3 class="anchored" data-anchor-id="cumulative-hazard-function">Cumulative Hazard Function</h3>
<p>The hazard function <img src="https://latex.codecogs.com/png.latex?%5Clambda(t)"> tells us the instantaneous risk of an event at a single moment in time, but on its own it doesn’t tell us how much risk has built up over a time interval. To answer that, we integrate the hazard over time to get the cumulative hazard function:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5CLambda(t)%20=%20%5Cint_0%5Et%20%5Clambda(u)%5C,%20du%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5CLambda(t)"> accumulates those infinitesimal risks into a single running total up to time <img src="https://latex.codecogs.com/png.latex?t"> — much like how integrating speed over time gives you total distance traveled, rather than an instantaneous rate.</p>
</section>
<section id="relationship-between-the-survival-function-and-hazard-function" class="level3">
<h3 class="anchored" data-anchor-id="relationship-between-the-survival-function-and-hazard-function">Relationship between the Survival Function and Hazard Function</h3>
<p>There’s actually a close connection between the survival function <img src="https://latex.codecogs.com/png.latex?S(t)"> and the hazard function <img src="https://latex.codecogs.com/png.latex?%5Clambda(t)">.</p>
<p>Back to the hazard function: <img src="https://latex.codecogs.com/png.latex?%0A%5Clambda(t)%20=%20%5Clim_%7Bh%20%5Cto%200%7D%20%5Cfrac%7BP%5Cbig(%5Ctext%7Bevent%20in%20%7D%20%5Bt,%20t+h)%20%5Cmid%20%5Ctext%7Bno%20event%20in%20%7D%20%5B0,t)%5Cbig)%7D%7Bh%7D%0A"></p>
<p>which in the language of probability means: <img src="https://latex.codecogs.com/png.latex?%0A%5Clambda(t)%20=%20%5Clim_%7Bh%20%5Cto%200%7D%20%5Cfrac%7B%5CPr(t%20%3C%20T%20%5Cleq%20t+h%20%5Cmid%20T%20%3E%20t)%7D%7Bh%7D%0A"></p>
<p>which under the law of conditional probability becomes: <img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign%7D%0A%5Clambda(t)%20&amp;=%20%5Clim_%7Bu%20%5Cto%200%7D%20%5Cfrac%7B%5CPr(t%20%3C%20T%20%5Cleq%20t+h)/%5CPr(T%20%3E%20t)%7D%7Bh%7D%20%5C%5C%0A&amp;=%20%5Clim_%7Bu%20%5Cto%200%7D%20%5Cfrac%7B%5BF(t+u)%20-%20F(t)%5D/u%7D%7BS(t)%7D%20%5C%5C%0A&amp;=%20%5Cfrac%7B%5Cpartial%20F(t)/%5Cpartial%20t%7D%7BS(t)%7D%20%5C%5C%0A&amp;=%20%5Cfrac%7Bf(t)%7D%7BS(t)%7D,%0A%5Cend%7Balign%7D%0A"></p>
<p>Based on the result above, we can get a relationship between the survival function and cumulative hazard function. As a stepping stone, let’s take derivative of the log of <img src="https://latex.codecogs.com/png.latex?S(t)"> with respect to <img src="https://latex.codecogs.com/png.latex?t">: <img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Cpartial%20%5Clog%20S(t)%7D%7B%5Cpartial%20t%7D%20=%20%5Cfrac%7B%5Cpartial%20S(t)/%5Cpartial%20t%7D%7BS(t)%7D%20=%20-%5Cfrac%7Bf(t)%7D%7BS(t)%7D%20=%20-%5Clambda(t)%0A"></p>
<p>Integrating both sides, we get: <img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign%7D%0A%5Cint_0%5Et%20%5Clambda(v)%5C,%20dv%20&amp;=%20-%5Clog%20S(t).%20%5C%5C%5B6pt%5D%0A%5CLambda(t)%20&amp;=%20-%5Clog%20S(t),%20%5C%5C%5B6pt%5D%0AS(t)%20&amp;=%20%5Cexp%5B-%5CLambda(t)%5D.%0A%5Cend%7Balign%7D%0A"></p>
<p>Such connection allows us to estimate the survival function <img src="https://latex.codecogs.com/png.latex?S(t)"> from the cumulative hazard function <img src="https://latex.codecogs.com/png.latex?%5CLambda(t)">, and vice versa.</p>
</section>
<section id="how-are-these-functions-used-in-practice" class="level3">
<h3 class="anchored" data-anchor-id="how-are-these-functions-used-in-practice">How are these functions used in practice?</h3>
<p>Now that we have defined the survival function, hazard function, and cumulative hazard function, we can now revisit the questions that survival analysis is built to answer:</p>
<ol type="1">
<li>What’s the probability that a new customer will stay for at least x days?</li>
</ol>
<p>This is simply the survival function evaluated at x: <img src="https://latex.codecogs.com/png.latex?S(x)%20=%20P(T%20%3E%20x)">.</p>
<ol start="2" type="1">
<li>What is the expected lifetime of a new customer/group?</li>
</ol>
<p>This is the expected lifetime: <img src="https://latex.codecogs.com/png.latex?E%5BT%5D%20=%20%5Cint_0%5E%5Cinfty%20S(t)%5C,%20dt"></p>
<ol start="3" type="1">
<li>How many existing customers are expected to leave in the next x days?</li>
</ol>
<p>This is the conditional probability of leaving in the next x days, given that they have already survived to today. If a customer has already survived to time s, then the probability of leaving in the next x days is:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(T%20%3E%20s+x%20%5Cmid%20T%20%3E%20s)%20=%20%5Cfrac%7BP(T%20%3E%20s+x)%7D%7BP(T%20%3E%20s)%7D%20=%20%5Cfrac%7BS(s+x)%7D%7BS(s)%7D"></p>
<p>The expected number of customers leaving in the next x days can be estimated by the sum of these conditional probabilities across all customers who have survived to today.</p>
<ol start="4" type="1">
<li>What is a customer’s expected remaining ‘lifetime’ given that they have already survived to today?</li>
</ol>
<p>Here we need the expected remaining time until the event occurs, given that the subject has already survived to time <img src="https://latex.codecogs.com/png.latex?t_0">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign%7D%0Ae(t_0)%20&amp;=%20%5Cmathbb%7BE%7D%5BT%20-%20t_0%20%5Cmid%20T%20%3E%20t_0%5D%20%5C%5C%5B4pt%5D%0A&amp;=%20%5Cint_0%5E%5Cinfty%20P(T%20-%20t_0%20%3E%20u%20%5Cmid%20T%20%3E%20t_0)%5C,%20du%20%5C%5C%5B4pt%5D%0A&amp;=%20%5Cint_0%5E%5Cinfty%20%5Cfrac%7BS(t_0+u)%7D%7BS(t_0)%7D%5C,%20du%20%5C%5C%5B4pt%5D%0A&amp;=%20%5Cfrac%7B1%7D%7BS(t_0)%7D%20%5Cint_0%5E%5Cinfty%20S(t_0+u)%5C,%20du%20%5C%5C%5B4pt%5D%0A&amp;=%20%5Cfrac%7B1%7D%7BS(t_0)%7D%20%5Cint_%7Bt_0%7D%5E%5Cinfty%20S(t)%5C,%20dt%0A%5Cend%7Balign%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?T"> is the event time, <img src="https://latex.codecogs.com/png.latex?t_0"> is the time already survived, and <img src="https://latex.codecogs.com/png.latex?T-t_0"> is the remaining time. The expected remaining lifetime can be calculated if the survival function is known, or estimated based on simulations. The latter provides more information about the distribution of remaining lifetime, which can be used to calculate percentiles rather than a single expected value.</p>
<p>To get a distribution of remaining lifetime, we can use the conditional survival property to get samples:</p>
<p>We know that the conditional probability of surviving <img src="https://latex.codecogs.com/png.latex?u"> units of time beyond <img src="https://latex.codecogs.com/png.latex?t_0">, given survival to <img src="https://latex.codecogs.com/png.latex?t_0">, is: <img src="https://latex.codecogs.com/png.latex?%0AP(T%20-%20t_0%20%3E%20u%20%5Cmid%20T%20%3E%20t_0)%20=%20%5Cfrac%7BS(t_0+u)%7D%7BS(t_0)%7D%0A"></p>
<p>To get <img src="https://latex.codecogs.com/png.latex?u">, we can do the following: <img src="https://latex.codecogs.com/png.latex?%0AS(t_0+u)=%20S(t_0)%20P(T%20-%20t_0%20%3E%20u%20%5Cmid%20T%20%3E%20t_0)%0A"></p>
<p>Now if we denote the probability <img src="https://latex.codecogs.com/png.latex?P"> with a uniform random variable <img src="https://latex.codecogs.com/png.latex?U%20%5Csim%20Uniform(0,1)">, and use the relationship between the survival function and the cumulative hazard function, we can get a sample of <img src="https://latex.codecogs.com/png.latex?u"> by solving the following equation:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cexp%5B-%5CLambda(t_0+u)%5D%20=%20S(t_0)%20%5Ccdot%20U%20%5Cimplies%20u%20=%20%5CLambda%5E%7B-1%7D%5B-%5Clog(S(t_0)%20%5Ccdot%20U)%5D%20-%20t_0%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5CLambda%5E%7B-1%7D"> denotes the inverse of the cumulative hazard function.</p>
<p>The result abvove shows that the distribution of remaining lifetime can be obtained by sampling from a uniform distribution and transforming it through the cumulative hazard function. This allows us to generate a distribution of remaining lifetimes for subjects who have already survived to a certain time point, providing valuable insights into their expected future survival.</p>
</section>
</section>
<section id="non-parametric-estimates-of-survival-and-hazard-functions" class="level2">
<h2 class="anchored" data-anchor-id="non-parametric-estimates-of-survival-and-hazard-functions">Non-parametric Estimates of Survival and Hazard Functions</h2>
<p>So far everything we’ve discussed has been in terms of the <em>true</em>, or <em>theoretical</em> survival and hazard functions, which are unknown in practice. When working with real data, we need to estimate these functions from observed event times and censoring information.There are broadly two approaches to estimating survival and hazard functions: parametric and non-parametric. Parametric methods assume a specific distribution for the event times (e.g., exponential, Weibull, log-normal), while non-parametric methods make no such assumptions and instead rely on the observed data to estimate the functions directly.</p>
<p>In this post, we focus on non-parametric estimation, which is particularly useful when we have little prior knowledge about the underlying distribution of event times or when we want to avoid imposing potentially incorrect assumptions.</p>
<p>The most common non-parametric estimators of the survival and hazard functions are the <strong>Kaplan-Meier estimator</strong> and the <strong>Nelson-Aalen estimator</strong>, respectively. Both estimators are built on the same underlying data — the observed event times and the number of subjects at risk at each event time — but they combine that information in different ways to estimate different quantities.</p>
<section id="kaplan-meier-estimator" class="level3">
<h3 class="anchored" data-anchor-id="kaplan-meier-estimator">Kaplan-Meier Estimator</h3>
<p>The idea of the Kaplan-Meier estimator is chaining together conditional survival probabilities across small intervals with the conditional survival property.</p>
<p>Suppose we observe <img src="https://latex.codecogs.com/png.latex?k"> distinct event times <img src="https://latex.codecogs.com/png.latex?t_1%20%3C%20t_2%20%3C%20%5Ccdots%20%3C%20t_k"> in our data (censored observations don’t contribute event times, but they do affect who remains at risk). At each event time <img src="https://latex.codecogs.com/png.latex?t_i">, define:</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?n_i"> = the number of subjects still at risk just before <img src="https://latex.codecogs.com/png.latex?t_i"> (i.e., alive and not yet censored)</li>
<li><img src="https://latex.codecogs.com/png.latex?d_i"> = the number of events that occur exactly at <img src="https://latex.codecogs.com/png.latex?t_i"></li>
</ul>
<p>The idea is to estimate the <em>conditional</em> probability of surviving past <img src="https://latex.codecogs.com/png.latex?t_i">, given survival up to just before <img src="https://latex.codecogs.com/png.latex?t_i">, using the simplest possible empirical estimate — the observed proportion:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cwidehat%7BP%7D(T%20%3E%20t_i%20%5Cmid%20T%20%5Cgeq%20t_i)%20=%20%5Cfrac%7Bn_i%20-%20d_i%7D%7Bn_i%7D%0A"></p>
<p>Note that censoring is naturally handled here: censored subjects are included in <img src="https://latex.codecogs.com/png.latex?n_i"> up until their censoring time, but they never contribute to <img src="https://latex.codecogs.com/png.latex?d_i"> since they don’t experience the event.</p>
<p>Now here’s where the conditional survival property does its work. Since <img src="https://latex.codecogs.com/png.latex?S(t)"> can be built up as a chain of conditional survival probabilities across each interval between consecutive event times, we estimate the overall survival function as a product of these per-interval conditional probabilities, for all event times up to and including <img src="https://latex.codecogs.com/png.latex?t">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cwidehat%7BS%7D(t)%20=%20%5Cprod_%7Bi:%5C,%20t_i%20%5Cleq%20t%7D%20%5Cfrac%7Bn_i%20-%20d_i%7D%7Bn_i%7D%0A"></p>
<p>So with the Kaplan-Meier estimator, each factor in the product represents the estimated probability of “surviving this particular interval,” and multiplying them together — exactly as the conditional survival identity <img src="https://latex.codecogs.com/png.latex?P(T%3Et%5Cmid%20T%3Es)%20=%20S(t)/S(s)"> suggests.</p>
<p>Here’s a simple example to illustrate the Kaplan-Meier estimator:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="kaplan_meier_estimator.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3" title="Kaplan-Meier Estimator"><img src="https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/kaplan_meier_estimator.png" class="img-fluid figure-img" alt="Kaplan-Meier Estimator"></a></p>
<figcaption>Kaplan-Meier Estimator</figcaption>
</figure>
</div>
<p>As visualized, the Kaplan-Meier curve is a step function that drops at each observed event time, with the size of the drop determined by the number of events and the number at risk at that time.</p>
<p>There are also confidence intervals that can be constructed around the Kaplan-Meier estimate, often using Greenwood’s formula to estimate the variance of the survival function. For more details on the Kaplan-Meier estimator, check Kalbfleisch and Prentice’s <a href="https://onlinelibrary.wiley.com/doi/book/10.1002/9781118032985">The Statistical Analysis of Failure Time Data.</a></p>
</section>
<section id="nelson-aalen-estimator" class="level3">
<h3 class="anchored" data-anchor-id="nelson-aalen-estimator">Nelson-Aalen Estimator</h3>
<p>Where the Kaplan-Meier estimator targets <img src="https://latex.codecogs.com/png.latex?S(t)"> directly, the <strong>Nelson-Aalen estimator</strong> estimates the cumulative hazard <img src="https://latex.codecogs.com/png.latex?%5CLambda(t)"> instead — using the exact same at-risk bookkeeping (<img src="https://latex.codecogs.com/png.latex?n_i">, <img src="https://latex.codecogs.com/png.latex?d_i">) but combining it differently.</p>
<p>Recall that the cumulative hazard is defined as an integral over the instantaneous hazard:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5CLambda(t)%20=%20%5Cint_0%5Et%20%5Clambda(u)%5C,%20du%0A"></p>
<p>Just as Kaplan-Meier estimates a conditional survival probability at each event time and combines them multiplicatively, Nelson-Aalen estimates the hazard at each event time and combines them additively. At each observed event time <img src="https://latex.codecogs.com/png.latex?t_i">, the natural empirical estimate of the instantaneous hazard — the “fraction of the at-risk population that experienced the event right now” — is simply:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cwidehat%7B%5Clambda%7D(t_i)%20=%20%5Cfrac%7Bd_i%7D%7Bn_i%7D%0A"></p>
<p>Since the cumulative hazard is a running sum of instantaneous hazard contributions, the Nelson-Aalen estimator sums these per-interval hazard estimates across all event times up to and including <img src="https://latex.codecogs.com/png.latex?t">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cwidehat%7B%5CLambda%7D(t)%20=%20%5Csum_%7Bi:%5C,%20t_i%20%5Cleq%20t%7D%20%5Cfrac%7Bd_i%7D%7Bn_i%7D%0A"></p>
<p>Each term <img src="https://latex.codecogs.com/png.latex?d_i/n_i"> can be thought of as a small “chunk” of accumulated risk contributed at <img src="https://latex.codecogs.com/png.latex?t_i"> — subjects who are still at risk but experience the event right then. Summing these chunks across time builds up the total accumulated hazard, exactly mirroring how the continuous-time integral <img src="https://latex.codecogs.com/png.latex?%5Cint_0%5Et%20%5Clambda(u)%5C,du"> accumulates instantaneous risk. As a result, the NA estimator is a <strong>discrete step function</strong> — it only jumps at observed event times within the node and is flat between them:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Chat%7BH%7D(t)%20=%20%5Cbegin%7Bcases%7D%0A0%20&amp;%20t%20%3C%20t_1%20%5C%5C%0A%5Cdfrac%7Bd_1%7D%7Bn_1%7D%20&amp;%20t_1%20%5Cleq%20t%20%3C%20t_2%20%5C%5C%5B6pt%5D%0A%5Cdfrac%7Bd_1%7D%7Bn_1%7D%20+%20%5Cdfrac%7Bd_2%7D%7Bn_2%7D%20&amp;%20t_2%20%5Cleq%20t%20%3C%20t_3%20%5C%5C%5B6pt%5D%0A%5Cvdots%20&amp;%20%5C%5C%0A%5Cdisplaystyle%5Csum_%7Bj=1%7D%5E%7BK%7D%5Cfrac%7Bd_j%7D%7Bn_j%7D%20&amp;%20t%20%5Cgeq%20t_K%0A%5Cend%7Bcases%7D%0A"></p>
<p>Here’s an example of the Nelson-Aalen estimator:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="nelson_aalen_estimator.png" class="lightbox" data-gallery="quarto-lightbox-gallery-4" title="Nelson-Aalen Estimator"><img src="https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/nelson_aalen_estimator.png" class="img-fluid figure-img" alt="Nelson-Aalen Estimator"></a></p>
<figcaption>Nelson-Aalen Estimator</figcaption>
</figure>
</div>
</section>
<section id="kaplan-meier-vs.-nelson-aalen" class="level3">
<h3 class="anchored" data-anchor-id="kaplan-meier-vs.-nelson-aalen">Kaplan-Meier vs.&nbsp;Nelson-Aalen</h3>
<p>Both estimators are built from the same underlying data — the risk sets <img src="https://latex.codecogs.com/png.latex?n_i"> and event counts <img src="https://latex.codecogs.com/png.latex?d_i"> at each observed event time — but they combine that information in two structurally different ways:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cwidehat%7BS%7D_%7BKM%7D(t)%20=%20%5Cprod_%7Bi:%5C,%20t_i%20%5Cleq%20t%7D%20%5Cleft(1%20-%20%5Cfrac%7Bd_i%7D%7Bn_i%7D%5Cright)%0A%5Cqquad%5Ctext%7Bvs.%7D%5Cqquad%0A%5Cwidehat%7B%5CLambda%7D_%7BNA%7D(t)%20=%20%5Csum_%7Bi:%5C,%20t_i%20%5Cleq%20t%7D%20%5Cfrac%7Bd_i%7D%7Bn_i%7D%0A"></p>
<p>Recall the identity connecting <img src="https://latex.codecogs.com/png.latex?S(t)"> and <img src="https://latex.codecogs.com/png.latex?%5CLambda(t)"> that we derived earlier:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AS(t)%20=%20%5Cexp%5B-%5CLambda(t)%5D%0A"></p>
<p>If we plug the Nelson-Aalen estimate of <img src="https://latex.codecogs.com/png.latex?%5CLambda(t)"> into this identity, we get an alternative estimator of the survival function:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cwidehat%7BS%7D_%7BNA%7D(t)%20=%20%5Cexp%5Cleft%5B-%5Csum_%7Bi:%5C,%20t_i%20%5Cleq%20t%7D%20%5Cfrac%7Bd_i%7D%7Bn_i%7D%5Cright%5D%0A"></p>
<p>This is sometimes called the <strong>Fleming-Harrington estimator</strong>. It turns out to be numerically very close to <img src="https://latex.codecogs.com/png.latex?%5Cwidehat%7BS%7D_%7BKM%7D(t)"> in most practical settings, and the two converge to the same quantity asymptotically. Below is a comparison of the Kaplan-Meier and Nelson-Aalen estimates on the same dataset:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="km_vs_na.png" class="lightbox" data-gallery="quarto-lightbox-gallery-5" title="Comparison of Kaplan-Meier and Nelson-Aalen Estimators"><img src="https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/km_vs_na.png" class="img-fluid figure-img" alt="Comparison of Kaplan-Meier and Nelson-Aalen Estimators"></a></p>
<figcaption>Comparison of Kaplan-Meier and Nelson-Aalen Estimators</figcaption>
</figure>
</div>
<p>In practice, Kaplan-Meier is the more commonly reported estimator of <img src="https://latex.codecogs.com/png.latex?S(t)">, while Nelson-Aalen is generally preferred as the estimator of <img src="https://latex.codecogs.com/png.latex?%5CLambda(t)">.</p>
</section>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In this blog post, we introduced the fundamentals of survival analysis, including the key concepts of time-to-event data, survival function, hazard function, and cumulative hazard function, and explored their relationships. We also discussed non-parametric estimation methods, specifically the Kaplan-Meier and Nelson-Aalen estimators, which allow us to estimate survival and hazard functions from observed data. The non-parametric estimations serve as a foundation for more advanced survival analysis techniques, which we will explore in subsequent posts.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li>R. M. Dobrow. <a href="https://onlinelibrary.wiley.com/doi/book/10.1002/9781118740712">Introduction to Stochastic Processes with R.</a> Wiley, 2016.</li>
<li>J. D. Singer, J. B. Willett. <a href="https://academic.oup.com/book/41753">Applied Longitudinal Data Analysis: Modeling Change and Event Occurrence.</a> Oxford University Press, 2003.</li>
<li>F. E. Harrell Jr.&nbsp;<a href="https://link.springer.com/book/10.1007/978-3-319-19425-7">Regression Modeling Strategies: With Applications to Linear Models, Logistic and Ordinal Regression, and Survival Analysis.</a> Springer, 2015.</li>
<li>D. G. Kleinbaum, M. Klein. <a href="https://link.springer.com/book/10.1007/978-1-4419-6646-9">Survival Analysis: A Self-Learning Text, Third Edition.</a> Springer, 2012.</li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Survival Analysis - Part 1 -
Fundamentals.”</span> July 19. <a href="https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/">https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/</a>.
</div></div></section></div> ]]></description>
  <category>Statistics</category>
  <guid>https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/</guid>
  <pubDate>Sun, 19 Jul 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2026-07-19-survival-fundamentals/sidebar.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Bayesian Optimization - Acquisition Functions</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>In the first post of the series, we introduced the concept of Gaussian Processes. In this post, we will focus on the acquisition functions, which are another key component of Bayesian Optimization.</p>
<p>Think back to Minesweeper. When you click on a square, the surrounding squares reveal how many mines are adjacent to it. For the next click, you can either click on the squares around the revealed ones, or explore the squares that are far away from the revealed ones. In other words, you can either exploit the information you have, or explore the unknown. This is the same exploration-exploitation dilemma that Bayesian Optimization formalizes through acquisition functions.</p>
<p>With Bayesian Optimization, as we draw and evaluate new samples, we update our belief about the underlying function and try to decide where to sample next. Acquisition functions are the tools that help us make this decision. They are designed to balance the trade-off between exploration and exploitation, guiding the search for the global optimum of the objective function.</p>
</section>
<section id="acquisition-functions" class="level2">
<h2 class="anchored" data-anchor-id="acquisition-functions">Acquisition Functions</h2>
<p>In this post, we will take a deep dive into three common acquisition functions: Upper Confidence Bound (UCB), Probability of Improvement (PI), and Expected Improvement (EI). We will also implement them in Python.</p>
<section id="upper-confidence-bound-ucb" class="level3">
<h3 class="anchored" data-anchor-id="upper-confidence-bound-ucb">Upper Confidence Bound (UCB)</h3>
<p>The idea of UCB is straightforward. It selects the next sample based on the upper confidence bound of the posterior distribution, while considering the trade-off between exploration and exploitation. The upper confidence bound is defined as:</p>
<p><img src="https://latex.codecogs.com/png.latex?a(x;%20%5Clambda)%20=%20%5Cmu(x)%20+%20%5Clambda%5Csigma(x)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cmu(x)"> is the mean of the posterior distribution, <img src="https://latex.codecogs.com/png.latex?%5Csigma(x)"> is the standard deviation of the posterior distribution, and <img src="https://latex.codecogs.com/png.latex?%5Clambda"> is a hyperparameter that controls the trade-off between exploration and exploitation. A larger value of <img src="https://latex.codecogs.com/png.latex?%5Clambda"> encourages exploration, while a smaller value encourages exploitation.</p>
</section>
<section id="probability-of-improvement-pi" class="level3">
<h3 class="anchored" data-anchor-id="probability-of-improvement-pi">Probability of Improvement (PI)</h3>
<p>While UCB considers both the mean and the uncertainty of the posterior distribution, it does not consider the probability of improvement over the current best estimate. Whether the sample gives a better observation is hard to know. The Probability of Improvement (PI) acquisition function addresses this by selecting the next sample based on the probability of improving the current best estimate.</p>
<p>Suppose the best solution we have so far is <img src="https://latex.codecogs.com/png.latex?f(x%5E*)"> achieved at <img src="https://latex.codecogs.com/png.latex?x%5E*">. For our next draw of sample at <img src="https://latex.codecogs.com/png.latex?x">, we would like to know how likely it is that there is an improvement over the current best result. Define the improvement as:</p>
<p><img src="https://latex.codecogs.com/png.latex?I(x)%20=%20%5Cmax(f(x)-f(x%5E*),0)"></p>
<p>The formulation says that, if the new observation <img src="https://latex.codecogs.com/png.latex?f(x)"> has a better result than the current best observation <img src="https://latex.codecogs.com/png.latex?f(x%5E*)">, <img src="https://latex.codecogs.com/png.latex?I(x)"> will be the amount of improvement; if the new observation is no better than the current best observation, and hence <img src="https://latex.codecogs.com/png.latex?f(x)-f(x%5E*)%3C0">, <img src="https://latex.codecogs.com/png.latex?I(x)"> would be zero.</p>
<p>We can then define the probability of improvement as:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(I(x)%3E0)%20=%20P(f(x)-f(x%5E*)%3E0)"></p>
<p>The idea of the probability of improvement acquisition function is to go with the sample that maximizes the probability of improvement. But how is the probability calculated? Recall that each point in a Gaussian Process is assumed to follow a normal distribution, which means:</p>
<p><img src="https://latex.codecogs.com/png.latex?f(x)%20%5Csim%20%5Cmathcal%7BN%7D(%5Cmu(x),%20%5Csigma%5E2(x))"></p>
<p>The probability that the next sample has a better result than the current best result is:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(f(x)%3Ef(x%5E*))"></p>
<div id="fig-pi" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-pi-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="prob_improvement.jpg" class="lightbox" data-gallery="quarto-lightbox-gallery-1" title="Figure&nbsp;1: Source: E. Kamperi. Acquisition functions in Bayesian Optimization. 2021."><img src="https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/prob_improvement.jpg" class="img-fluid figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-pi-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: <em>Source: E. Kamperi. <a href="https://ekamperi.github.io/machine%20learning/2021/06/11/acquisition-functions.html#upper-confidence-bound-ucb">Acquisition functions in Bayesian Optimization.</a> 2021.</em>
</figcaption>
</figure>
</div>
<p>With <img src="https://latex.codecogs.com/png.latex?f(x)"> standardized, the expression can be rewritten as:</p>
<p><img src="https://latex.codecogs.com/png.latex?P%5Cleft(%5Cdfrac%7Bf(x)-%5Cmu(x)%7D%7B%5Csigma(x)%7D%3E%5Cdfrac%7Bf(x%5E*)-%5Cmu(x)%7D%7B%5Csigma(x)%7D%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7Bf(x)-%5Cmu(x)%7D%7B%5Csigma(x)%7D=z"> is a standard normal distribution <img src="https://latex.codecogs.com/png.latex?z%20%5Csim%20%5Cmathcal%7BN%7D(0,1)">.</p>
<p>Therefore, the probability of improvement is:</p>
<p><img src="https://latex.codecogs.com/png.latex?P%5Cleft(z%3E%5Cdfrac%7Bf(x%5E*)-%5Cmu(x)%7D%7B%5Csigma(x)%7D%5Cright)%20=%201-%5CPhi%5Cleft(%5Cdfrac%7Bf(x%5E*)-%5Cmu(x)%7D%7B%5Csigma(x)%7D%5Cright)"></p>
<p>The PI acquisition function is then defined as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BPI%7D(x)%20=%20%5CPhi%5Cleft(%5Cfrac%7B%5Cmu(x)%20-%20f(x%5E*)%7D%7B%5Csigma(x)%7D%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cmu"> is the mean of the posterior distribution, which represents the predicted value of the function at point <img src="https://latex.codecogs.com/png.latex?x">; <img src="https://latex.codecogs.com/png.latex?%5Csigma"> is the standard deviation of the posterior distribution, which represents the uncertainty of the prediction at point <img src="https://latex.codecogs.com/png.latex?x">; <img src="https://latex.codecogs.com/png.latex?f(x%5E*)"> is the current best observation; <img src="https://latex.codecogs.com/png.latex?%5CPhi"> is the cumulative distribution function (CDF) of the standard normal distribution.</p>
<p>To control for the exploration-exploitation trade-off, we can introduce a hyperparameter <img src="https://latex.codecogs.com/png.latex?%5Cxi"> to the PI acquisition function:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BPI%7D(x;%5Cxi)%20=%20%5CPhi%5Cleft(%5Cfrac%7B%5Cmu(x)%20-%20f(x%5E*)%20-%20%5Cxi%7D%7B%5Csigma(x)%7D%5Cright)"></p>
<p>When <img src="https://latex.codecogs.com/png.latex?%5Cxi=0">, we recover the original PI formula. Larger values of <img src="https://latex.codecogs.com/png.latex?%5Cxi"> raise the improvement threshold, steering the algorithm toward exploration.</p>
</section>
<section id="expected-improvement-ei" class="level3">
<h3 class="anchored" data-anchor-id="expected-improvement-ei">Expected Improvement (EI)</h3>
<p>PI only considers the probability of improving the current best estimate, but it does not account for the magnitude of the improvement. Expected Improvement (EI) accounts for this by taking the expectation of the improvement values <img src="https://latex.codecogs.com/png.latex?I(x)">:</p>
<p><img src="https://latex.codecogs.com/png.latex?EI(x)%20=%20%5Cint%5E%7B%5Cinfty%7D_%7B-%5Cinfty%7DI(x)%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cvarphi(z)"> is the probability density function of the standard normal distribution: <img src="https://latex.codecogs.com/png.latex?%5Cvarphi(z)%20=%20%5Cdfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%7D%5Cexp(-z%5E2/2)">.</p>
<p>How to do the integration? Consider the expression of <img src="https://latex.codecogs.com/png.latex?I(x)">:</p>
<p><img src="https://latex.codecogs.com/png.latex?EI(x)%20=%20%5Cint%5E%7B%5Cinfty%7D_%7B-%5Cinfty%7D%5Cmax(f(x)-f(x%5E*),0)%5C,%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz"></p>
<p>Let <img src="https://latex.codecogs.com/png.latex?z_0"> denote the value where the max function switches from 0 to <img src="https://latex.codecogs.com/png.latex?f(x)-f(x%5E*)">. The integration can be broken down into two pieces:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BEI%7D(x)%20=%20%5Cunderbrace%7B%5Cint_%7B-%5Cinfty%7D%5E%7Bz_0%7D%20I(x)%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz%7D_%7B%5Ctext%7BZero%20since%20%7D%20I(x)=0%7D%20+%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20I(x)%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz"></p>
<p>We can now focus on the latter part:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20I(x)%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz"></p>
<p>Here <img src="https://latex.codecogs.com/png.latex?I(x)%20=%20f(x)%20-%20f(x%5E*)">.</p>
<p>For mathematical convenience, we use a reparameterization trick on <img src="https://latex.codecogs.com/png.latex?f(x)">. If <img src="https://latex.codecogs.com/png.latex?f(x)%20%5Csim%20%5Cmathcal%7BN%7D(%5Cmu(x),%20%5Csigma%5E2(x))">, and <img src="https://latex.codecogs.com/png.latex?z%20%5Csim%20%5Cmathcal%7BN%7D(0,1)">, then <img src="https://latex.codecogs.com/png.latex?f(x)"> can be reparameterized as <img src="https://latex.codecogs.com/png.latex?f(x)%20=%20%5Cmu(x)%20+%20%5Csigma(x)z">.</p>
<p>Plugging the expression back into the integration, we get:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balign%7D%0A%5Ctext%7BEI%7D(x)%20&amp;=%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20%5Cmax(f(x)%20-%20f(x%5E*),%200)%5C,%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz%0A=%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20(%5Cmu%20+%20%5Csigma%20z%20-%20f(x%5E*))%5C,%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz%20%5C%5C%0A&amp;=%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20(%5Cmu%20-%20f(x%5E*))%5C,%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz%0A+%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20%5Csigma%20z%20%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%7D%20e%5E%7B-z%5E2/2%7D%5C,%5Cmathrm%7Bd%7Dz%20%5C%5C%0A&amp;=%20(%5Cmu%20-%20f(x%5E*))%20%5Cunderbrace%7B%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20%5Cvarphi(z)%5C,%5Cmathrm%7Bd%7Dz%7D_%7B1-%5CPhi(z_0)%5C,%5Cequiv%5C,1-%5Ctext%7BCDF%7D(z_0)%7D%0A+%20%5Cfrac%7B%5Csigma%7D%7B%5Csqrt%7B2%5Cpi%7D%7D%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20z%20e%5E%7B-z%5E2/2%7D%5C,%5Cmathrm%7Bd%7Dz%20%5C%5C%0A&amp;=%20(%5Cmu%20-%20f(x%5E*))%5Cunderbrace%7B(1%20-%20%5CPhi(z_0))%7D_%7B%5CPhi(-z_0)%7D%0A+%20%5Cfrac%7B%5Csigma%7D%7B%5Csqrt%7B2%5Cpi%7D%7D%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20z%20e%5E%7B-z%5E2/2%7D%5C,%5Cmathrm%7Bd%7Dz%0A%5Cend%7Balign%7D"></p>
<p>Here, the integration <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Csigma%7D%7B%5Csqrt%7B2%5Cpi%7D%7D%20%5Cint_%7Bz_0%7D%5E%7B%5Cinfty%7D%20z%20e%5E%7B-z%5E2/2%7D%5C,%5Cmathrm%7Bd%7Dz"> can be solved by substitution and we get:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Csigma%20%5Cunderbrace%7B%5Cdfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%7D%5Cexp%5C!%5Cleft(-%5Cfrac%7Bz_0%5E2%7D%7B2%7D%5Cright)%7D_%7B%5Cvarphi(z_0)=%5Cvarphi(-z_0)%20%5Ctext%7B%20due%20to%20symmetry%20of%20the%20PDF%7D%7D"></p>
<p>Here <img src="https://latex.codecogs.com/png.latex?z_0%20=%20%5Cdfrac%7Bf(x%5E*)%20-%20%5Cmu%7D%7B%5Csigma%7D">.</p>
<p>Therefore, the final expression of <img src="https://latex.codecogs.com/png.latex?EI(x)"> is:</p>
<p><img src="https://latex.codecogs.com/png.latex?EI(x)%20=%20(%5Cmu%20-%20f(x%5E*))%5C,%5CPhi%5C!%5Cleft(%5Cfrac%7B%5Cmu%20-%20f(x%5E*)%7D%7B%5Csigma%7D%5Cright)%20+%20%5Csigma%5Cvarphi%5C!%5Cleft(%5Cfrac%7B%5Cmu%20-%20f(x%5E*)%7D%7B%5Csigma%7D%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cmu"> is the mean of the posterior distribution, which represents the predicted value of the function at point <img src="https://latex.codecogs.com/png.latex?x">; <img src="https://latex.codecogs.com/png.latex?%5Csigma"> is the standard deviation of the posterior distribution, which represents the uncertainty of the prediction at point <img src="https://latex.codecogs.com/png.latex?x">; <img src="https://latex.codecogs.com/png.latex?f(x%5E*)"> is the current best observation; <img src="https://latex.codecogs.com/png.latex?%5CPhi"> is the cumulative distribution function (CDF) of the standard normal distribution; <img src="https://latex.codecogs.com/png.latex?%5Cvarphi"> is the probability density function (PDF) of the standard normal distribution, which gives the likelihood of a standard normal random variable taking on a specific value.</p>
<p>One last piece of the Expected Improvement algorithm is a hyperparameter <img src="https://latex.codecogs.com/png.latex?%5Cxi"> that controls the exploitation vs.&nbsp;exploration trade-off:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BEI%7D(x;%5Cxi)%20=%20(%5Cmu%20-%20f(x%5E*)%20-%20%5Cxi)%5C,%5CPhi%5C!%5Cleft(%5Cfrac%7B%5Cmu%20-%20f(x%5E*)%20-%20%5Cxi%7D%7B%5Csigma%7D%5Cright)%20+%20%5Csigma%5Cvarphi%5C!%5Cleft(%5Cfrac%7B%5Cmu%20-%20f(x%5E*)%20-%20%5Cxi%7D%7B%5Csigma%7D%5Cright)"></p>
<p>As with PI, large values of <img src="https://latex.codecogs.com/png.latex?%5Cxi"> steer the algorithm toward exploration, as they essentially raise the threshold by pretending we have a higher current best value than we actually do.</p>
</section>
</section>
<section id="acquisition-function-implementation" class="level2">
<h2 class="anchored" data-anchor-id="acquisition-function-implementation">Acquisition Function Implementation</h2>
<p>In this section we examine the code implementation of Bayesian Optimization. Two things stood out when studying the implementation:</p>
<p><strong>Optimization</strong> — an optimization algorithm is used to find the next sampling location that maximizes the acquisition function.</p>
<p><strong>Kernel</strong> — in practice, a Matérn kernel is commonly used rather than an RBF kernel.</p>
<section id="optimization-algorithm" class="level3">
<h3 class="anchored" data-anchor-id="optimization-algorithm">Optimization Algorithm</h3>
<p>The acquisition functions above allow us to evaluate them at any given point. To find the optimal point, we need to maximize the acquisition function. In simple cases where the acquisition function is smooth and unimodal, a grid search is sufficient. However, in more complex cases where the acquisition function may have multiple local maxima, we need an optimization algorithm to find the global maximum.</p>
<p>In the implementation, we use the L-BFGS-B algorithm to find the point that maximizes the acquisition function. The L-BFGS-B algorithm is a quasi-Newton method that approximates the Broyden–Fletcher–Goldfarb–Shanno (BFGS) algorithm using limited memory. It is particularly useful for optimizing functions with a large number of variables and can handle simple box constraints on the variables.</p>
<p>The code snippet below shows the implementation of the <code>propose_location</code> method, which uses the L-BFGS-B algorithm to find the next sampling location by maximizing the acquisition function. The idea is to pass the acquisition function to the SciPy optimizer <code>minimize</code>. For each optimization, the function tries several random initializations — think of it as using gradient descent to find the maximum of a function, but starting from different random points to avoid getting stuck in local maxima. The best result across all random initializations is returned as the next sampling location.</p>
<div id="f5b1fe4f" class="cell" data-execution_count="1">
<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="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> propose_location(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, acquisition, bounds, n_restarts<span 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-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Find the next sampling location by maximizing the acquisition function</span></span>
<span id="cb1-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    using multi-restart L-BFGS-B optimization to avoid local optima.</span></span>
<span id="cb1-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Each restart begins from a random point drawn uniformly from bounds.</span></span>
<span id="cb1-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    The best result across all restarts is returned.</span></span>
<span id="cb1-7"></span>
<span id="cb1-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Args:</span></span>
<span id="cb1-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        acquisition: Acquisition function to maximize (e.g. expected_improvement)</span></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        bounds:      Search space bounds, shape (1, 2)</span></span>
<span id="cb1-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        n_restarts:  Number of random restarts for the optimizer.</span></span>
<span id="cb1-12"></span>
<span id="cb1-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns:</span></span>
<span id="cb1-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        X_next: Next proposed sampling location, shape (1, 1)</span></span>
<span id="cb1-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb1-16">    dim <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_train.shape[<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;"># feature dimension</span></span>
<span id="cb1-17">    min_val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.inf</span>
<span id="cb1-18">    min_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;">None</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> min_obj(X):</span>
<span id="cb1-21">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># negate because scipy.optimize.minimize minimizes</span></span>
<span id="cb1-22">        <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>acquisition(X)</span>
<span id="cb1-23">    </span>
<span id="cb1-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x0 <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> np.random.uniform(bounds[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bounds[:,<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>(n_restarts, dim)):</span>
<span id="cb1-25">        res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> minimize(min_obj, x0<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x0, bounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>bounds, method<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;">'L-BFGS-B'</span>)</span>
<span id="cb1-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> res.fun <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> min_val:</span>
<span id="cb1-27">            min_val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> res.fun</span>
<span id="cb1-28">            min_x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> res.x</span>
<span id="cb1-29">    </span>
<span id="cb1-30">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> min_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>
</details>
</div>
</section>
<section id="matérn-kernel" class="level3">
<h3 class="anchored" data-anchor-id="matérn-kernel">Matérn Kernel</h3>
<p>Although the RBF kernel is popular, it is less commonly used in Bayesian Optimization because it assumes that the underlying function is infinitely differentiable, which is usually not true in practice. In other words, when we use the RBF kernel, we implicitly assume that the function we are trying to optimize is smooth everywhere. In reality, the actual function may have abrupt changes or discontinuities. As a result, a generalized version of the RBF kernel — the Matérn kernel — is often used:</p>
<p><img src="https://latex.codecogs.com/png.latex?k(x_i,%20x_j)%20=%20%5Cfrac%7B1%7D%7B%5CGamma(%5Cnu)2%5E%7B%5Cnu-1%7D%7D%5Cleft(%5Cfrac%7B%5Csqrt%7B2%5Cnu%7D%7D%7Bl%7D%5C,d(x_i,%20x_j)%5Cright)%5E%5Cnu%20K_%5Cnu%5Cleft(%5Cfrac%7B%5Csqrt%7B2%5Cnu%7D%7D%7Bl%7D%5C,d(x_i,%20x_j)%5Cright)"></p>
<p>Here is what each term does:</p>
<ul>
<li><p><strong><img src="https://latex.codecogs.com/png.latex?d(x_i,%20x_j)"></strong> — the Euclidean distance between two input points: <img src="https://latex.codecogs.com/png.latex?d(x_i,%20x_j)%20=%20%5C%7Cx_i%20-%20x_j%5C%7C_2%20=%20%5Csqrt%7B%5Csum_k%20(x_%7Bik%7D%20-%20x_%7Bjk%7D)%5E2%7D"></p></li>
<li><p><strong><img src="https://latex.codecogs.com/png.latex?%5Cell"> (length scale)</strong> — controls how quickly correlation decays with distance. Larger <img src="https://latex.codecogs.com/png.latex?%5Cell"> means smoother, slower-varying functions; smaller <img src="https://latex.codecogs.com/png.latex?%5Cell"> means the function can wiggle over shorter input distances.</p></li>
<li><p><strong><img src="https://latex.codecogs.com/png.latex?%5Cnu"> (smoothness parameter)</strong> — controls the smoothness of the function. A smaller value of <img src="https://latex.codecogs.com/png.latex?%5Cnu"> allows for more abrupt changes, while a larger value results in a smoother function. As <img src="https://latex.codecogs.com/png.latex?%5Cnu%20%5Cto%20%5Cinfty">, the Matérn kernel converges exactly to the RBF kernel.</p></li>
<li><p><strong><img src="https://latex.codecogs.com/png.latex?K_%5Cnu"> (modified Bessel function)</strong> — a special function that models functions with varying degrees of smoothness.</p></li>
<li><p><strong><img src="https://latex.codecogs.com/png.latex?%5CGamma(%5Cnu)"></strong> — the Gamma function, a normalizing constant.</p></li>
</ul>
<p>In practice, the most common choice is <img src="https://latex.codecogs.com/png.latex?%5Cnu%20=%202.5">, which corresponds to a twice-differentiable function. This is a good compromise between flexibility and smoothness, and is the default in many Gaussian Process libraries (e.g., scikit-learn, GPyTorch).</p>
</section>
<section id="class-details" class="level3">
<h3 class="anchored" data-anchor-id="class-details">Class Details</h3>
<p>With the core of the BO implementation introduced, we can now look at the <code>GPreg</code> class that wraps the full Bayesian Optimization pipeline — from GP posterior computation to sequential sampling and visualization.</p>
<p><strong>Infrastructure</strong></p>
<ul>
<li><code>__init__</code> — stores training data, plot grid, objective function, and initializes the prior</li>
<li><code>mean_func</code> — zero mean prior</li>
<li><code>kernel_func</code> — Matérn kernel (<img src="https://latex.codecogs.com/png.latex?%5Cnu">=2.5) via sklearn</li>
<li><code>compute_posterior</code> — computes <img src="https://latex.codecogs.com/png.latex?%5Cmu"> and <img src="https://latex.codecogs.com/png.latex?%5CSigma"> given training data; <code>rewrite</code> flag protects the plot grid posterior from being overwritten during optimization</li>
</ul>
<p><strong>Acquisition functions</strong></p>
<ul>
<li><code>improvement_probability</code> — implements PI: <img src="https://latex.codecogs.com/png.latex?%5CPhi(Z)"></li>
<li><code>expected_improvement</code> — implements EI: <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bimp%7D%20%5Ccdot%20%5CPhi(Z)%20+%20%5Csigma%20%5Ccdot%20%5Cvarphi(Z)"></li>
<li><code>upper_confidence_bound</code> — implements UCB: <img src="https://latex.codecogs.com/png.latex?%5Cmu(x)%20+%20%5Clambda%5Csigma(x)"></li>
</ul>
<p><strong>Optimization</strong></p>
<ul>
<li><code>propose_location</code> — maximizes acquisition function via multi-restart L-BFGS-B</li>
</ul>
<p><strong>Plotting</strong></p>
<ul>
<li><code>plot_approximation</code> — surrogate mean + uncertainty band + samples</li>
<li><code>plot_acquisition</code> — EI curve over search space</li>
</ul>
<p><strong>BO loop</strong></p>
<ul>
<li><code>run_bo</code> — unified loop; plots directly when <code>store_traces=False</code>, stores traces when <code>True</code>; accepts <code>n_restarts</code> to control optimizer speed</li>
</ul>
<p><strong>Performance Analysis</strong></p>
<ul>
<li><code>compare_acquisition</code> — runs EI and PI from the same initial points and plots them side by side with dual axes</li>
<li><code>convergence_plot</code> — averages best observed value over multiple random experiments for EI, PI, and UCB, with shaded standard deviation bands</li>
</ul>
<p>Expand to see the full implementation of the <code>GPreg</code> class.</p>
<div id="c0686003" class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Show 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> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb2-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.gaussian_process.kernels <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Matern</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> norm</span>
<span id="cb2-5"><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="cb2-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.spatial.distance <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cdist</span>
<span id="cb2-7"></span>
<span id="cb2-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> GPreg:</span>
<span id="cb2-9">    </span>
<span id="cb2-10">    <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_train, y_train, X_plot, f, length_scale<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>, bounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.array([[<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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>]]), keps<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;">1e-8</span>):</span>
<span id="cb2-11">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Initialize the Gaussian Process regression model.</span></span>
<span id="cb2-13"></span>
<span id="cb2-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X_train:      Initial training inputs, shape (n, 1)</span></span>
<span id="cb2-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            y_train:      Initial training targets, shape (n, 1)</span></span>
<span id="cb2-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X_plot:       Dense grid of points for plotting, shape (m, 1). Never changes.</span></span>
<span id="cb2-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            f:            Objective function to optimize. Must accept (X, noise=...).</span></span>
<span id="cb2-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            length_scale: Length scale parameter for the Matern kernel.</span></span>
<span id="cb2-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            bounds:       Search space bounds, shape (1, 2) e.g. np.array([[-1.0, 2.0]])</span></span>
<span id="cb2-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            keps:         Jitter added to kernel diagonal for numerical stability.</span></span>
<span id="cb2-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-23">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.L <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> length_scale</span>
<span id="cb2-24">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> keps</span>
<span id="cb2-25">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.bounds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bounds </span>
<span id="cb2-26">        </span>
<span id="cb2-27">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># store initial state so run_bo can reset between acquisition function runs</span></span>
<span id="cb2-28">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train_init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train</span>
<span id="cb2-29">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train_init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_train</span>
<span id="cb2-30">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train</span>
<span id="cb2-31">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_train</span>
<span id="cb2-32">        </span>
<span id="cb2-33">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_plot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_plot  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fixed dense grid for plotting, never changes</span></span>
<span id="cb2-34">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_plot</span>
<span id="cb2-35">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.obj_fn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f</span>
<span id="cb2-36">        </span>
<span id="cb2-37">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># initialize prior mean (zero) and prior covariance over plot grid</span></span>
<span id="cb2-38">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn <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>.mean_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test)</span>
<span id="cb2-39">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn <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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test, length_scale<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>.L) <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;">1e-15</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>np.eye(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test))</span>
<span id="cb2-40">    </span>
<span id="cb2-41">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> mean_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb2-42">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-43"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Zero mean prior function. Returns a zero vector of shape (n, 1) for n input points.</span></span>
<span id="cb2-44"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        A zero mean is the standard choice when there is no prior knowledge about the function's average behavior.</span></span>
<span id="cb2-45"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-46">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.zeros((np.size(X), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb2-47">    </span>
<span id="cb2-48">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, z, length_scale<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>, nu<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;">2.5</span>):</span>
<span id="cb2-49">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-50"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Matern kernel with nu=2.5 (twice differentiable).</span></span>
<span id="cb2-51"></span>
<span id="cb2-52"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-53"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X:            First input array, shape (n, 1)</span></span>
<span id="cb2-54"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            z:            Second input array, shape (m, 1)</span></span>
<span id="cb2-55"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            length_scale: Controls how quickly correlation decays with distance.</span></span>
<span id="cb2-56"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            nu:           Smoothness parameter. nu=2.5 means twice differentiable.</span></span>
<span id="cb2-57"></span>
<span id="cb2-58"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Returns:</span></span>
<span id="cb2-59"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            Kernel matrix of shape (n, m).</span></span>
<span id="cb2-60"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-61">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Matern(length_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>length_scale, nu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nu)(X, z)</span>
<span id="cb2-62">        </span>
<span id="cb2-63">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compute_posterior(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X_test<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>, rewrite<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-64">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-65"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Compute the GP posterior mean and covariance conditioned on training data.</span></span>
<span id="cb2-66"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        K is the train-train kernel matrix, K_s is train-test, K_ss is test-test.</span></span>
<span id="cb2-67"></span>
<span id="cb2-68"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-69"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X_test:  Test points to predict at. Defaults to X_plot (the dense grid).</span></span>
<span id="cb2-70"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            rewrite: If True, updates self.muFn and self.Kfn (used for plotting).</span></span>
<span id="cb2-71"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">                     If False, returns values without touching stored state (used</span></span>
<span id="cb2-72"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">                     inside acquisition functions during optimization).</span></span>
<span id="cb2-73"></span>
<span id="cb2-74"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Returns:</span></span>
<span id="cb2-75"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            posterior_mean: shape (n_test, 1)</span></span>
<span id="cb2-76"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            posterior_cov:  shape (n_test, n_test)</span></span>
<span id="cb2-77"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-78">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> X_test <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>:</span>
<span id="cb2-79">            X_test <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_plot </span>
<span id="cb2-80">        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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, length_scale<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>.L) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train))</span>
<span id="cb2-81">        K_s <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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, X_test, length_scale<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>.L)</span>
<span id="cb2-82">        K_ss <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>.kernel_func(X_test, X_test, length_scale<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>.L) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(X_test))</span>
<span id="cb2-83">        K_inv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linalg.inv(K)</span>
<span id="cb2-84">        </span>
<span id="cb2-85">        posterior_mean <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.dot(K_s.T, np.dot(K_inv, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train))</span>
<span id="cb2-86">        posterior_cov  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> K_ss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.dot(K_s.T, np.dot(K_inv, K_s))</span>
<span id="cb2-87">        </span>
<span id="cb2-88">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> rewrite:</span>
<span id="cb2-89">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> posterior_mean</span>
<span id="cb2-90">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> posterior_cov</span>
<span id="cb2-91">        </span>
<span id="cb2-92">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> posterior_mean, posterior_cov</span>
<span id="cb2-93">        </span>
<span id="cb2-94">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> upper_confidence_bound(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, lambda_<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="cb2-95">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-96"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Upper Confidence Bound (UCB) acquisition function.</span></span>
<span id="cb2-97"></span>
<span id="cb2-98"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-99"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X:       Candidate point(s), shape (n, 1)</span></span>
<span id="cb2-100"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            lambda_: Exploration-exploitation trade-off parameter. Larger values encourage more exploration.</span></span>
<span id="cb2-101"></span>
<span id="cb2-102"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Returns:</span></span>
<span id="cb2-103"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            ucb: Upper confidence bound at each point in X, shape (n,)</span></span>
<span id="cb2-104"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-105">        X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.atleast_2d(X)                        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ensure 2D input</span></span>
<span id="cb2-106">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> 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 class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> X.shape[<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>
<span id="cb2-107">            X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X.T                                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ensure shape (n, 1) not (1, n)</span></span>
<span id="cb2-108">        </span>
<span id="cb2-109">        mu, cov <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_posterior(X, rewrite<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 class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># predict without overwriting plot grid posterior</span></span>
<span id="cb2-110">        mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mu.flatten()</span>
<span id="cb2-111">        sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.maximum(np.diag(cov), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># posterior standard deviation at each point</span></span>
<span id="cb2-112">        </span>
<span id="cb2-113">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> lambda_ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sigma                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># upper confidence bound</span></span>
<span id="cb2-114"></span>
<span id="cb2-115">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> improvement_probability(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, xi<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="cb2-116">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-117"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Probability of Improvement (PI) acquisition function.</span></span>
<span id="cb2-118"></span>
<span id="cb2-119"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-120"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X:   Candidate point(s), shape (n, 1)</span></span>
<span id="cb2-121"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            xi:  Exploration-exploitation trade-off. Larger xi = more exploration.</span></span>
<span id="cb2-122"></span>
<span id="cb2-123"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Returns:</span></span>
<span id="cb2-124"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            pi: Probability of improvement at each point in X, shape (n,)</span></span>
<span id="cb2-125"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-126">        X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.atleast_2d(X)</span>
<span id="cb2-127">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> 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 class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> X.shape[<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>
<span id="cb2-128">            X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X.T</span>
<span id="cb2-129">        mu, cov <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_posterior(X, rewrite<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="cb2-130">        mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mu.flatten()</span>
<span id="cb2-131">        sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.maximum(np.diag(cov), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb2-132">        mu_sample_opt <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;">max</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train)</span>
<span id="cb2-133"></span>
<span id="cb2-134">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> np.errstate(divide<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;">'warn'</span>):</span>
<span id="cb2-135">            imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu_sample_opt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> xi</span>
<span id="cb2-136">            Z  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sigma</span>
<span id="cb2-137">            pi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> norm.cdf(Z)</span>
<span id="cb2-138">            pi[sigma <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.0</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.0</span></span>
<span id="cb2-139"></span>
<span id="cb2-140">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> pi</span>
<span id="cb2-141"></span>
<span id="cb2-142">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> expected_improvement(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, xi<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="cb2-143">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-144"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Expected Improvement (EI) acquisition function.</span></span>
<span id="cb2-145"></span>
<span id="cb2-146"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-147"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X:   Candidate point(s), shape (n, 1)</span></span>
<span id="cb2-148"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            xi:  Exploration-exploitation trade-off. Larger xi = more exploration.</span></span>
<span id="cb2-149"></span>
<span id="cb2-150"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Returns:</span></span>
<span id="cb2-151"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            ei: Expected improvement at each point in X, shape (n,)</span></span>
<span id="cb2-152"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-153">        X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.atleast_2d(X)          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ensure 2D input</span></span>
<span id="cb2-154">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> 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 class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> X.shape[<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>
<span id="cb2-155">            X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X.T                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ensure shape (n, 1) not (1, n)</span></span>
<span id="cb2-156">        mu, cov <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_posterior(X, rewrite<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="cb2-157">        mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mu.flatten()</span>
<span id="cb2-158">        sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.maximum(np.diag(cov), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb2-159">        mu_sample_opt <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;">max</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train)</span>
<span id="cb2-160">        </span>
<span id="cb2-161">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> np.errstate(divide<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;">'warn'</span>):</span>
<span id="cb2-162">            imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu_sample_opt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> xi</span>
<span id="cb2-163">            Z  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sigma</span>
<span id="cb2-164">            ei <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> norm.cdf(Z) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> norm.pdf(Z)</span>
<span id="cb2-165">            ei[sigma <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.0</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.0</span></span>
<span id="cb2-166">            </span>
<span id="cb2-167">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ei</span>
<span id="cb2-168">    </span>
<span id="cb2-169">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> propose_location(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, acquisition, bounds, n_restarts<span 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="cb2-170">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-171"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Find the next sampling location by maximizing the acquisition function.</span></span>
<span id="cb2-172"></span>
<span id="cb2-173"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-174"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            acquisition: Acquisition function to maximize (e.g. expected_improvement)</span></span>
<span id="cb2-175"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            bounds:      Search space bounds, shape (1, 2)</span></span>
<span id="cb2-176"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_restarts:  Number of random restarts for the optimizer.</span></span>
<span id="cb2-177"></span>
<span id="cb2-178"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Returns:</span></span>
<span id="cb2-179"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X_next: Next proposed sampling location, shape (1, 1)</span></span>
<span id="cb2-180"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-181">        dim <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_train.shape[<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;"># feature dimension</span></span>
<span id="cb2-182">        min_val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.inf</span>
<span id="cb2-183">        min_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;">None</span></span>
<span id="cb2-184">        </span>
<span id="cb2-185">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> min_obj(X):</span>
<span id="cb2-186">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># negate because scipy.optimize.minimize minimizes</span></span>
<span id="cb2-187">            <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>acquisition(X)</span>
<span id="cb2-188">        </span>
<span id="cb2-189">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x0 <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> np.random.uniform(bounds[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bounds[:,<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>(n_restarts, dim)):</span>
<span id="cb2-190">            res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> minimize(min_obj, x0<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x0, bounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>bounds, method<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;">'L-BFGS-B'</span>)</span>
<span id="cb2-191">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> res.fun <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> min_val:</span>
<span id="cb2-192">                min_val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> res.fun</span>
<span id="cb2-193">                min_x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> res.x</span>
<span id="cb2-194">        </span>
<span id="cb2-195">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> min_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>
<span id="cb2-196">    </span>
<span id="cb2-197">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_approximation(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X_next, Y_next, i, n_iter):</span>
<span id="cb2-198">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-199"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Plot the GP surrogate mean, uncertainty band, observations, and next sample.</span></span>
<span id="cb2-200"></span>
<span id="cb2-201"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Displays:</span></span>
<span id="cb2-202"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          - Red dashed line: noise-free true objective (ground truth)</span></span>
<span id="cb2-203"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          - Blue line:       GP posterior mean (surrogate)</span></span>
<span id="cb2-204"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          - Blue band:       95% credible interval (+/- 1.96 * sigma)</span></span>
<span id="cb2-205"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          - Black dots:      Noisy observations seen so far</span></span>
<span id="cb2-206"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          - Green dashed:    Next proposed sampling location</span></span>
<span id="cb2-207"></span>
<span id="cb2-208"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-209"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X_next: Next proposed point, shape (1, 1)</span></span>
<span id="cb2-210"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            Y_next: Objective value at X_next</span></span>
<span id="cb2-211"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            i:      Current iteration index (0-based)</span></span>
<span id="cb2-212"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_iter: Total number of iterations (for subplot layout)</span></span>
<span id="cb2-213"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-214">        mu <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>.muFn.flatten()</span>
<span id="cb2-215">        sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.maximum(np.diag(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb2-216">        X_plot <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_plot.flatten()</span>
<span id="cb2-217">        </span>
<span id="cb2-218">        plt.subplot(n_iter, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</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> 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="cb2-219">        plt.plot(X_plot, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.obj_fn(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_plot, noise<span 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="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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Noise-free objective'</span>)</span>
<span id="cb2-220">        plt.plot(X_plot, mu, <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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Surrogate mean'</span>)</span>
<span id="cb2-221">        plt.fill_between(X_plot, mu <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.96</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sigma, mu <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.96</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>sigma, 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;">'95% CI'</span>)</span>
<span id="cb2-222">        plt.scatter(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train, c<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>, zorder<span 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>, 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;">'Samples'</span>)</span>
<span id="cb2-223">        plt.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_next, 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;">'g'</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>, 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;">'Next sample'</span>)</span>
<span id="cb2-224">        plt.title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Iteration </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>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 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-225">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> 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;">0</span>:</span>
<span id="cb2-226">            plt.legend()</span>
<span id="cb2-227"></span>
<span id="cb2-228">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_acquisition(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X_next, i, n_iter):</span>
<span id="cb2-229">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-230"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Plot the EI acquisition function curve over the search space.</span></span>
<span id="cb2-231"></span>
<span id="cb2-232"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-233"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            X_next: Next proposed point (shown as vertical dashed line)</span></span>
<span id="cb2-234"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            i:      Current iteration index (0-based)</span></span>
<span id="cb2-235"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_iter: Total number of iterations (for subplot layout)</span></span>
<span id="cb2-236"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-237">        ei <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>.expected_improvement(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_plot)</span>
<span id="cb2-238">        X_plot <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_plot.flatten()</span>
<span id="cb2-239">        </span>
<span id="cb2-240">        plt.subplot(n_iter, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</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> 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;">2</span>)</span>
<span id="cb2-241">        plt.plot(X_plot, ei, <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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Expected Improvement'</span>)</span>
<span id="cb2-242">        plt.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_next, 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;">'g'</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>, 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;">'Next sample'</span>)</span>
<span id="cb2-243">        plt.title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'EI - Iteration </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>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 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-244">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> 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;">0</span>:</span>
<span id="cb2-245">            plt.legend()</span>
<span id="cb2-246">    </span>
<span id="cb2-247">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> run_bo(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, acquisition<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>, n_iter<span 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>, store_traces<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>, n_restarts<span 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="cb2-248">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-249"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Run the Bayesian Optimization loop.</span></span>
<span id="cb2-250"></span>
<span id="cb2-251"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        At each iteration:</span></span>
<span id="cb2-252"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          1. Compute the GP posterior over the plot grid</span></span>
<span id="cb2-253"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          2. Find the next point by maximizing the acquisition function</span></span>
<span id="cb2-254"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          3. Evaluate the objective at the next point</span></span>
<span id="cb2-255"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">          4. Update training data and repeat</span></span>
<span id="cb2-256"></span>
<span id="cb2-257"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Always resets X_train and y_train to the initial state before running,</span></span>
<span id="cb2-258"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        so multiple calls (e.g. in compare_acquisition) start from the same data.</span></span>
<span id="cb2-259"></span>
<span id="cb2-260"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-261"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            acquisition:   Acquisition function to use. Defaults to expected_improvement.</span></span>
<span id="cb2-262"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_iter:        Number of BO iterations.</span></span>
<span id="cb2-263"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            store_traces:  If False, plots each iteration as it runs (single-function mode).</span></span>
<span id="cb2-264"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">                           If True, stores iteration data as a list of dicts for later</span></span>
<span id="cb2-265"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">                           plotting (used by compare_acquisition).</span></span>
<span id="cb2-266"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_restarts:    Number of restarts for propose_location.</span></span>
<span id="cb2-267"></span>
<span id="cb2-268"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Returns:</span></span>
<span id="cb2-269"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            traces (only when store_traces=True): list of dicts, one per iteration,</span></span>
<span id="cb2-270"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            each containing mu, sigma, X_next, Y_next, acq_vals, X_train, y_train.</span></span>
<span id="cb2-271"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-272">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> acquisition <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>:</span>
<span id="cb2-273">            acquisition <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>.expected_improvement</span>
<span id="cb2-274"></span>
<span id="cb2-275">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># reset to initial state so runs are always comparable</span></span>
<span id="cb2-276">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train <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_train_init.copy()</span>
<span id="cb2-277">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train <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_train_init.copy()</span>
<span id="cb2-278"></span>
<span id="cb2-279">        traces <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb2-280"></span>
<span id="cb2-281">        <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> store_traces:</span>
<span id="cb2-282">            plt.figure(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>, n_iter <span 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="cb2-283">            plt.subplots_adjust(hspace<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>)</span>
<span id="cb2-284"></span>
<span id="cb2-285">        <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_iter):</span>
<span id="cb2-286">            mu, cov <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_posterior(rewrite<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-287">            sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.maximum(np.diag(cov), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb2-288"></span>
<span id="cb2-289">            X_next <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>.propose_location(acquisition, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.bounds, n_restarts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_restarts)</span>
<span id="cb2-290">            Y_next <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>.obj_fn(X_next)</span>
<span id="cb2-291">            acq_vals <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> acquisition(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_plot)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># acquisition values over full plot grid</span></span>
<span id="cb2-292"></span>
<span id="cb2-293">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> store_traces:</span>
<span id="cb2-294">                traces.append({</span>
<span id="cb2-295">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mu'</span>: mu.flatten(),</span>
<span id="cb2-296">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sigma'</span>: sigma,</span>
<span id="cb2-297">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_next'</span>: X_next,</span>
<span id="cb2-298">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Y_next'</span>: Y_next,</span>
<span id="cb2-299">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'acq_vals'</span>: acq_vals,</span>
<span id="cb2-300">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_train'</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train.copy(),</span>
<span id="cb2-301">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y_train'</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train.copy()</span>
<span id="cb2-302">                })</span>
<span id="cb2-303">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb2-304">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.plot_approximation(X_next, Y_next, i, n_iter)</span>
<span id="cb2-305">                <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.plot_acquisition(X_next, i, n_iter)</span>
<span id="cb2-306"></span>
<span id="cb2-307">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.vstack((<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, X_next))</span>
<span id="cb2-308">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.vstack((<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train, Y_next))</span>
<span id="cb2-309"></span>
<span id="cb2-310">        <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> store_traces:</span>
<span id="cb2-311">            plt.show()</span>
<span id="cb2-312">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb2-313">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># restore initial state after trace collection</span></span>
<span id="cb2-314">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train <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_train_init.copy()</span>
<span id="cb2-315">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train <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_train_init.copy()</span>
<span id="cb2-316">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> traces</span>
<span id="cb2-317"></span>
<span id="cb2-318">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compare_acquisition(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, n_iter):</span>
<span id="cb2-319">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-320"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Compare EI and PI acquisition functions side by side.</span></span>
<span id="cb2-321"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Runs the full BO loop twice from the same initial data and plots both</span></span>
<span id="cb2-322"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        surrogate means and acquisition curves together at each iteration</span></span>
<span id="cb2-323"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        using dual y-axes for readability.</span></span>
<span id="cb2-324"></span>
<span id="cb2-325"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-326"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_iter: Number of BO iterations to run and display.</span></span>
<span id="cb2-327"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-328">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># run both acquisition functions from same initial state</span></span>
<span id="cb2-329">        traces_ei <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>.run_bo(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.expected_improvement, n_iter, store_traces<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-330">        traces_pi <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>.run_bo(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.improvement_probability, n_iter, store_traces<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-331"></span>
<span id="cb2-332">        X_plot <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_plot.flatten()</span>
<span id="cb2-333"></span>
<span id="cb2-334">        plt.figure(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;">9</span>, n_iter <span 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="cb2-335">        plt.subplots_adjust(hspace<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>)</span>
<span id="cb2-336"></span>
<span id="cb2-337">        <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_iter):</span>
<span id="cb2-338">            ei_trace <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> traces_ei[i]</span>
<span id="cb2-339">            pi_trace <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> traces_pi[i]</span>
<span id="cb2-340"></span>
<span id="cb2-341">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- combined surrogate plot with twin axis ---</span></span>
<span id="cb2-342">            ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplot(n_iter, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</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> 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="cb2-343">            ax1_twin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax1.twinx()</span>
<span id="cb2-344"></span>
<span id="cb2-345">            ax1.plot(X_plot, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.obj_fn(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_plot, noise<span 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="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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'True fn'</span>)</span>
<span id="cb2-346">            ax1.plot(X_plot, ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mu'</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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'EI surrogate mean'</span>)</span>
<span id="cb2-347">            ax1.fill_between(X_plot,</span>
<span id="cb2-348">                             ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mu'</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;">1.96</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sigma'</span>],</span>
<span id="cb2-349">                             ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mu'</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;">1.96</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sigma'</span>],</span>
<span id="cb2-350">                             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.15</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;">'blue'</span>)</span>
<span id="cb2-351">            ax1.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'EI surrogate'</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;">'blue'</span>)</span>
<span id="cb2-352">            ax1.tick_params(axis<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;">'y'</span>, labelcolor<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;">'blue'</span>)</span>
<span id="cb2-353"></span>
<span id="cb2-354">            ax1_twin.plot(X_plot, pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mu'</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'g-'</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;">'PI surrogate mean'</span>)</span>
<span id="cb2-355">            ax1_twin.fill_between(X_plot,</span>
<span id="cb2-356">                                  pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mu'</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;">1.96</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sigma'</span>],</span>
<span id="cb2-357">                                  pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'mu'</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;">1.96</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sigma'</span>],</span>
<span id="cb2-358">                                  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.15</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;">'green'</span>)</span>
<span id="cb2-359">            ax1_twin.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PI surrogate'</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;">'green'</span>)</span>
<span id="cb2-360">            ax1_twin.tick_params(axis<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;">'y'</span>, labelcolor<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;">'green'</span>)</span>
<span id="cb2-361"></span>
<span id="cb2-362">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shared initial samples</span></span>
<span id="cb2-363">            ax1.scatter(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train_init, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train_init, c<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>, zorder<span 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>, 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;">'Initial samples'</span>)</span>
<span id="cb2-364"></span>
<span id="cb2-365">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># EI and PI proposed samples from previous iterations</span></span>
<span id="cb2-366">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> i <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-367">                ei_new_X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_train'</span>][<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train_init):]</span>
<span id="cb2-368">                ei_new_y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y_train'</span>][<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train_init):]</span>
<span id="cb2-369">                ax1.scatter(ei_new_X, ei_new_y, c<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;">'blue'</span>, marker<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>, zorder<span 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>, 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;">'EI samples'</span>)</span>
<span id="cb2-370"></span>
<span id="cb2-371">                pi_new_X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_train'</span>][<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train_init):]</span>
<span id="cb2-372">                pi_new_y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y_train'</span>][<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train_init):]</span>
<span id="cb2-373">                ax1_twin.scatter(pi_new_X, pi_new_y, c<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;">'green'</span>, marker<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;">'s'</span>, zorder<span 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>, 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;">'PI samples'</span>)</span>
<span id="cb2-374"></span>
<span id="cb2-375">            ax1.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_next'</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;">'blue'</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="cb2-376">                        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'EI next: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X_next"</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="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>
<span id="cb2-377">            ax1.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_next'</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;">'green'</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="cb2-378">                        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'PI next: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X_next"</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="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>
<span id="cb2-379"></span>
<span id="cb2-380">            ax1.set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Surrogate - Iter </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>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 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-381">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> 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;">0</span>:</span>
<span id="cb2-382">                lines1, labels1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax1.get_legend_handles_labels()</span>
<span id="cb2-383">                lines1_twin, labels1_twin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax1_twin.get_legend_handles_labels()</span>
<span id="cb2-384">                ax1.legend(lines1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> lines1_twin, labels1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> labels1_twin, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>)</span>
<span id="cb2-385"></span>
<span id="cb2-386">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- combined acquisition plot with twin axis ---</span></span>
<span id="cb2-387">            ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplot(n_iter, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</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> 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;">2</span>)</span>
<span id="cb2-388">            ax3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax2.twinx()</span>
<span id="cb2-389"></span>
<span id="cb2-390">            ax2.plot(X_plot, ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'acq_vals'</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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'EI'</span>)</span>
<span id="cb2-391">            ax2.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ei_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_next'</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;">'blue'</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="cb2-392">            ax2.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'EI'</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;">'blue'</span>)</span>
<span id="cb2-393">            ax2.tick_params(axis<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;">'y'</span>, labelcolor<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;">'blue'</span>)</span>
<span id="cb2-394"></span>
<span id="cb2-395">            ax3.plot(X_plot, pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'acq_vals'</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'g-'</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;">'PI'</span>)</span>
<span id="cb2-396">            ax3.axvline(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pi_trace[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'X_next'</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;">'green'</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="cb2-397">            ax3.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PI'</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;">'green'</span>)</span>
<span id="cb2-398">            ax3.tick_params(axis<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;">'y'</span>, labelcolor<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;">'green'</span>)</span>
<span id="cb2-399"></span>
<span id="cb2-400">            ax2.set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Acquisition - Iter </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>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 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-401">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> 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;">0</span>:</span>
<span id="cb2-402">                lines2, labels2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax2.get_legend_handles_labels()</span>
<span id="cb2-403">                lines3, labels3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax3.get_legend_handles_labels()</span>
<span id="cb2-404">                ax2.legend(lines2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> lines3, labels2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> labels3)</span>
<span id="cb2-405"></span>
<span id="cb2-406">        plt.show()</span>
<span id="cb2-407"></span>
<span id="cb2-408">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> convergence_plot(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, n_iter, n_experiments<span 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>, n_restarts<span 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="cb2-409">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-410"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Plot the convergence of EI, PI, and UCB acquisition functions.</span></span>
<span id="cb2-411"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Runs the BO loop for each acquisition function n_experiments times</span></span>
<span id="cb2-412"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        from different random seeds and plots the mean and standard deviation</span></span>
<span id="cb2-413"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        of the best observed value at each iteration.</span></span>
<span id="cb2-414"></span>
<span id="cb2-415"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Args:</span></span>
<span id="cb2-416"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_iter:        Number of BO iterations per experiment.</span></span>
<span id="cb2-417"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_experiments: Number of random experiments to average over.</span></span>
<span id="cb2-418"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            n_restarts:    Number of restarts for propose_location.</span></span>
<span id="cb2-419"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        """</span></span>
<span id="cb2-420">        results <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;">'EI'</span>: [], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PI'</span>: [], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'UCB'</span>: []}</span>
<span id="cb2-421"></span>
<span id="cb2-422">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> seed <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_experiments):</span>
<span id="cb2-423">            np.random.seed(seed)</span>
<span id="cb2-424"></span>
<span id="cb2-425">            traces_ei  <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>.run_bo(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.expected_improvement,    n_iter, store_traces<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>, n_restarts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_restarts)</span>
<span id="cb2-426">            traces_pi  <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>.run_bo(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.improvement_probability, n_iter, store_traces<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>, n_restarts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_restarts)</span>
<span id="cb2-427">            traces_ucb <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>.run_bo(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.upper_confidence_bound,  n_iter, store_traces<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>, n_restarts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_restarts)</span>
<span id="cb2-428"></span>
<span id="cb2-429">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> best_observed(traces):</span>
<span id="cb2-430">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> [np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(t[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y_train'</span>]) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> t <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> traces]</span>
<span id="cb2-431"></span>
<span id="cb2-432">            results[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'EI'</span>].append(best_observed(traces_ei))</span>
<span id="cb2-433">            results[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PI'</span>].append(best_observed(traces_pi))</span>
<span id="cb2-434">            results[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'UCB'</span>].append(best_observed(traces_ucb))</span>
<span id="cb2-435"></span>
<span id="cb2-436">        iterations <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;">1</span>, n_iter <span 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-437">        colors <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;">'EI'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'blue'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PI'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'green'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'UCB'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>}</span>
<span id="cb2-438"></span>
<span id="cb2-439">        plt.figure(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;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb2-440">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> name, runs <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> results.items():</span>
<span id="cb2-441">            runs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(runs)</span>
<span id="cb2-442">            mean <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> runs.mean(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="cb2-443">            std  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> runs.std(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="cb2-444">            plt.plot(iterations, mean, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-o'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>colors[name], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>name)</span>
<span id="cb2-445">            plt.fill_between(iterations,</span>
<span id="cb2-446">                            mean <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> std,</span>
<span id="cb2-447">                            mean <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> std,</span>
<span id="cb2-448">                            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>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>colors[name])</span>
<span id="cb2-449"></span>
<span id="cb2-450">        true_max <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;">max</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.obj_fn(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_plot, noise<span 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="cb2-451">        plt.axhline(y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>true_max, 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="cb2-452">                    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'True maximum (</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>true_max<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>
<span id="cb2-453">        plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Iteration'</span>)</span>
<span id="cb2-454">        plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Best observed value'</span>)</span>
<span id="cb2-455">        plt.title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Convergence of Acquisition Functions (</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n_experiments<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;"> experiments)'</span>)</span>
<span id="cb2-456">        plt.legend()</span>
<span id="cb2-457">        plt.tight_layout()</span>
<span id="cb2-458">        plt.show()</span></code></pre></div></div>
</details>
</div>
</section>
<section id="bayesian-optimization-with-expected-improvement" class="level3">
<h3 class="anchored" data-anchor-id="bayesian-optimization-with-expected-improvement">Bayesian Optimization with Expected Improvement</h3>
<p>With the <code>GPreg</code> class defined, we can now run Bayesian Optimization using the Expected Improvement acquisition function.</p>
<div id="e3c97c15" class="cell" data-fig-height="20" data-fig-width="8" data-execution_count="3">
<details class="code-fold">
<summary>Show 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="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Setup</span></span>
<span id="cb3-2">bounds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([[<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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>]])</span>
<span id="cb3-3">X_plot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(bounds[<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>], bounds[<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>).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>
<span id="cb3-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Initial samples</span></span>
<span id="cb3-6">noise <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></span>
<span id="cb3-7">X_init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([[<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 class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>]])</span>
<span id="cb3-8"></span>
<span id="cb3-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> f(X, noise<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>):</span>
<span id="cb3-10">    <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.sin(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</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> 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;">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.7</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> noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.random.randn(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>X.shape)</span>
<span id="cb3-11"></span>
<span id="cb3-12">Y_init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f(X_init, noise)</span>
<span id="cb3-13"></span>
<span id="cb3-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Instantiate</span></span>
<span id="cb3-15">gp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GPreg(</span>
<span id="cb3-16">    f <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f,</span>
<span id="cb3-17">    X_train<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_init,</span>
<span id="cb3-18">    y_train<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Y_init,</span>
<span id="cb3-19">    X_plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X_plot,</span>
<span id="cb3-20">    length_scale<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="cb3-21">    bounds<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>bounds</span>
<span id="cb3-22">)</span>
<span id="cb3-23">    </span>
<span id="cb3-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Run</span></span>
<span id="cb3-25">np.random.seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb3-26">gp.run_bo(n_iter<span 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>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/cell-4-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2"><img src="https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/index_files/figure-html/cell-4-output-1.png" width="792" height="1170" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
<p>Starting from two initial observations, EI first explores the boundary of the search space where uncertainty is highest, then progressively narrows toward the true maximum. Early iterations show broad, flat acquisition curves reflecting high uncertainty; by iteration 5 the curve has sharpened into a narrow peak near <img src="https://latex.codecogs.com/png.latex?x%20%5Capprox%201.3">, signaling a transition from exploration to exploitation as the surrogate converges on the true function.</p>
</section>
<section id="expected-improvement-vs.-probability-of-improvement" class="level3">
<h3 class="anchored" data-anchor-id="expected-improvement-vs.-probability-of-improvement">Expected Improvement vs.&nbsp;Probability of Improvement</h3>
<p>Now let’s compare the results of the Expected Improvement and Probability of Improvement acquisition functions.</p>
<div id="99933eac" class="cell" data-fig-height="20" data-fig-width="8" data-execution_count="4">
<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">np.random.seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb4-2">gp.compare_acquisition(n_iter<span 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>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/cell-5-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3"><img src="https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/index_files/figure-html/cell-5-output-1.png" width="785" height="1170" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
<p>One clear difference is that PI tends to be more exploitative in its sampling, often proposing points close to the current best. This is because PI only considers the probability of improvement, not its magnitude. In contrast, EI balances both the probability and the expected magnitude of improvement, leading to more measured and directed sampling.</p>
</section>
</section>
<section id="convergence-of-acquisition-functions" class="level2">
<h2 class="anchored" data-anchor-id="convergence-of-acquisition-functions">Convergence of Acquisition Functions</h2>
<p>We now examine the convergence behavior of the three acquisition functions over multiple random experiments. For each acquisition function, we run the Bayesian Optimization loop for 15 iterations. To account for randomness, the process is repeated 20 times. The best observed value at each iteration is recorded, and we compute the mean and standard deviation across experiments.</p>
<div id="216c10fe" class="cell" data-execution_count="5">
<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">np.random.seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb5-2">gp.convergence_plot(n_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, n_experiments<span 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>, n_restarts<span 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>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/cell-6-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-4"><img src="https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/index_files/figure-html/cell-6-output-1.png" width="758" height="470" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
<p>Averaged over 20 random experiments, all three methods perform similarly in early iterations before EI pulls ahead slightly in the mid-range (iterations 5–9), crossing the true maximum line first. By iteration 15, EI, PI, and UCB converge to comparable final values. The wide shaded bands indicate high run-to-run variability — no method dominates consistently on this simple 1D function. In fact, Bull (2011) proved that EI achieves optimal (up to log factors) convergence rates for the Matérn kernel case specifically. The acquisition function choice matters most in higher dimensions and with expensive-to-evaluate objectives, where EI’s balanced exploration-exploitation behavior becomes a more reliable advantage.</p>
</section>
<section id="comparison-with-grid-search" class="level2">
<h2 class="anchored" data-anchor-id="comparison-with-grid-search">Comparison with Grid Search</h2>
<p>Perhaps the most important comparison is between Bayesian Optimization and Grid Search, which illustrates why Bayesian Optimization is used in the first place. Grid Search evaluates the objective function at evenly spaced points across the search space — a reasonable approach when the space is small and evaluations are cheap. What makes Bayesian Optimization superior in many scenarios is that it adaptively selects points based on the GP surrogate model and acquisition function, concentrating evaluations in promising regions rather than spreading them uniformly.</p>
<p>Below is a 2D example of Bayesian Optimization vs.&nbsp;Grid Search on a test error surface over two hyperparameters (lambda, sigma). The left panel shows the grid search samples while the right panel shows the Bayesian Optimization samples. Note how Bayesian Optimization concentrates samples in low-error regions, while grid search spreads them evenly. The convergence trace at the bottom shows that Bayesian Optimization reaches a lower error level faster than grid search.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="bo_gs_comparison.png" class="lightbox" data-gallery="quarto-lightbox-gallery-5" title="Bayesian Optimization vs.&nbsp;Grid Search"><img src="https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/bo_gs_comparison.png" class="img-fluid figure-img" alt="Bayesian Optimization vs.&nbsp;Grid Search"></a></p>
<figcaption>Bayesian Optimization vs.&nbsp;Grid Search</figcaption>
</figure>
</div>
<p>Expand to see the full code for this example.</p>
<div id="be0171b8" class="cell" data-execution_count="6">
<details class="code-fold">
<summary>Show 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> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb6-2"><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="cb6-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mpl_toolkits.mplot3d <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Axes3D</span>
<span id="cb6-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.gaussian_process.kernels <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Matern</span>
<span id="cb6-5"><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> norm</span>
<span id="cb6-6"><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="cb6-7"></span>
<span id="cb6-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ── Objective: 2D test error surface over (lambda, sigma) ──────────────────</span></span>
<span id="cb6-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_error(X, noise<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="cb6-10">    l, s <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>], X[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb6-11">    err <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (np.sin(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> l) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> np.cos(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-12">           <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> l<span 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 class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s<span 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>
<span id="cb6-13">           noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.random.randn(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(l)))</span>
<span id="cb6-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> err.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="cb6-15"></span>
<span id="cb6-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ── Minimal 2D GP + EI ──────────────────────────────────────────────────────</span></span>
<span id="cb6-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> GP2D:</span>
<span id="cb6-18">    <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_train, y_train, bounds, keps<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;">1e-6</span>):</span>
<span id="cb6-19">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train</span>
<span id="cb6-20">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_train</span>
<span id="cb6-21">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.bounds  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bounds</span>
<span id="cb6-22">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.keps    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> keps</span>
<span id="cb6-23">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.kernel  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Matern(length_scale<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>, nu<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;">2.5</span>)</span>
<span id="cb6-24"></span>
<span id="cb6-25">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> posterior(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X_test):</span>
<span id="cb6-26">        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>.kernel(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train))</span>
<span id="cb6-27">        K_s  <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>.kernel(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, X_test)</span>
<span id="cb6-28">        K_ss <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>.kernel(X_test, X_test) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(X_test))</span>
<span id="cb6-29">        K_inv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linalg.inv(K)</span>
<span id="cb6-30">        mu  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> K_s.T <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> K_inv <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_train</span>
<span id="cb6-31">        cov <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> K_ss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_s.T <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> K_inv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> K_s</span>
<span id="cb6-32">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> mu.flatten(), np.sqrt(np.maximum(np.diag(cov), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb6-33"></span>
<span id="cb6-34">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> ei(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, xi<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="cb6-35">        X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.atleast_2d(X)</span>
<span id="cb6-36">        mu, sigma <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>.posterior(X)</span>
<span id="cb6-37">        best  <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;">min</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train)</span>
<span id="cb6-38">        imp   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> best <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> xi</span>
<span id="cb6-39">        Z     <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sigma <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;">1e-9</span>)</span>
<span id="cb6-40">        ei    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> norm.cdf(Z) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> norm.pdf(Z)</span>
<span id="cb6-41">        ei[sigma <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-10</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.0</span></span>
<span id="cb6-42">        <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>ei  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># negate for scipy.optimize.minimize</span></span>
<span id="cb6-43"></span>
<span id="cb6-44">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> propose_location(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, n_restarts<span 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="cb6-45">        best_val, best_x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.inf, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb6-46">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x0 <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> np.random.uniform(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.bounds[:,<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>.bounds[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>],</span>
<span id="cb6-47">                                    size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(n_restarts, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.bounds.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])):</span>
<span id="cb6-48">            res <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> minimize(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.ei, x0<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x0, bounds<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>.bounds, method<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;">'L-BFGS-B'</span>)</span>
<span id="cb6-49">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> res.fun <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> best_val:</span>
<span id="cb6-50">                best_val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> res.fun</span>
<span id="cb6-51">                best_x   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> res.x</span>
<span id="cb6-52">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> best_x.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>
<span id="cb6-53"></span>
<span id="cb6-54"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ── Setup ───────────────────────────────────────────────────────────────────</span></span>
<span id="cb6-55">np.random.seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb6-56"></span>
<span id="cb6-57">bounds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([[<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;">4.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</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;">2.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>]])</span>
<span id="cb6-58">n_bo   <span 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></span>
<span id="cb6-59">n_grid <span 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 class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 6x6 = 36 ~ 30 points</span></span>
<span id="cb6-60"></span>
<span id="cb6-61"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dense surface for plotting</span></span>
<span id="cb6-62">l_grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(bounds[<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>], bounds[<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;">40</span>)</span>
<span id="cb6-63">s_grid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(bounds[<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>], bounds[<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;">40</span>)</span>
<span id="cb6-64">LL, SS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.meshgrid(l_grid, s_grid)</span>
<span id="cb6-65">XY_surf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.column_stack([LL.ravel(), SS.ravel()])</span>
<span id="cb6-66">ZZ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> test_error(XY_surf, noise<span 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>).reshape(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>)</span>
<span id="cb6-67"></span>
<span id="cb6-68"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ── Grid Search ─────────────────────────────────────────────────────────────</span></span>
<span id="cb6-69">gl <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(bounds[<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>], bounds[<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>], n_grid)</span>
<span id="cb6-70">gs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linspace(bounds[<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>], bounds[<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>], n_grid)</span>
<span id="cb6-71">GL, GS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.meshgrid(gl, gs)</span>
<span id="cb6-72">grid_pts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.column_stack([GL.ravel(), GS.ravel()])</span>
<span id="cb6-73">grid_pts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> grid_pts[:n_bo]</span>
<span id="cb6-74">grid_y   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> test_error(grid_pts, noise<span 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>).flatten()</span>
<span id="cb6-75">grid_best <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.minimum.accumulate(grid_y)</span>
<span id="cb6-76">gs_best_err <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> grid_best[<span 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="cb6-77">gs_best_pt  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> grid_pts[np.argmin(grid_y)]</span>
<span id="cb6-78"></span>
<span id="cb6-79"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ── Bayesian Optimisation ────────────────────────────────────────────────────</span></span>
<span id="cb6-80">X_init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.uniform(bounds[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bounds[:,<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>(<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;">2</span>))</span>
<span id="cb6-81">y_init <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> test_error(X_init).flatten()</span>
<span id="cb6-82"></span>
<span id="cb6-83">gp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GP2D(X_init, y_init.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>), bounds)</span>
<span id="cb6-84">bo_pts <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>(X_init)</span>
<span id="cb6-85">bo_y   <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>(y_init)</span>
<span id="cb6-86"></span>
<span id="cb6-87"><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_bo <span 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="cb6-88">    x_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gp.propose_location()</span>
<span id="cb6-89">    y_next <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> test_error(x_next, noise<span 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>).flatten()[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb6-90">    bo_pts.append(x_next.flatten())</span>
<span id="cb6-91">    bo_y.append(y_next)</span>
<span id="cb6-92">    gp.X_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.vstack(bo_pts)</span>
<span id="cb6-93">    gp.y_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(bo_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>)</span>
<span id="cb6-94"></span>
<span id="cb6-95">bo_pts    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(bo_pts)</span>
<span id="cb6-96">bo_y      <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(bo_y)</span>
<span id="cb6-97">bo_best   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.minimum.accumulate(bo_y)</span>
<span id="cb6-98">bo_best_err <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bo_best[<span 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="cb6-99">bo_best_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argmin(bo_y)</span>
<span id="cb6-100"></span>
<span id="cb6-101"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ── Plot ─────────────────────────────────────────────────────────────────────</span></span>
<span id="cb6-102">fig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.figure(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;">14</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb6-103">fig.patch.set_facecolor(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'white'</span>)</span>
<span id="cb6-104"></span>
<span id="cb6-105">surf_kw   <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>(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;">'YlOrRd'</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>, linewidth<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>, edgecolor<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>, antialiased<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="cb6-106">marker_kw <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>(s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, facecolors<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;">'none'</span>, edgecolors<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;">'#cc0000'</span>, linewidths<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.2</span>, zorder<span 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="cb6-107">elev, azim <span 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 class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span></span>
<span id="cb6-108"></span>
<span id="cb6-109">ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fig.add_subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">221</span>, projection<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;">'3d'</span>)</span>
<span id="cb6-110">ax1.set_facecolor(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'white'</span>)</span>
<span id="cb6-111">ax1.plot_surface(LL, SS, ZZ, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>surf_kw)</span>
<span id="cb6-112">gz <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> test_error(grid_pts, noise<span 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>).flatten()</span>
<span id="cb6-113">ax1.scatter(grid_pts[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], grid_pts[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], gz, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>marker_kw)</span>
<span id="cb6-114">ax1.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lambda'</span>, fontsize<span 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>, 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;">2</span>)</span>
<span id="cb6-115">ax1.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sigma'</span>,  fontsize<span 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>, 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;">2</span>)</span>
<span id="cb6-116">ax1.set_zlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test error'</span>, fontsize<span 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>, 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;">2</span>)</span>
<span id="cb6-117">ax1.tick_params(labelsize<span 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="cb6-118">ax1.view_init(elev<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>elev, azim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>azim)</span>
<span id="cb6-119">ax1.set_title(</span>
<span id="cb6-120">    <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'G.S. error: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>gs_best_err<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;">  lambda: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>gs_best_pt[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<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;">  sigma: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>gs_best_pt[<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;">:.1f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>,</span>
<span id="cb6-121">    fontsize<span 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>, fontweight<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;">'bold'</span>, 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;">6</span></span>
<span id="cb6-122">)</span>
<span id="cb6-123"></span>
<span id="cb6-124">ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fig.add_subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">222</span>, projection<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;">'3d'</span>)</span>
<span id="cb6-125">ax2.set_facecolor(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'white'</span>)</span>
<span id="cb6-126">ax2.plot_surface(LL, SS, ZZ, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>surf_kw)</span>
<span id="cb6-127">bz <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> test_error(bo_pts, noise<span 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>).flatten()</span>
<span id="cb6-128">ax2.scatter(bo_pts[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bo_pts[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], bz, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>marker_kw)</span>
<span id="cb6-129">ax2.scatter([bo_pts[bo_best_idx,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]], [bo_pts[bo_best_idx,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]],</span>
<span id="cb6-130">            [bz[bo_best_idx]], s<span 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>, c<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;">'red'</span>, zorder<span 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>, marker<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="cb6-131">ax2.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lambda'</span>, fontsize<span 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>, 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;">2</span>)</span>
<span id="cb6-132">ax2.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'sigma'</span>,  fontsize<span 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>, 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;">2</span>)</span>
<span id="cb6-133">ax2.set_zlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test error'</span>, fontsize<span 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>, 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;">2</span>)</span>
<span id="cb6-134">ax2.tick_params(labelsize<span 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="cb6-135">ax2.view_init(elev<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>elev, azim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>azim)</span>
<span id="cb6-136">ax2.set_title(</span>
<span id="cb6-137">    <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'B.O. error: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>bo_best_err<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;">  lambda: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>bo_pts[bo_best_idx,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<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;">  sigma: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>bo_pts[bo_best_idx,<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;">:.1f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>,</span>
<span id="cb6-138">    fontsize<span 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>, fontweight<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;">'bold'</span>, 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;">6</span></span>
<span id="cb6-139">)</span>
<span id="cb6-140"></span>
<span id="cb6-141">ax3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fig.add_subplot(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">212</span>)</span>
<span id="cb6-142">ax3.set_facecolor(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'white'</span>)</span>
<span id="cb6-143">iters <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;">1</span>, n_bo <span 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="cb6-144">ax3.plot(iters, grid_best, 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;">'#5555cc'</span>, linewidth<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;">2.5</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;">'Grid Search'</span>)</span>
<span id="cb6-145">ax3.plot(iters, bo_best,   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;">'#cc3333'</span>, linewidth<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;">2.5</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;">'Bayesian Optimization'</span>)</span>
<span id="cb6-146">true_min <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ZZ.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>()</span>
<span id="cb6-147">ax3.axhline(y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>true_min, 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;">'gray'</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>, linewidth<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="cb6-148">            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'True minimum (</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>true_min<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.3f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)'</span>)</span>
<span id="cb6-149">ax3.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Iteration'</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb6-150">ax3.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Best error found'</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb6-151">ax3.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Best Error over Time (B.O. and Grid Search)'</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>, fontweight<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;">'bold'</span>, 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;">8</span>)</span>
<span id="cb6-152">ax3.legend(fontsize<span 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="cb6-153">ax3.set_xlim(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_bo)</span>
<span id="cb6-154">ax3.spines[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'top'</span>].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb6-155">ax3.spines[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'right'</span>].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb6-156">ax3.tick_params(labelsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>)</span>
<span id="cb6-157"></span>
<span id="cb6-158">plt.tight_layout(h_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;">3</span>)</span>
<span id="cb6-159">plt.show()</span></code></pre></div></div>
</details>
</div>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In this post, we explored the fundamentals of three acquisition functions: Expected Improvement (EI), Probability of Improvement (PI), and Upper Confidence Bound (UCB). By combining a Gaussian Process surrogate with an acquisition function, Bayesian Optimization balances exploration of the search space with exploitation of known good areas.</p>
<p>What I find compelling about Bayesian Optimization is how it mirrors the way we naturally learn: make a guess, observe the outcome, update your beliefs, and try again — but guided by math rather than intuition. Like gradient descent, it is an iterative search, but one that builds an explicit model of uncertainty and uses it to decide where to look next. There is something elegant about an algorithm that knows what it does not know.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li>E. Kamperi. <a href="https://ekamperi.github.io/machine%20learning/2021/06/11/acquisition-functions.html#upper-confidence-bound-ucb">Acquisition functions in Bayesian Optimization.</a> 2021.</li>
<li>M. Krasserm. <a href="https://krasserm.github.io/2018/03/21/bayesian-optimization/#Optimization-algorithm">Bayesian Optimization.</a> 2018.</li>
<li>Scikit-learn. <a href="https://scikit-learn.org/stable/modules/gaussian_process.html#matern-kernel">Gaussian Processes.</a> 2024.</li>
<li>Bull, A. D. <a href="http://www.jmlr.org/papers/v12/bull11a.html">Convergence Rates of Efficient Global Optimization Algorithms.</a> <em>Journal of Machine Learning Research</em>, 12(88):2879–2904, 2011.</li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Bayesian Optimization - Acquisition
Functions.”</span> June 30. <a href="https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/">https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/</a>.
</div></div></section></div> ]]></description>
  <category>Machine Learning</category>
  <category>Gaussian Processes</category>
  <category>Bayesian</category>
  <guid>https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/</guid>
  <pubDate>Tue, 30 Jun 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2026-06-30-bayesian-optimization-acquisition-functions/sidebar.png" medium="image" type="image/png" height="103" width="144"/>
</item>
<item>
  <title>Bayesian Optimization - Gaussian Processes</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>If you’re a millennial, chances are you played a Windows game called Minesweeper growing up. The premise is deceptively simple: a grid of covered squares hides a set number of mines, and your job is to uncover all the safe squares without triggering one. When you click a square, it either reveals a number — indicating how many of its neighboring squares contain mines — or ends the game in an explosion. Using those numbers, you reason about which adjacent squares are safe to click and which are likely deadly. The further you get, the more information you have, and the more confident your next move becomes. At its heart, Minesweeper is a game of inference under uncertainty. You build a mental model of where the mines are hiding, and you use it to decide where to step next.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="minesweeper.jpg" class="lightbox" data-gallery="quarto-lightbox-gallery-1" title="A game of Minesweeper"><img src="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/minesweeper.jpg" class="img-fluid quarto-figure quarto-figure-center figure-img" style="width:80.0%" alt="A game of Minesweeper"></a></p>
</figure>
</div>
<figcaption>A game of Minesweeper</figcaption>
</figure>
</div>
<p>Bayesian Optimization is the Minesweeper of Machine Learning (ML). A typical ML workflow involves defining an objective function — such as a loss function — and then solving for its minimum or maximum using numerical methods based on its derivatives. But there are cases where neither the objective function nor its derivatives are known. For such black-box functions, the only option is to draw samples in search of the optimal value. When samples are cheap to draw, a grid-search approach — systematically evaluating many combinations of input variables — works fine. But when samples are expensive, such as tuning the hyperparameters of a deep neural network or drilling for oil at candidate geographic coordinates, reaching the optimum with as few samples as possible becomes critical.</p>
<p>That is where Bayesian Optimization (BO) shines. BO consists of two components: a surrogate model — most commonly a Gaussian Process — and an acquisition function. The Gaussian Process is like the revealed squares on the Minesweeper grid, telling you what the landscape looks like around your observations. The acquisition function is your reasoning about where to click next. And the mines? They are the optimum values of your objective function.</p>
</section>
<section id="gaussian-processes-gp-through-the-lens-of-regression" class="level2">
<h2 class="anchored" data-anchor-id="gaussian-processes-gp-through-the-lens-of-regression">Gaussian Processes (GP) through the Lens of Regression</h2>
<p>There are many ways to introduce Gaussian Processes, of which the most intuitive to me is through the regression perspective.</p>
<p>Forget about Gaussian Processes for a minute. A typical regression workflow goes like this:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cunderbrace%7BD%7D_%7B%5Ctext%7BData%7D%7D%20%5Crightarrow%20%5Cunderbrace%7BW%7D_%7B%5Ctext%7BRegression%20Parameters%7D%7D%20%5Crightarrow%20%5Cunderbrace%7By%7D_%7B%5Ctext%7BPredictions%7D%7D"></p>
<p>You use data to estimate regression parameters, then use the estimated parameters to make predictions. To estimate the regression parameters <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D">, two paradigms are most common:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BMLE:%7D%20%5Cquad%20P(%5Cmathbf%7BD%7D%7C%5Cmathbf%7Bw%7D)%20=%20%5Cprod%5En_%7Bi=1%7DP(y_i%7Cx_i,%5Cmathbf%7Bw%7D)"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BMAP:%7D%20%5Cquad%20P(%5Cmathbf%7Bw%7D%7C%5Cmathbf%7BD%7D)%20=%20%5Cfrac%7BP(D%7C%5Cmathbf%7Bw%7D)P(%5Cmathbf%7Bw%7D)%7D%7Bz%7D%20%5Cpropto%20P(%5Cmathbf%7BD%7D%7C%5Cmathbf%7Bw%7D)P(%5Cmathbf%7Bw%7D)"></p>
<p>For inference tasks, the parameters are the most important since they embed the relationship between the predictors and the outcome. However, both methods lead to a single solution of <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D">. In fact, there are many <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"> that may fit the data well and are worth considering. This argument is stronger for predictive tasks where the actual values of parameters <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"> are less of interest.</p>
<p>Bayesians say: let’s go directly from data to predictions, accounting for the variability of the parameters without having to estimate them:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cunderbrace%7BD%7D_%7B%5Ctext%7BData%7D%7D%20%5Crightarrow%20%5Cunderbrace%7By%7D_%7B%5Ctext%7BPredictions%7D%7D"></p>
<p>This leads to the posterior predictive distribution:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(y_i%7Cx_i,D)%20=%20%5Cint_w%20P(y_i%7Cx_i,w,D)%5C,dw"></p>
<p>The equation says: for a test point <img src="https://latex.codecogs.com/png.latex?i">, we consider every possible value of the regression parameters and take a weighted average of their predicted values by integrating them out. The formula above can be further broken down into a product of the likelihood and posterior:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(y_i%20%5Cmid%20x_i,%20D)%20=%20%5Cint_w%20%5Cunderbrace%7BP(y_i%20%5Cmid%20x_i,%20w)%7D_%7B%5Ctext%7BLikelihood%7D%7D%20%5C,%20%5Cunderbrace%7BP(w%20%5Cmid%20D)%7D_%7B%5Ctext%7BPosterior%7D%7D%20%5C,%20dw"></p>
<p>Here is where the magic happens. The likelihood <img src="https://latex.codecogs.com/png.latex?P(y_i%7Cx_i,w)"> is Gaussian. The posterior <img src="https://latex.codecogs.com/png.latex?P(w%20%5Cmid%20D)%20=%20%5Cfrac%7BP(D%7Cw)P(w)%7D%7Bz%7D">, if we assume a Gaussian prior <img src="https://latex.codecogs.com/png.latex?P(w)"> (just like we do with Ridge regression), is also Gaussian. Two Gaussians multiplied together is still a Gaussian, so <img src="https://latex.codecogs.com/png.latex?P(y%7Cx,D)"> is also a Gaussian!</p>
<p>Now that is just one test case. We can extend the same idea to more than one test point:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(y_*%20%5Cmid%20D,%20%5Cmathbf%7Bx%7D)%20%5Csim%20%5Cmathcal%7BN%7D(%5Cmu_%7By_*%7CD%7D,%20%5CSigma_%7By_*%7CD%7D)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?y_*"> is the test dataset.</p>
<section id="gaussian-processes-assumption" class="level3">
<h3 class="anchored" data-anchor-id="gaussian-processes-assumption">Gaussian Processes Assumption</h3>
<p>Now the question becomes: how do we find <img src="https://latex.codecogs.com/png.latex?%5Cmu_%7By_*%7CD%7D"> and <img src="https://latex.codecogs.com/png.latex?%5CSigma_%7By_*%7CD%7D">? The key assumption is that our training data and test data <strong>jointly</strong> follow a <strong>multivariate normal distribution (MVN)</strong>:</p>
<p><img src="https://latex.codecogs.com/png.latex?P%5Cleft(%5Cbegin%7Bbmatrix%7D%20y_1%20%5C%5C%20%5Cvdots%20%5C%5C%20y_n%20%5C%5C%20y_*%20%5Cend%7Bbmatrix%7D,%20(x_1,%20%5Cldots,%20x_n),%20x_*%5Cright)%20%5Csim%20%5Cmathcal%7BN%7D(%5Cmu,%20%5CSigma)"></p>
<p>where the covariance matrix <img src="https://latex.codecogs.com/png.latex?%5CSigma"> is represented via a kernel function <img src="https://latex.codecogs.com/png.latex?K">, with <img src="https://latex.codecogs.com/png.latex?K_%7Bij%7D%20=%20k(x_i,%20x_j)">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5CSigma%20=%20%5Cbegin%7Bbmatrix%7D%20K%20&amp;%20K_*%20%5C%5C%20K_*%5ET%20&amp;%20K_%7B**%7D%20%5Cend%7Bbmatrix%7D"></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?K"> — an <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20n"> matrix of kernel evaluations between all pairs of training points, where entry <img src="https://latex.codecogs.com/png.latex?K_%7Bij%7D%20=%20k(x_i,%20x_j)">. This is the covariance structure among the observed data.</li>
<li><img src="https://latex.codecogs.com/png.latex?K_*"> — an <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%201"> vector of kernel evaluations between each training point and the test point <img src="https://latex.codecogs.com/png.latex?x_*">, where entry <img src="https://latex.codecogs.com/png.latex?K_%7B*i%7D%20=%20k(x_i,%20x_*)">. This is what links the training data to the test point.</li>
<li><img src="https://latex.codecogs.com/png.latex?K_*%5ET"> — the transpose of <img src="https://latex.codecogs.com/png.latex?K_*">, a <img src="https://latex.codecogs.com/png.latex?1%20%5Ctimes%20n"> vector. It appears in the lower left to keep the matrix symmetric, as a covariance matrix must be.</li>
<li><img src="https://latex.codecogs.com/png.latex?K_%7B**%7D"> — a scalar, the kernel evaluation of the test point with itself, <img src="https://latex.codecogs.com/png.latex?k(x_*,%20x_*)">. This is the prior variance of the test point before seeing any data.</li>
</ul>
<p>And what about Gaussian Processes? They are essentially MVN. The posterior predictive distribution can now be defined as follows (math derivation omitted):</p>
<p><img src="https://latex.codecogs.com/png.latex?P(y_*%20%5Cmid%20D,%20%5Cmathbf%7Bx%7D)%20%5Csim%20%5Cmathcal%7BN%7D(%5Cmu_%7By_*%7CD%7D,%20%5CSigma_%7By_*%7CD%7D)"></p>
<p>where</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmu_%7By_*%7CD%7D%20=%20K_*%5ET(K%20+%20%5Csigma%5E2%20I)%5E%7B-1%7Dy"></p>
<p>and</p>
<p><img src="https://latex.codecogs.com/png.latex?%5CSigma_%7By_*%7CD%7D%20=%20K_%7B**%7D%20-%20K_*%5ET(K%20+%20%5Csigma%5E2%20I)%5E%7B-1%7DK_*"></p>
</section>
<section id="gaussian-noise" class="level3">
<h3 class="anchored" data-anchor-id="gaussian-noise">Gaussian Noise</h3>
<p>In the example above, we treat the observed values <img src="https://latex.codecogs.com/png.latex?y"> as the true values of the underlying function <img src="https://latex.codecogs.com/png.latex?f">. However, in many applications this is not the case. The observed values are noisy, with an independent noise term layered on top:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Chat%7BY%7D_i%20=%20f_i%20+%20%5Cepsilon_i"></p>
<p>In this case the covariance matrix becomes <img src="https://latex.codecogs.com/png.latex?%5Chat%7B%5CSigma%7D%20=%20%5CSigma%20+%20%5Csigma%5E2%5Cmathbf%7BI%7D">, and the Gaussian Process posterior distribution leads to:</p>
<p><img src="https://latex.codecogs.com/png.latex?Y_*%20%5Cmid%20(Y_1%20=%20y_1,%20%5Cldots,%20Y_n%20=%20y_n,%20%5Cmathbf%7Bx%7D_1,%20%5Cldots,%20%5Cmathbf%7Bx%7D_n)%20%5Csim%20%5Cmathcal%7BN%7D%5C!%5Cleft(K_*%5E%5Ctop%20(K%20+%20%5Csigma%5E2%20I)%5E%7B-1%7D%20y,%5C%20K_%7B**%7D%20+%20%5Csigma%5E2%20I%20-%20K_*%5E%5Ctop%20(K%20+%20%5Csigma%5E2%20I)%5E%7B-1%7D%20K_*%5Cright)"></p>
<p>To bring everything full circle: we bypass the estimation of regression parameters but are still able to make predictions. With some observed data, we can obtain a distribution for the values of the test data.</p>
<p>Yet the assumption and formulation can seem odd. Why combine training and test data? Why represent the covariance matrix with kernel functions? The core idea of GP is that data points close to each other should yield similar results. Under the GP framework, predictions are made by assuming all data come from the same generative model and examining how close the test data are to the training data via the kernel. It is analogous to estimating your house price based on the house prices in your neighborhood — without building a specific regression model with predictors like number of bedrooms or year built.</p>
<p>To think in MVN terms is a paradigm shift. In most regression settings, individual data points are assumed to have their own distributions. In Gaussian Processes, our data are counted only as a partial observation of one sample from an MVN. To facilitate understanding, we now visit the origin of Gaussian Processes in Stochastic Processes.</p>
</section>
</section>
<section id="gaussian-processes-gp-through-the-lens-of-stochastic-processes" class="level2">
<h2 class="anchored" data-anchor-id="gaussian-processes-gp-through-the-lens-of-stochastic-processes">Gaussian Processes (GP) through the Lens of Stochastic Processes</h2>
<p>By <a href="https://en.wikipedia.org/wiki/Gaussian_process">Wikipedia</a>, a Gaussian Process is a time continuous stochastic process <img src="https://latex.codecogs.com/png.latex?%5C%7BX_t;%20t%20%5Cin%20T%5C%7D"> such that for every finite set of indices <img src="https://latex.codecogs.com/png.latex?t_1,%20%5Cldots,%20t_k"> in the index set <img src="https://latex.codecogs.com/png.latex?T">,</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7BX%7D_%7Bt_1,%5Cldots,t_k%7D%20=%20(X_%7Bt_1%7D,%20%5Cldots,%20X_%7Bt_k%7D)"></p>
<p>is a multivariate Gaussian random variable. Essentially, GP observations are never independent — although collected at different inputs, they are <strong>jointly</strong> Gaussian, correlated with each other through the kernel function. The data points collectively are one realization from the <strong>joint</strong> distribution:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bbmatrix%7D%20f(x_1)%20%5C%5C%20%5Cvdots%20%5C%5C%20f(x_n)%20%5Cend%7Bbmatrix%7D%20%5Csim%20%5Cmathcal%7BN%7D(%5Cmu,%20%5CSigma)"></p>
<p>The covariance structure encoded in <img src="https://latex.codecogs.com/png.latex?K"> means that observing <img src="https://latex.codecogs.com/png.latex?f(x_i)"> says something about <img src="https://latex.codecogs.com/png.latex?f(x_j)"> for nearby <img src="https://latex.codecogs.com/png.latex?x_j">. The most common choice for the covariance structure is the Radial Basis Function (RBF) kernel:</p>
<p><img src="https://latex.codecogs.com/png.latex?k(x_i,%20x_j)%20=%20%5Csigma%5E2%5Cexp%5Cleft(-%5Cfrac%7B%5C%7Cx_i%20-%20x_j%5C%7C%5E2%7D%7B2%5Cell%5E2%7D%5Cright)"></p>
</section>
<section id="gaussian-processes-visualized" class="level2">
<h2 class="anchored" data-anchor-id="gaussian-processes-visualized">Gaussian Processes Visualized</h2>
<p>We have now discussed two views of Gaussian Processes. The <strong>Conditional View</strong>: after observing some points, the remaining points follow an updated Gaussian — the posterior predictive distribution from the regression perspective. And the <strong>Joint View</strong>: all observations together are one draw from a multivariate Gaussian, corresponding to the stochastic process perspective.</p>
<p>In this section, we code GPs in Python to generate plots of both views using the RBF kernel.</p>
<div id="imports" class="cell" data-message="false" data-execution_count="1">
<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> 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> scipy</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> scipy.spatial.distance</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> itertools</span>
<span id="cb1-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="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.gridspec <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> gridspec</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> matplotlib.figure <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Figure</span>
<span id="cb1-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> matplotlib.gridspec <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> SubplotSpec</span>
<span id="cb1-9"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mpl_toolkits.axes_grid1 <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_axes_locatable</span>
<span id="cb1-10"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ndarray <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> KernelMatrix</span>
<span id="cb1-11"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.stats.qmc <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LatinHypercube</span></code></pre></div></div>
</details>
</div>
<div id="gp-class" 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="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> GPreg:</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>, X_train, y_train, X_test, length_scale<span 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>, amplitude<span 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>, keps<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;">1e-8</span>):</span>
<span id="cb2-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.L <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> length_scale</span>
<span id="cb2-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> amplitude</span>
<span id="cb2-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> keps</span>
<span id="cb2-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn <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>.mean_func(X_test)</span>
<span id="cb2-8">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn <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>.kernel_func(X_test, X_test, amplitude<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>.A, length_scale<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>.L) <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;">1e-15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(np.shape(X_test)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb2-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train</span>
<span id="cb2-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_train</span>
<span id="cb2-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_test</span>
<span id="cb2-12">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sin(X_test)</span>
<span id="cb2-13"></span>
<span id="cb2-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> mean_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb2-15">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Zero mean function."""</span></span>
<span id="cb2-16">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.zeros((np.shape(X)[<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="cb2-17"></span>
<span id="cb2-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x, z, amplitude<span 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>, length_scale<span 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-19">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""RBF (squared exponential) kernel."""</span></span>
<span id="cb2-20">        sq_dist <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scipy.spatial.distance.cdist(x, z, 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;">'sqeuclidean'</span>)</span>
<span id="cb2-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> amplitude<span 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> np.exp(<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> sq_dist <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> length_scale<span 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-22"></span>
<span id="cb2-23">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compute_posterior(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb2-24">        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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, amplitude<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>.A, length_scale<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>.L) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(np.shape(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb2-25">        K_s <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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test, amplitude<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>.A, length_scale<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>.L)</span>
<span id="cb2-26">        K_ss <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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test, amplitude<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>.A, length_scale<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>.L) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(np.shape(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb2-27">        K_inv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linalg.inv(K)</span>
<span id="cb2-28">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.dot(K_s.T, np.dot(K_inv, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train))</span>
<span id="cb2-29">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> K_ss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.dot(K_s.T, np.dot(K_inv, K_s))</span>
<span id="cb2-30">        <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;">None</span></span>
<span id="cb2-31"></span>
<span id="cb2-32">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate_random_prior_plots(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, num_points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>, num_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;">5</span>):</span>
<span id="cb2-33">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Plot prior GP samples."""</span></span>
<span id="cb2-34">        X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.expand_dims(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;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, num_points), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-35">        sigma <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>.kernel_func(X, X, amplitude<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>.A, length_scale<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>.L)</span>
<span id="cb2-36">        Y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.multivariate_normal(mean<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.zeros(num_points), cov<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sigma, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_samples)</span>
<span id="cb2-37">        plt.figure(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;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb2-38">        <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_samples):</span>
<span id="cb2-39">            plt.plot(X, Y[i], 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>, marker<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;">"o"</span>, markersize<span 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="cb2-40">        plt.xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$x$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)</span>
<span id="cb2-41">        plt.ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$y = f(x)$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)</span>
<span id="cb2-42">        plt.title(</span>
<span id="cb2-43">            <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>num_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;"> different function realizations at </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_points<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;"> points</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;">"</span></span>
<span id="cb2-44">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sampled from a Gaussian process with exponentiated quadratic kernel"</span></span>
<span id="cb2-45">        )</span>
<span id="cb2-46">        plt.xlim([<span 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>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])</span>
<span id="cb2-47">        plt.show()</span>
<span id="cb2-48"></span>
<span id="cb2-49">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate_posterior_plots(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, num_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;">3</span>):</span>
<span id="cb2-50">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Plot posterior distribution and samples."""</span></span>
<span id="cb2-51">        fig, (ax1, ax2) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(nrows<span 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>, ncols<span 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>, 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;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>))</span>
<span id="cb2-52">        ax1.plot(X, np.sin(X), <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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">sin(x)$"</span>)</span>
<span id="cb2-53">        ax1.fill_between(</span>
<span id="cb2-54">            X.flatten(),</span>
<span id="cb2-55">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn.flatten() <span 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> np.sqrt(np.diag(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn)),</span>
<span id="cb2-56">            <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn.flatten() <span 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> np.sqrt(np.diag(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn)),</span>
<span id="cb2-57">            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;">"red"</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.15</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"95% CI — </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;">2</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\s</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">igma_{test</span><span class="cf" 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;">train}</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>
<span id="cb2-58">        )</span>
<span id="cb2-59">        ax1.plot(X, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r-"</span>, lw<span 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>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><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;">$\m</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">u_{test</span><span class="cf" 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;">train}</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>
<span id="cb2-60">        ax1.plot(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ko"</span>, 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>, 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;">"$(x_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{train}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">, y_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{train}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">)$"</span>)</span>
<span id="cb2-61">        ax1.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$x$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)</span>
<span id="cb2-62">        ax1.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$y$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)</span>
<span id="cb2-63">        ax1.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Posterior predictive distribution"</span>)</span>
<span id="cb2-64">        ax1.legend()</span>
<span id="cb2-65">        ax2.plot(X, np.random.multivariate_normal(mean<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>.muFn.flatten(), cov<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>.Kfn, 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;">5</span>).T, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>)</span>
<span id="cb2-66">        ax2.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$x$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)</span>
<span id="cb2-67">        ax2.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$y$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)</span>
<span id="cb2-68">        ax2.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"5 function realizations from the posterior GP"</span>)</span>
<span id="cb2-69">        ax2.set_xlim([X.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(), X.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()])</span>
<span id="cb2-70">        plt.tight_layout()</span>
<span id="cb2-71">        plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stderr">
<pre><code>&lt;&gt;:52: SyntaxWarning:

invalid escape sequence '\s'

&lt;&gt;:52: SyntaxWarning:

invalid escape sequence '\s'

C:\Users\rwang\AppData\Local\Temp\ipykernel_16496\1627296385.py:52: SyntaxWarning:

invalid escape sequence '\s'
</code></pre>
</div>
</div>
<section id="joint-view" class="level3">
<h3 class="anchored" data-anchor-id="joint-view">Joint View</h3>
<p>Each curve below represents one GP sample, with 40 observed points shown and infinitely many unobserved points implied. One collection of 40 data points is only a partial observation of one realized function.</p>
<div id="cell-joint-view" 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="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">X_train_1d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array([[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.7</span>], [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.2</span>], [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.1</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</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="cb4-2">y_train_1d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sin(X_train_1d)</span>
<span id="cb4-3">X_test_1d <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;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</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="cb4-4"></span>
<span id="cb4-5">gp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> GPreg(X_train_1d, y_train_1d, X_test_1d, <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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-8</span>)</span>
<span id="cb4-6">gp.generate_random_prior_plots()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/joint-view-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2"><img src="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/index_files/figure-html/joint-view-output-1.png" id="joint-view" width="585" height="397" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
</section>
<section id="conditional-view-posterior-predictive-distribution" class="level3">
<h3 class="anchored" data-anchor-id="conditional-view-posterior-predictive-distribution">Conditional View — Posterior Predictive Distribution</h3>
<p>Suppose we have a function <img src="https://latex.codecogs.com/png.latex?f(x)%20=%20%5Csin(x)"> for which we have observed the values at several data points, and we hope to build a posterior predictive distribution over the entire space. Plugging the observed values into the posterior predictive formula:</p>
<p><img src="https://latex.codecogs.com/png.latex?Y_*%20%5Cmid%20(Y_1%20=%20y_1,%20%5Cldots,%20Y_n%20=%20y_n,%20%5Cmathbf%7Bx%7D_1,%20%5Cldots,%20%5Cmathbf%7Bx%7D_n)%20%5Csim%20%5Cmathcal%7BN%7D%5C!%5Cleft(K_*%5E%5Ctop%20(K%20+%20%5Csigma%5E2%20I)%5E%7B-1%7D%20y,%5C%20K_%7B**%7D%20+%20%5Csigma%5E2%20I%20-%20K_*%5E%5Ctop%20(K%20+%20%5Csigma%5E2%20I)%5E%7B-1%7D%20K_*%5Cright)"></p>
<p>we get the posterior predictive distribution at each test point:</p>
<div id="cell-conditional-view" 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="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">gp.compute_posterior()</span>
<span id="cb5-2">gp.generate_posterior_plots(X_test_1d, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/conditional-view-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3"><img src="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/index_files/figure-html/conditional-view-output-1.png" id="conditional-view" width="565" height="565" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
<p>The characteristic football/sausage shape reflects low variance around observed values and high variance for points far from the training data. Statistically, 95% of samples drawn from the posterior should fall within the shaded 95% confidence interval.</p>
</section>
<section id="why-conditioning-reduces-variance" class="level3">
<h3 class="anchored" data-anchor-id="why-conditioning-reduces-variance">Why Conditioning Reduces Variance</h3>
<p>With a GP, the closer <img src="https://latex.codecogs.com/png.latex?x_*"> is to the training points, the more confident the model becomes, and thus the more variance gets reduced. But why? What role does the kernel play? Let’s unpack the math behind the posterior covariance.</p>
<p>The posterior covariance of a test point <img src="https://latex.codecogs.com/png.latex?x_*"> given training data is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5CSigma_%7By_*%7CD%7D%20=%20K_%7B**%7D%20-%20K_*%5ET%20K%5E%7B-1%7D%20K_*"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?K_%7B**%7D"> is the <em>prior</em> variance of <img src="https://latex.codecogs.com/png.latex?x_*"> — the uncertainty before seeing any data — and <img src="https://latex.codecogs.com/png.latex?K_*%5ET%20K%5E%7B-1%7D%20K_*"> is the variance <em>removed</em> by the training points. Assume <img src="https://latex.codecogs.com/png.latex?n"> training points and a single test point <img src="https://latex.codecogs.com/png.latex?x_*">, with <img src="https://latex.codecogs.com/png.latex?K"> as <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20n">, <img src="https://latex.codecogs.com/png.latex?K_*"> as <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%201">, and <img src="https://latex.codecogs.com/png.latex?K_*%5ET"> as <img src="https://latex.codecogs.com/png.latex?1%20%5Ctimes%20n">. The full product is a scalar:</p>
<p><img src="https://latex.codecogs.com/png.latex?K_*%5ET%20K%5E%7B-1%7D%20K_*%20=%20%5Cunderbrace%7B(1%20%5Ctimes%20n)%7D_%7BK_*%5ET%7D%20%5Cunderbrace%7B(n%20%5Ctimes%20n)%7D_%7BK%5E%7B-1%7D%7D%20%5Cunderbrace%7B(n%20%5Ctimes%201)%7D_%7BK_*%7D%20=%20(1%20%5Ctimes%201)"></p>
<p>Given the <a href="https://en.wikipedia.org/wiki/Definite_matrix">positive definite</a> nature of kernels, this quantity is always positive — it can be thought of as the total amount of variance removed from the test data.</p>
<p>To see how much variance is removed, let’s examine the quantity with three training points <img src="https://latex.codecogs.com/png.latex?(x_1,%20x_2,%20x_3)"> and one test point <img src="https://latex.codecogs.com/png.latex?x_*">. Set <img src="https://latex.codecogs.com/png.latex?a%20=%20k(x_*,%20x_1)">, <img src="https://latex.codecogs.com/png.latex?b%20=%20k(x_*,%20x_2)">, <img src="https://latex.codecogs.com/png.latex?c%20=%20k(x_*,%20x_3)">, with <img src="https://latex.codecogs.com/png.latex?m_%7Bij%7D"> denoting entries of <img src="https://latex.codecogs.com/png.latex?K%5E%7B-1%7D">:</p>
<p><img src="https://latex.codecogs.com/png.latex?K_*%5ET%20K%5E%7B-1%7D%20K_*%20=%20%5Cbegin%7Bbmatrix%7D%20a%20&amp;%20b%20&amp;%20c%20%5Cend%7Bbmatrix%7D%0A%5Cbegin%7Bbmatrix%7D%20m_%7B11%7D%20&amp;%20m_%7B12%7D%20&amp;%20m_%7B13%7D%20%5C%5C%20m_%7B21%7D%20&amp;%20m_%7B22%7D%20&amp;%20m_%7B23%7D%20%5C%5C%0Am_%7B31%7D%20&amp;%20m_%7B32%7D%20&amp;%20m_%7B33%7D%20%5Cend%7Bbmatrix%7D%0A%5Cbegin%7Bbmatrix%7D%20a%20%5C%5C%20b%20%5C%5C%20c%20%5Cend%7Bbmatrix%7D%0A=%20m_%7B11%7Da%5E2%20+%20m_%7B22%7Db%5E2%20+%20m_%7B33%7Dc%5E2%20+%202m_%7B12%7Dab%20+%202m_%7B13%7Dac%20+%202m_%7B23%7Dbc"></p>
<p>The <strong>squared terms</strong> <img src="https://latex.codecogs.com/png.latex?a%5E2,%20b%5E2,%20c%5E2"> capture how similar <img src="https://latex.codecogs.com/png.latex?x_*"> is to each individual training point. The <strong>cross terms</strong> <img src="https://latex.codecogs.com/png.latex?ab,%20ac,%20bc"> capture interactions between <img src="https://latex.codecogs.com/png.latex?x_*">’s relationships to different training points and are treated as constants driven by the training data structure.</p>
<p>With the RBF kernel, each similarity score <img src="https://latex.codecogs.com/png.latex?k(x_*,%20x_i)"> approaches 1 when <img src="https://latex.codecogs.com/png.latex?x_*"> is close to <img src="https://latex.codecogs.com/png.latex?x_i"> and 0 when far away. This means one nearby training point gives moderate variance reduction; two nearby training points give larger reduction; and no nearby training points means the GP falls back to its prior. The variance reduction is therefore a <strong>vote</strong> from each training point, weighted by proximity to <img src="https://latex.codecogs.com/png.latex?x_*">. GP uncertainty is <em>locally determined</em> — confidence builds up around observed points and fades in unexplored regions. As we will see in the second blog of the series, this is exactly the signal the acquisition function uses to decide where to sample next.</p>
</section>
</section>
<section id="higher-dimension-gp" class="level2">
<h2 class="anchored" data-anchor-id="higher-dimension-gp">Higher Dimension GP</h2>
<p>So far we have focused on simple 1D examples. In the real world, data points come in much higher dimensions. The distance calculation remains the same: for each pair of data points, we take the distances across each feature and compute the norm of the difference vector. The example below extends the GP to a 2D input space, modeling the underlying function <img src="https://latex.codecogs.com/png.latex?f(x_1,%20x_2)%20=%20x_1%20%5Cexp(-x_1%5E2%20-%20x_2%5E2)">.</p>
<div id="cell-high-dim-gp" class="cell" data-fig-height="4" data-fig-width="9" data-execution_count="5">
<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="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> HighDimGPreg:</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_train, y_train, X_test, L<span 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>, A<span 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>, keps<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;">1e-8</span>):</span>
<span id="cb6-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.L <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> L</span>
<span id="cb6-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.A <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> A</span>
<span id="cb6-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> keps</span>
<span id="cb6-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn <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>.mean_func(X_test)</span>
<span id="cb6-8">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn <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>.kernel_func(X_test, X_test) <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;">1e-15</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(X_test.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb6-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train</span>
<span id="cb6-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_train.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="cb6-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_test</span>
<span id="cb6-12">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_test <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;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.exp(<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;">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;">2</span> <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;">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="cb6-13"></span>
<span id="cb6-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> mean_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X):</span>
<span id="cb6-15">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Zero mean function."""</span></span>
<span id="cb6-16">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.zeros((X.shape[<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="cb6-17"></span>
<span id="cb6-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x, z):</span>
<span id="cb6-19">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""RBF kernel with amplitude and length scale."""</span></span>
<span id="cb6-20">        sq_dist <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scipy.spatial.distance.cdist(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>.L, 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>.L, 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;">'sqeuclidean'</span>)</span>
<span id="cb6-21">        <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>.A<span 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> np.exp(<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> sq_dist)</span>
<span id="cb6-22"></span>
<span id="cb6-23">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compute_posterior(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb6-24">        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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb6-25">        K_s <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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_train, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test)</span>
<span id="cb6-26">        K_ss <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>.kernel_func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test) <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>.keps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.eye(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.X_test.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb6-27">        K_inv <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.linalg.inv(K)</span>
<span id="cb6-28">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.muFn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.dot(K_s.T, np.dot(K_inv, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y_train))</span>
<span id="cb6-29">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> K_ss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> np.dot(K_s.T, np.dot(K_inv, K_s))</span>
<span id="cb6-30">        <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;">None</span></span>
<span id="cb6-31"></span>
<span id="cb6-32">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate_plots(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, X, nx):</span>
<span id="cb6-33">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Generate heatmap plots of the posterior mean and uncertainty."""</span></span>
<span id="cb6-34">        mu <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>.muFn.ravel()</span>
<span id="cb6-35">        std <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.sqrt(np.diag(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.Kfn))</span>
<span id="cb6-36">        fig, axes <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;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</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;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb6-37">        im0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].imshow(</span>
<span id="cb6-38">            mu.reshape(nx, nx), origin<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;">'lower'</span>, 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;">'viridis'</span>,</span>
<span id="cb6-39">            extent<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 class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(), X[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(), X[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(), X[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()]</span>
<span id="cb6-40">        )</span>
<span id="cb6-41">        axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Posterior Mean'</span>)</span>
<span id="cb6-42">        axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$x_1$'</span>)</span>
<span id="cb6-43">        axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$x_2$'</span>)</span>
<span id="cb6-44">        plt.colorbar(im0, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb6-45">        im1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].imshow(</span>
<span id="cb6-46">            std.reshape(nx, nx), origin<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;">'lower'</span>, 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;">'plasma'</span>,</span>
<span id="cb6-47">            extent<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 class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(), X[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(), X[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">min</span>(), X[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>()]</span>
<span id="cb6-48">        )</span>
<span id="cb6-49">        axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Posterior Std Dev (Uncertainty)'</span>)</span>
<span id="cb6-50">        axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$x_1$'</span>)</span>
<span id="cb6-51">        axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$x_2$'</span>)</span>
<span id="cb6-52">        plt.colorbar(im1, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>axes[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb6-53">        plt.tight_layout()</span>
<span id="cb6-54">        plt.show()</span>
<span id="cb6-55"></span>
<span id="cb6-56"></span>
<span id="cb6-57">nx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span></span>
<span id="cb6-58">n_train <span 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="cb6-59">sampler <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LatinHypercube(d<span 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="cb6-60">X_train_2d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sampler.random(n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n_train)</span>
<span id="cb6-61">X_train_2d[:, <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> (X_train_2d[:, <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="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> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</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="cb6-62">X_train_2d[:, <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> (X_train_2d[:, <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="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> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</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="cb6-63">y_train_2d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> X_train_2d[:, <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> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>X_train_2d[:, <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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> X_train_2d[:, <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="cb6-64"></span>
<span id="cb6-65">X_test_seq <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;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, nx)</span>
<span id="cb6-66">x1, x2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.meshgrid(X_test_seq, X_test_seq)</span>
<span id="cb6-67">X_test_2d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.column_stack([x1.ravel(), x2.ravel()])</span>
<span id="cb6-68"></span>
<span id="cb6-69">gp2d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> HighDimGPreg(X_train_2d, y_train_2d, X_test_2d, L<span 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>, A<span 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>, keps<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;">1e-8</span>)</span>
<span id="cb6-70">gp2d.compute_posterior()</span>
<span id="cb6-71">gp2d.generate_plots(X_test_2d, nx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nx)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/high-dim-gp-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-4"><img src="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/index_files/figure-html/high-dim-gp-output-1.png" id="high-dim-gp" width="933" height="399" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
<p>The <strong>posterior mean</strong> (left) shows the GP’s best estimate of the underlying function across the 2D input space. The color intensity represents the predicted function value — warmer colors indicate higher values, cooler colors indicate lower values. The surface is smooth, as expected from the RBF kernel.</p>
<p>The <strong>posterior uncertainty</strong> (right) shows the posterior standard deviation <img src="https://latex.codecogs.com/png.latex?%5Csigma_%7Btest%7Ctrain%7D"> at each test point — the square root of the diagonal of <img src="https://latex.codecogs.com/png.latex?%5CSigma_%7By_*%7CD%7D">. Dark regions indicate low uncertainty near the 10 Latin Hypercube training points, where variance reduction is large. Bright regions indicate high uncertainty far from all training points, where the posterior falls back toward the prior. With only 10 training points over a 2D space, large portions of the input space remain uncertain — illustrating precisely why efficient sampling strategies like BO matter when evaluations are expensive.</p>
</section>
<section id="gp-kernels-and-parameters" class="level2">
<h2 class="anchored" data-anchor-id="gp-kernels-and-parameters">GP Kernels and Parameters</h2>
<p>So far we have only used the RBF kernel:</p>
<p><img src="https://latex.codecogs.com/png.latex?k(x_i,%20x_j)%20=%20%5Csigma%5E2%5Cexp%5Cleft(-%5Cfrac%7B%5C%7Cx_i%20-%20x_j%5C%7C%5E2%7D%7B2%5Cell%5E2%7D%5Cright)"></p>
<p>where two hyperparameters are required: <img src="https://latex.codecogs.com/png.latex?%5Csigma"> (amplitude) and <img src="https://latex.codecogs.com/png.latex?%5Cell"> (lengthscale). In practice, these parameters are unknown and usually estimated via Maximum Likelihood Estimation. A great reference is <a href="https://peterroelants.github.io/posts/gaussian-process-kernel-fitting/">Gaussian processes (2/3) — Fitting a Gaussian process kernel</a>.</p>
<p>Each parameter affects the shape of the kernel function and the resulting GP. Let’s first look at how the parameters affect the kernel function itself:</p>
<div id="cell-gp-kernel-distance" class="cell" data-execution_count="6">
<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"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Reference: Roelants, P. (2019). Gaussian Processes (3/3) - Exploring Kernels.</span></span>
<span id="cb7-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># https://peterroelants.github.io/posts/gaussian-process-kernels/</span></span>
<span id="cb7-3"></span>
<span id="cb7-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> exponentiated_quadratic(xa, xb, amplitude<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>, length_scale<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="cb7-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""RBF kernel with explicit hyperparameters."""</span></span>
<span id="cb7-6">    sq_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scipy.spatial.distance.cdist(xa, xb, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sqeuclidean"</span>)</span>
<span id="cb7-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> amplitude<span 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> np.exp(<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> sq_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> length_scale<span 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-8"></span>
<span id="cb7-9">xlim <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;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb7-10">X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.expand_dims(np.linspace(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>xlim, 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;">75</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb7-11">zero <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>
<span id="cb7-12"></span>
<span id="cb7-13">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(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;">5.4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb7-14"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ls, amp, label <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [</span>
<span id="cb7-15">    (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" 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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">ell = 1$, $</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;">sigma = 1$"</span>),</span>
<span id="cb7-16">    (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" 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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">ell = 0.5$, $</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;">sigma = 1$"</span>),</span>
<span id="cb7-17">    (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="st" 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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">ell = 1$, $</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;">sigma = 0.5$"</span>),</span>
<span id="cb7-18">    (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="st" 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="st" style="color: #20794D;
background-color: null;
font-style: inherit;">ell = 0.5$, $</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;">sigma = 0.5$"</span>),</span>
<span id="cb7-19">]:</span>
<span id="cb7-20">    Σ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> exponentiated_quadratic(xa<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>zero, xb<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X, amplitude<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>amp, length_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ls)</span>
<span id="cb7-21">    ax.plot(X[:, <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>, :], label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>label)</span>
<span id="cb7-22"></span>
<span id="cb7-23">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$x_a - x_b$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb7-24">ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$K(x_a,x_b)$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb7-25">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Exponentiated quadratic kernel"</span>)</span>
<span id="cb7-26">ax.set_ylim((<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;">1.1</span>))</span>
<span id="cb7-27">ax.set_xlim(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>xlim)</span>
<span id="cb7-28">ax.legend(loc<span 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-29">plt.tight_layout()</span>
<span id="cb7-30">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/gp-kernel-distance-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-5"><img src="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/index_files/figure-html/gp-kernel-distance-output-1.png" id="gp-kernel-distance" width="506" height="277" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
<p>Now let’s see how the parameters affect the GP samples themselves:</p>
<div id="cell-gp-kernel-samples" 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="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;"># Reference: Roelants, P. (2019). Gaussian Processes (3/3) - Exploring Kernels.</span></span>
<span id="cb8-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># https://peterroelants.github.io/posts/gaussian-process-kernels/</span></span>
<span id="cb8-3"></span>
<span id="cb8-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> sample_from_kernel(</span>
<span id="cb8-5">    covariance: KernelMatrix, nb_of_samples: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, nb_of_realizations: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb8-6">) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> KernelMatrix:</span>
<span id="cb8-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Draw sample functions from a covariance matrix."""</span></span>
<span id="cb8-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> np.random.multivariate_normal(</span>
<span id="cb8-9">        mean<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.zeros(nb_of_samples), cov<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>covariance, size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nb_of_realizations</span>
<span id="cb8-10">    ).T</span>
<span id="cb8-11"></span>
<span id="cb8-12"></span>
<span id="cb8-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_kernel(</span>
<span id="cb8-14">    X: KernelMatrix, y: KernelMatrix, covariance: KernelMatrix,</span>
<span id="cb8-15">    description: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, fig: Figure, subplot_spec: SubplotSpec,</span>
<span id="cb8-16">    xlim: <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 class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>], scatter: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</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;">False</span>, rotate_x_labels: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</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;">False</span>,</span>
<span id="cb8-17">) <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;">None</span>:</span>
<span id="cb8-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Visualize a kernel through samples and its covariance matrix."""</span></span>
<span id="cb8-19">    grid_spec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gridspec.GridSpecFromSubplotSpec(</span>
<span id="cb8-20">        <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>, width_ratios<span 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="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], height_ratios<span 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="cb8-21">        wspace<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.18</span>, hspace<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.0</span>, subplot_spec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>subplot_spec,</span>
<span id="cb8-22">    )</span>
<span id="cb8-23">    ax1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fig.add_subplot(grid_spec[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb8-24">    ax2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fig.add_subplot(grid_spec[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb8-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> scatter:</span>
<span id="cb8-26">        <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>(y.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]):</span>
<span id="cb8-27">            ax1.scatter(X, y[:, i], 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.8</span>, s<span 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-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb8-29">        <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>(y.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]):</span>
<span id="cb8-30">            ax1.plot(X, y[:, i], 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.8</span>)</span>
<span id="cb8-31">    ax1.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$y$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</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;">0</span>)</span>
<span id="cb8-32">    ax1.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$x$"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</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;">0</span>)</span>
<span id="cb8-33">    ax1.set_xlim(xlim)</span>
<span id="cb8-34">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> rotate_x_labels:</span>
<span id="cb8-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> label <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ax1.get_xticklabels():</span>
<span id="cb8-36">            label.set_rotation(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>)</span>
<span id="cb8-37">    ax1.set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Samples from </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>description<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="cb8-38">    im <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ax2.imshow(covariance, 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;">"YlGnBu"</span>)</span>
<span id="cb8-39">    divider <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_axes_locatable(ax2)</span>
<span id="cb8-40">    cax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> divider.append_axes(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"right"</span>, size<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;">"5%"</span>, pad<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="cb8-41">    cbar <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.colorbar(im, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax2, cax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cax)</span>
<span id="cb8-42">    cbar.ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$K(X,X)$"</span>, fontsize<span 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="cb8-43">    ax2.set_title(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Covariance matrix</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>description<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="cb8-44">    ax2.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X"</span>, fontsize<span 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>, 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;">0</span>)</span>
<span id="cb8-45">    ax2.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X"</span>, fontsize<span 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>, 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;">0</span>)</span>
<span id="cb8-46">    nb_ticks <span 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="cb8-47">    ticks <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>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(xlim[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], xlim[<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>
<span id="cb8-48">    ticks_idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.rint(</span>
<span id="cb8-49">        np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ticks), num<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>(nb_ticks, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ticks))) <span 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="cb8-50">    ).astype(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)</span>
<span id="cb8-51">    ticks <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>(np.array(ticks)[ticks_idx])</span>
<span id="cb8-52">    ax2.set_xticks(np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</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 class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ticks)))</span>
<span id="cb8-53">    ax2.set_yticks(np.linspace(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</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 class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(ticks)))</span>
<span id="cb8-54">    ax2.set_xticklabels(ticks)</span>
<span id="cb8-55">    ax2.set_yticklabels(ticks)</span>
<span id="cb8-56">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> rotate_x_labels:</span>
<span id="cb8-57">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> label <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ax2.get_xticklabels():</span>
<span id="cb8-58">            label.set_rotation(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>)</span>
<span id="cb8-59">    ax2.grid(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb8-60"></span>
<span id="cb8-61"></span>
<span id="cb8-62"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_kernel_combinations(amplitudes, length_scales, nb_of_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;">150</span>, nb_of_realizations<span 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-63">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Plot GP samples and covariance matrices for all combinations of hyperparameters."""</span></span>
<span id="cb8-64">    xlim <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;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb8-65">    X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.expand_dims(np.linspace(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>xlim, nb_of_samples), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb8-66">    combinations <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>(itertools.product(amplitudes, length_scales))</span>
<span id="cb8-67">    n_combos <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>(combinations)</span>
<span id="cb8-68">    fig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.figure(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;">7</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_combos))</span>
<span id="cb8-69">    gs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gridspec.GridSpec(n_combos, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figure<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>fig, wspace<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>, hspace<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>)</span>
<span id="cb8-70">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, (amplitude, length_scale) <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>(combinations):</span>
<span id="cb8-71">        Σ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> exponentiated_quadratic(xa<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X, xb<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X, amplitude<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>amplitude, length_scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>length_scale)</span>
<span id="cb8-72">        y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sample_from_kernel(covariance<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Σ, nb_of_samples<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nb_of_samples, nb_of_realizations<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nb_of_realizations)</span>
<span id="cb8-73">        plot_kernel(</span>
<span id="cb8-74">            X<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>X, y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y, covariance<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Σ,</span>
<span id="cb8-75">            description<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"$</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;">ell = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>length_scale<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;">sigma = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>amplitude<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="cb8-76">            fig<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>fig, subplot_spec<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>gs[i], xlim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>xlim,</span>
<span id="cb8-77">        )</span>
<span id="cb8-78">    plt.suptitle(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Exponentiated quadratic kernel"</span>, y<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.99</span>)</span>
<span id="cb8-79">    fig.subplots_adjust(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.07</span>, bottom<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.04</span>, right<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.93</span>, top<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.94</span>)</span>
<span id="cb8-80">    plt.show()</span>
<span id="cb8-81"></span>
<span id="cb8-82"></span>
<span id="cb8-83">plot_kernel_combinations(amplitudes<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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10.0</span>], length_scales<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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>])</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/gp-kernel-samples-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-6"><img src="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/index_files/figure-html/gp-kernel-samples-output-1.png" id="gp-kernel-samples" width="705" height="1427" class="figure-img"></a></p>
</figure>
</div>
</div>
</div>
<p>The RBF kernel has two hyperparameters: the length scale <img src="https://latex.codecogs.com/png.latex?%5Cell"> and the amplitude <img src="https://latex.codecogs.com/png.latex?%5Csigma">. The six plots above correspond to all combinations of <img src="https://latex.codecogs.com/png.latex?%5Csigma%20%5Cin%20%5C%7B1,%2010%5C%7D"> and <img src="https://latex.codecogs.com/png.latex?%5Cell%20%5Cin%20%5C%7B0.5,%201,%202%5C%7D">, generated by <code>itertools.product</code> in this order:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: center;">Plot</th>
<th style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Csigma"></th>
<th style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?%5Cell"></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: center;">1</td>
<td style="text-align: center;">1.0</td>
<td style="text-align: center;">0.5</td>
</tr>
<tr class="even">
<td style="text-align: center;">2</td>
<td style="text-align: center;">1.0</td>
<td style="text-align: center;">1.0</td>
</tr>
<tr class="odd">
<td style="text-align: center;">3</td>
<td style="text-align: center;">1.0</td>
<td style="text-align: center;">2.0</td>
</tr>
<tr class="even">
<td style="text-align: center;">4</td>
<td style="text-align: center;">10.0</td>
<td style="text-align: center;">0.5</td>
</tr>
<tr class="odd">
<td style="text-align: center;">5</td>
<td style="text-align: center;">10.0</td>
<td style="text-align: center;">1.0</td>
</tr>
<tr class="even">
<td style="text-align: center;">6</td>
<td style="text-align: center;">10.0</td>
<td style="text-align: center;">2.0</td>
</tr>
</tbody>
</table>
<p><strong>Length scale <img src="https://latex.codecogs.com/png.latex?%5Cell"> controls the smoothness of the function.</strong> At <img src="https://latex.codecogs.com/png.latex?%5Cell%20=%200.5"> (plots 1, 4), the sampled functions are highly wiggly — only points within 0.5 units of each other are considered similar, so the function changes direction rapidly. At <img src="https://latex.codecogs.com/png.latex?%5Cell%20=%201"> (plots 2, 5), functions are smooth at a moderate pace. At <img src="https://latex.codecogs.com/png.latex?%5Cell%20=%202"> (plots 3, 6), the functions are very slow-moving — points up to 2 units apart remain highly correlated, producing long sweeping curves. In the covariance matrix, a larger <img src="https://latex.codecogs.com/png.latex?%5Cell"> spreads correlations further from the diagonal, making the matrix appear more uniformly bright. A smaller <img src="https://latex.codecogs.com/png.latex?%5Cell"> concentrates correlation near the diagonal.</p>
<p><strong>Amplitude <img src="https://latex.codecogs.com/png.latex?%5Csigma"> controls the vertical scale of the function.</strong> At <img src="https://latex.codecogs.com/png.latex?%5Csigma%20=%201"> (plots 1–3), function values stay roughly within <img src="https://latex.codecogs.com/png.latex?%5B-1,%201%5D">. At <img src="https://latex.codecogs.com/png.latex?%5Csigma%20=%2010"> (plots 4–6), they can swing as wide as <img src="https://latex.codecogs.com/png.latex?%5B-10,%2010%5D">, while the smoothness pattern mirrors plots 1–3 exactly since <img src="https://latex.codecogs.com/png.latex?%5Cell"> is unchanged. Comparing plot 1 (<img src="https://latex.codecogs.com/png.latex?%5Cell=0.5">, <img src="https://latex.codecogs.com/png.latex?%5Csigma=1">) to plot 4 (<img src="https://latex.codecogs.com/png.latex?%5Cell=0.5">, <img src="https://latex.codecogs.com/png.latex?%5Csigma=10">): identical wiggliness, but the vertical range is inflated by a factor of 10. <img src="https://latex.codecogs.com/png.latex?%5Csigma"> scales the entire kernel matrix by <img src="https://latex.codecogs.com/png.latex?%5Csigma%5E2">, inflating variance at every point without touching the correlation structure. Think of <img src="https://latex.codecogs.com/png.latex?%5Cell"> as controlling the <em>shape</em> of the functions and <img src="https://latex.codecogs.com/png.latex?%5Csigma"> as controlling their <em>range</em>.</p>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>Gaussian Processes are a powerful and elegant tool for modeling uncertainty. Starting from the regression perspective, we saw how integrating out the parameters leads naturally to the posterior predictive distribution — a Gaussian whose mean and covariance are fully defined by the kernel function. From the stochastic processes perspective, we saw that a GP treats the entire function as a single draw from a multivariate Gaussian, where observations are jointly correlated rather than independent.</p>
<p>The kernel function is the engine of the GP. It encodes how information propagates from observed points to unobserved ones. The closer a test point is to the training points, the more confident the model becomes, and the more variance gets reduced. This variance reduction is not magic — it is a weighted sum of similarities, driven entirely by how close a test point is to the training data.</p>
<p>Back to the Minesweeper analogy: the GP is your mental model of the board. Each observation updates your belief about the surrounding landscape, narrowing uncertainty near revealed squares and leaving it wide open in unexplored corners. In the next blog of the series, we will see how the acquisition function uses that uncertainty map to decide where to click next — and how the full Bayesian Optimization loop comes together.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li><p>P. Roelants. <a href="https://peterroelants.github.io/posts/gaussian-process-tutorial/">Gaussian Processes Tutorial.</a> 2019.</p></li>
<li><p>P. Roelants. <a href="https://peterroelants.github.io/posts/gaussian-process-kernels/">Gaussian Processes (3/3) — Exploring Kernels.</a> 2019.</p></li>
<li><p>K. Weinberger. <a href="https://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote15.html">Gaussian Processes.</a> Cornell CS4780 Machine Learning Lecture Notes. 2018.</p></li>
<li><p>M. Krasserm. <a href="https://krasserm.github.io/2018/03/21/bayesian-optimization/#Optimization-algorithm">Bayesian Optimization.</a> 2018.</p></li>
<li><p>R. B. Gramacy. <a href="https://bookdown.org/rbg/surrogates/chap5.html">Surrogates: Gaussian Process Modeling, Design, and Optimization for the Applied Sciences, Chapter 5.</a> Chapman Hall/CRC, 2020.</p></li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Bayesian Optimization - Gaussian
Processes.”</span> June 14. <a href="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/">https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/</a>.
</div></div></section></div> ]]></description>
  <category>Machine Learning</category>
  <category>Gaussian Processes</category>
  <category>Bayesian</category>
  <guid>https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/</guid>
  <pubDate>Sun, 14 Jun 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2025-06-14-bayesian-optimization-gaussian-processes/sidebar.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Kernel Methods and SVM</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2025-06-01-kernel-methods-and-svm/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>Just like backpropagation is the primitive mathematical engine of AI, kernels are the underlying mechanism of many powerful machine learning algorithms. In fact, the concept of kernels is so fundamental that it can still be found in today’s AI applications, although in a more implicit way.</p>
<p>Despite its importance, the concept of kernels is probably one of the most confusing and thus most underappreciated topics in machine learning. Most data practitioners, like myself, first learned of kernels in the context of Support Vector Machines (SVM), which itself is another hard topic. On the other hand, if you try to learn kernel from its mathematical definition which involves Hilbert spaces, you will easily get lost.</p>
<p>One of the most common interpretation one can find online is that kernels are a way to implicitly map data into a high-dimensional feature space, which allows us to capture complex relationships in the data (shown as Figure.1). While this interpretation is intuitive, it only explains the necessity to go to high-dimension, but does not explain what role kernels have to play in the process.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="kernel-trick.jpg" class="lightbox" data-gallery="quarto-lightbox-gallery-1" title="Kernel trick illustration. Source: Medium"><img src="https://changruiraywang.com/blog/2025-06-01-kernel-methods-and-svm/kernel-trick.jpg" class="img-fluid quarto-figure quarto-figure-center figure-img" style="width:80.0%" alt="Kernel trick illustration. Source: Medium"></a></p>
</figure>
</div>
<figcaption>Kernel trick illustration. Source: <a href="https://medium.com/@zxr.nju/what-is-the-kernel-trick-why-is-it-important-98a98db0961d">Medium</a></figcaption>
</figure>
</div>
<p>In this blog, I try to retell the story of kernels based on my learning notes of many amazing resources, explaining what they are, why they are important, and how they work in the context of machine learning algorithms.</p>
</section>
<section id="what-are-kernels" class="level2">
<h2 class="anchored" data-anchor-id="what-are-kernels">What are Kernels?</h2>
<p>Intuitively speaking, a kernel function <img src="https://latex.codecogs.com/png.latex?K(x,y)"> is a similarity function. It takes two data points as input and returns a number that measures the similarity between the two data points. The similarity measure is calculated based on the inner product of the features of the two data points. The more similar the two data points are, the higher the kernel value. Moreover, which is more important, the similarity is achieved very cost-effectively.</p>
<p>So kernels do only one thing, and they do it extremely well: measuring similarities between two data points with minimal computational overhead.</p>
<p>As a toy example, consider a person’s height and weight as a two-dimension feature vector:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D=(x_1,%5C%20x_2)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?x_1"> is height and <img src="https://latex.codecogs.com/png.latex?x_2"> is weight.</p>
<p>Suppose we have two people <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D"> and <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bz%7D"> with feature vectors <img src="https://latex.codecogs.com/png.latex?(180,%2070)"> and <img src="https://latex.codecogs.com/png.latex?(160,%2050)">, and we want to calculate their similarity:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Clangle%20%5Cmathbf%7Bx%7D,%5Cmathbf%7Bz%7D%20%5Crangle=%20x_1*z_1+x_2*z_2%20=%20180%20%5Ctimes%20160%20+%2070%20%5Ctimes%2050"></p>
<p>Now suppose there is a non-linear, high-dimension feature vector transformed from the original feature vector, that measures the similarity in a more complex way by including the square and interaction terms:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cphi(%5Cmathbf%7Bx%7D)%20=%20(x_1%5E2,%5C%20x_2%5E2,%5C%20%5Csqrt%7B2%7D%5C,x_1%20x_2)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cphi(%5Cmathbf%7Bx%7D)"> is the transformed feature vector.</p>
<p>The inner product of two feature vectors becomes:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Clangle%20%5Cmathbf%7Bx%7D,%20%5Cmathbf%7Bz%7D%20%5Crangle%20=%20180%5E2%20%5Ccdot%20160%5E2%20+%2070%5E2%20%5Ccdot%2050%5E2%20+%20%5Csqrt%7B2%7D%20%5Ccdot%20180%20%5Ccdot%2070%20%5Ccdot%20%5Csqrt%7B2%7D%20%5Ccdot%20160%20%5Ccdot%2050%20=%201%7B,%7D043%7B,%7D290%7B,%7D000"></p>
<p>Notice that this computation calculates the transformed non-linear terms first, then add them up, which is 11 multiplications and 2 summations in total.</p>
<p>However, there actually exists a function that does not require the actual calculation of the transformed high-dimension features and thus makes the computation easier:</p>
<p><img src="https://latex.codecogs.com/png.latex?K(%5Cmathbf%7Bx%7D,%20%5Cmathbf%7Bz%7D)%20=%20(%5Clangle%20%5Cmathbf%7Bx%7D,%20%5Cmathbf%7Bz%7D%20%5Crangle)%5E2%20=%20(x_1%20z_1%20+%20x_2%20z_2)%5E2%20=%20(180%20%5Ctimes%20160%20+%2070%20%5Ctimes%2050)%5E2%20=%201%7B,%7D043%7B,%7D290%7B,%7D000"></p>
<p>The function takes the inner product of the original feature vector and returns the same value. It only takes 3 multiplications and 1 summation — same result, far less computation.</p>
<p>To recap, with the first approach, we have to square and multiply the high-dimension terms: <img src="https://latex.codecogs.com/png.latex?x_1%5E2,x_2%5E2,z_1%5E2,z_2%5E2,x_1%20x_2%20z_1%20z_2">. However, with the second approach, we don’t need such high-dimension terms. We only need the low-dimension terms: <img src="https://latex.codecogs.com/png.latex?x_1x_2,z_1z_2">. The two approaches give the same result, but the second approach is much more computationally efficient.</p>
<p>In math’s language, the function <img src="https://latex.codecogs.com/png.latex?K"> is called a kernel function. It takes low-dimension features as input and returns the inner product of high-dimension features, skipping the step of calculating high-dimension features and their inner product. As an illustration, the kernel approach vs the non-kernel approach can be visualized as:</p>
<p>Low-dimension feature → kernel function with low-dimension features → high-dimension inner product</p>
<p>Low-dimension feature → high-dimension features → high-dimension inner product</p>
<p>The fact that the kernel function allows us to access high-dimension inner product using only low-dimension features is called the ‘Kernel Trick’.</p>
</section>
<section id="why-kernels" class="level2">
<h2 class="anchored" data-anchor-id="why-kernels">Why Kernels?</h2>
<p>The idea of efficient computation of inner products in high-dimension feature spaces is not just a mathematical curiosity. It has profound implications for machine learning algorithms.</p>
<p>In Machine Learning, it is a common feature engineering practice to create more features from existing features. Think of all the non-linear interaction terms: two-way interactions, three-way interactions, and even higher way interactions. To take it to the extreme, one could add as many non-linear terms as possible, with the hope that the practice reveals hidden relationships among the data. That is where Kernels come into play.</p>
<p>Two facts make kernels extremely powerful in machine learning:</p>
<p>(1). Computational Convenience - The transformation of data from low dimension to high dimension in the form of <strong>inner products</strong> of data points.</p>
<p>(2). Kernelized Algorithms - Some machine learning algorithms can actually take <strong>inner products</strong> of data points as input, making it possible to benefit from the computational effectiveness offered by kernels.</p>
<p>We go through the example of linear regression to illustrate both points.</p>
<section id="kernelized-linear-regression" class="level3">
<h3 class="anchored" data-anchor-id="kernelized-linear-regression">Kernelized Linear Regression</h3>
<p>It turns out that the conventional linear regression model can be re-expressed as a linear combination of inner products of input feature vectors.</p>
<p>Imagine a linear regression model with p features. Denote the regression parameter vector as <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D">. The loss function is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(%5Cmathbf%7Bw%7D)%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(%5Cmathbf%7Bw%7D%5ET%20x_i%20-%20y_i)%5E2"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?x_i"> is the <strong>feature vector</strong> of the ith observation, e.g.&nbsp;<img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bpmatrix%7D%20x_%7Bi1%7D%20%5C%5C%20x_%7Bi2%7D%20%5C%5C%20%5Cvdots%20%5C%5C%20x_%7Bip%7D%20%5Cend%7Bpmatrix%7D">.</p>
<p>Gradient descent updates <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"> as:</p>
<p><img src="https://latex.codecogs.com/png.latex?w_%7Bt+1%7D%20=%20w_t%20-%20s%20%5Cleft(%5Cfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Cmathbf%7Bw%7D%7D%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?s"> is the learning rate.</p>
<p>Here, <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Cmathbf%7Bw%7D%7D%20=%202%5Csum_%7Bi=1%7D%5E%7Bn%7D(%5Cmathbf%7Bw%7D%5ET%20%5Cmathbf%7Bx%7D_i%20-%20y_i)"></p>
<p>Therefore, the gradient can be expressed as a linear combination of input feature vectors:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Cmathbf%7Bw%7D%7D%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cunderbrace%7B2(%5Cmathbf%7Bw%7D%5ET%20%5Cmathbf%7Bx%7D_i%20-%20y_i)%7D_%7B%5Cgamma_i%7D%20%5Cmathbf%7Bx%7D_i%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cgamma_i%20%5Cmathbf%7Bx%7D_i"></p>
<p>Now that’s one tiny step along the gradient descent process. Since the parameters <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"> are essentially many of those tiny steps added together, it’s intuitive to think of the parameters <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"> as a linear combination of input feature vectors:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D%20=%20%5Csum%5E%7BJ%7D_j%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cgamma_i%20%5Cmathbf%7Bx%7D_i%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Calpha_i%20%5Cmathbf%7Bx%7D_i"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?J"> is the total steps of gradient descent; <img src="https://latex.codecogs.com/png.latex?%5Calpha_i"> is the new weights of the ith feature vector <img src="https://latex.codecogs.com/png.latex?x_i"> after combining J rounds of <img src="https://latex.codecogs.com/png.latex?%5Cgamma_i">.</p>
<p>The equation above is a very important representation of the linear regression model. It shows that the regression parameters <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bw%7D"> can be expressed as a linear combination of the input feature vectors:</p>
<p>$$ _{i=1}^{n} _i _i=</p>
<em>1 </em>{1st&nbsp;observation} + <em>2 </em>{2nd&nbsp;observation} + + <em>n </em>{nth&nbsp;observation} =
<img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Bpmatrix%7D%20%5Chat%7Bw%7D_1%20%5C%5C%20%5Chat%7Bw%7D_2%20%5C%5C%20%5Cvdots%20%5C%5C%20%5Chat%7Bw%7D_p%20%5Cend%7Bpmatrix%7D">
<p>$$</p>
<p>A huge benefit of the representation is that we can now just do the gradient descent in terms of <img src="https://latex.codecogs.com/png.latex?%5Calpha">, which is of dimension <img src="https://latex.codecogs.com/png.latex?n%5Ctimes%201">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cmathbf%7Bw%7D%5E1%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Calpha_i%5E0%20%5Cmathbf%7Bx%7D_i%20-%20s%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cgamma_i%5E0%20%5Cmathbf%7Bx%7D_i%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(%5Calpha_i%5E0%20-%20s%5Cgamma_i%5E0)%20%5Cmathbf%7Bx%7D_i%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Calpha_i%5E1%20%5Cmathbf%7Bx%7D_i%0A"></p>
<p>If we do gradient descent on the parameters themselves, the dimension could be as high as <img src="https://latex.codecogs.com/png.latex?2%5Ed%20%5Ctimes%201">.</p>
<p>Under the new representation, however, the regression model can be re-expressed as taking the inner product between data points as input:</p>
<p><img src="https://latex.codecogs.com/png.latex?y_j%20=%20w%5ETx_j%20+%20b%20=%20%5Csum_%7Bi=1%7D%5En%5Calpha_i%20%5Cunderbrace%7Bx_ix_j%5ET%7D_%7BK_%7Bij%7D%7D+b"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%7BK_%7Bij%7D%7D"> is the kernel function between the ith and jth observation.</p>
<p>To recap, we’ve shown that the linear regression model can be rewritten as a function of inner products of pairs of observations.</p>
<p>Now if we want to make a prediction for an observation <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bz%7D">, the prediction can be made via:</p>
<p><img src="https://latex.codecogs.com/png.latex?h(%5Cmathbf%7Bz%7D)%20=%20%5Cmathbf%7Bw%7D%5ET%20%5Cmathbf%7Bz%7D%20+%20b%20=%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Calpha_i%20x_i%5ET%20%5Cmathbf%7Bz%7D%20+%20b"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?x_i%5ET%20%5Cmathbf%7Bz%7D"> is the inner product between the ith observation’s feature vector <img src="https://latex.codecogs.com/png.latex?x_i%5ET"> <img src="https://latex.codecogs.com/png.latex?(1%20%5Ctimes%20p)"> and the new observation’s feature vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bz%7D"> <img src="https://latex.codecogs.com/png.latex?(p%20%5Ctimes%201)">.</p>
<p>We are essentially taking the inner product between the new observation with each of the existing observations. And since <img src="https://latex.codecogs.com/png.latex?%5Cunderbrace%7B%5Cmathbf%7Bx%7D_i%5E%5Ctop%7D_%7B%5Cscriptsize(1%20%5Ctimes%20p)%7D%20%5Cunderbrace%7B%5Cvphantom%7B%5Cmathbf%7Bx%7D_i%5E%5Ctop%7D%5Cmathbf%7Bz%7D%7D_%7B%5Cscriptsize(p%20%5Ctimes%201)%7D"> returns a number <img src="https://latex.codecogs.com/png.latex?1%20%5Ctimes%201">, we add up the results according to their weights <img src="https://latex.codecogs.com/png.latex?%5Calpha">.</p>
</section>
<section id="computational-convenience" class="level3">
<h3 class="anchored" data-anchor-id="computational-convenience">Computational Convenience</h3>
<p>Everything looks good so far. But why do we want to re-express the linear regression model as a function of inner products of pairs of observations?</p>
<p>Well, with the original linear regression model, if we want to include as many non-linear features as possible, the number of features will grow exponentially with the number of original features, making it computationally expensive.</p>
<p>Suppose we have a d-dimensional feature vector <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D"> to start with:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bx%7D%20=%20%5Cbegin%7Bpmatrix%7D%20x_1%20%5C%5C%20%5Cvdots%20%5C%5C%20x_d%20%5Cend%7Bpmatrix%7D"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?x_1"> through <img src="https://latex.codecogs.com/png.latex?x_d"> represent the features of an observation. For example, if an observation represents a house, <img src="https://latex.codecogs.com/png.latex?x_1"> could be area, <img src="https://latex.codecogs.com/png.latex?x_2"> could be year built, <img src="https://latex.codecogs.com/png.latex?x_3"> could be number of bedrooms, etc.</p>
<p>To capture non-linear relationships, we can then have a transformation <img src="https://latex.codecogs.com/png.latex?%5Cphi(x)"> such that:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cphi(x)%20=%20%5Cbegin%7Bpmatrix%7D%20x_1%20%5C%5C%20%5Cvdots%20%5C%5C%20x_d%20%5C%5C%20x_1x_2%20%5C%5C%20%5Cvdots%20%5C%5C%20x_%7Bd-1%7Dx_d%20%5Cend%7Bpmatrix%7D"></p>
<p>With a feature vector of length <img src="https://latex.codecogs.com/png.latex?d">, a transformation <img src="https://latex.codecogs.com/png.latex?%5Cphi(x)"> that contains all possible interaction terms is of length <img src="https://latex.codecogs.com/png.latex?2%5Ed">. There are two problems with this approach:</p>
<p>(1). The number of features grows exponentially with the number of original features, making it computationally expensive to calculate the regression parameters.</p>
<p>(2). The inner product of two transformed observations <img src="https://latex.codecogs.com/png.latex?%5Cphi(%5Cmathbf%7Bx%7D)%5E%5Ctop%20%5Cphi(%5Cmathbf%7Bz%7D)"> is also computationally expensive to calculate, since the dimension of the transformed feature vector <img src="https://latex.codecogs.com/png.latex?%5Cphi(x)"> is <img src="https://latex.codecogs.com/png.latex?2%5Ed">.</p>
<p>The kernelized form of the linear regression model, however, allows us to bypass both problems.</p>
<p>First, with the kernelized form, the number of regression parameters is just <img src="https://latex.codecogs.com/png.latex?n">, since each observation gets their own weight <img src="https://latex.codecogs.com/png.latex?%5Calpha_i">.</p>
<p>Second, there is a kernel function that allows us to calculate the inner product of two transformed observations <img src="https://latex.codecogs.com/png.latex?%5Cphi(%5Cmathbf%7Bx%7D)%5E%5Ctop%20%5Cphi(%5Cmathbf%7Bz%7D)"> without actually calculating the transformed features:</p>
<p><img src="https://latex.codecogs.com/png.latex?K(%5Cmathbf%7Bx%7D,%20%5Cmathbf%7Bz%7D)%20=%20%5Cphi(%5Cmathbf%7Bx%7D)%5E%5Ctop%20%5Cphi(%5Cmathbf%7Bz%7D)%20=%201%20%5Ccdot%201%20+%20x_1%20z_1%20+%20x_2%20z_2%20+%20%5Ccdots%20+%20x_1%20x_2%20z_1%20z_2%20+%20%5Ccdots%20+%20x_1%20%5Ccdots%20x_d%20z_1%20%5Ccdots%20z_d%20=%20%5Cprod_%7Bk=1%7D%5E%7Bd%7D%20(1%20+%20x_k%20z_k)"></p>
<p>So instead of calculating the high-dimension features one by one, we can directly get the inner product of the high-dimension features by calculating the kernel function with the original low-dimension features.</p>
<p>Therefore, by re-expressing the linear regression model as a function of inner products of pairs of observations, we can not only estimate the parameters more efficiently but also capture complex non-linear relationships in the data.</p>
</section>
</section>
<section id="types-of-kernels" class="level2">
<h2 class="anchored" data-anchor-id="types-of-kernels">Types of Kernels</h2>
<p>There are many types of kernels, and the choice of which kernel to use depends on the specific problem and data at hand. The most commonly used kernels are Polynomial and Radial Basis Function (RBF) Kernel.</p>
<section id="polynomial-kernel" class="level3">
<h3 class="anchored" data-anchor-id="polynomial-kernel">Polynomial Kernel</h3>
<p>The kernel from the linear regression example is actually a type of <strong>Polynomial</strong> kernel:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctextbf%7BPolynomial:%7D%20%5Cquad%20K(%5Cmathbf%7Bx%7D,%20%5Cmathbf%7Bz%7D)%20=%20(1%20+%20%5Cmathbf%7Bx%7D%5E%5Ctop%20%5Cmathbf%7Bz%7D)%5Ed"></p>
<p>Suppose observation <img src="https://latex.codecogs.com/png.latex?x"> has two features <img src="https://latex.codecogs.com/png.latex?x_1"> and <img src="https://latex.codecogs.com/png.latex?x_2">:</p>
<p><img src="https://latex.codecogs.com/png.latex?x%20=%20%5Cbegin%7Bpmatrix%7D%20x_1%20%5C%5C%20x_2%20%5Cend%7Bpmatrix%7D"></p>
<p>We want to add a bias term plus the square and interaction terms:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cphi(x)%20=%20%5Cbegin%7Bpmatrix%7D%201%20%5C%5C%20x_1%20%5C%5C%20x_2%20%5C%5C%20x_1%20x_2%20%5C%5C%20x_1%5E2%20%5C%5C%20x_2%5E2%20%5Cend%7Bpmatrix%7D"></p>
<p>The inner product of two transformed observations is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Clangle%20%5Cphi(%5Cmathbf%7Bx%7D),%20%5Cphi(%5Cmathbf%7Bz%7D)%20%5Crangle%20=%201%20+%20x_1%20z_1%20+%20x_2%20z_2%20+%20x_1%20x_2%20z_1%20z_2%20+%20x_1%5E2%20z_1%5E2%20+%20x_2%5E2%20z_2%5E2"></p>
<p>This is equivalent to the 2nd degree polynomial kernel:</p>
<p><img src="https://latex.codecogs.com/png.latex?K_%7B%5Ctext%7Bpoly%7D(2)%7D(%5Cmathbf%7Bx%7D,%20%5Cmathbf%7Bz%7D)%20=%20(1%20+%20%5Cmathbf%7Bx%7D%5ET%20%5Cmathbf%7Bz%7D)%5E2"></p>
<p>To verify, expand the squared term:</p>
<p><img src="https://latex.codecogs.com/png.latex?(1%20+%20x_1%20z_1%20+%20x_2%20z_2)%5E2%20=%201%20+%20x_1%20z_1%20+%20x_2%20z_2%20+%20x_1%20x_2%20z_1%20z_2%20+%20x_1%5E2%20z_1%5E2%20+%20x_2%5E2%20z_2%5E2"></p>
<p>In general, the <img src="https://latex.codecogs.com/png.latex?n">-degree polynomial kernel is defined as:</p>
<p><img src="https://latex.codecogs.com/png.latex?K_%7B%5Ctext%7Bpoly%7D(n)%7D(%5Cmathbf%7Bx%7D,%20%5Cmathbf%7Bz%7D)%20=%20(1%20+%20%5Cmathbf%7Bx%7D%5ET%20%5Cmathbf%7Bz%7D)%5En"></p>
<p>Polynomial kernels are building blocks of the most powerful kernel — the radial basis function kernel.</p>
</section>
<section id="the-radial-basis-function-rbf-kernel" class="level3">
<h3 class="anchored" data-anchor-id="the-radial-basis-function-rbf-kernel">The Radial Basis Function (RBF) Kernel</h3>
<p>The <strong>Radial Basis Function</strong> kernel is defined as:</p>
<p><img src="https://latex.codecogs.com/png.latex?K_%7B%5Ctext%7BRBF%7D%7D(x,%20z)%20=%20e%5E%7B-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%20%5C%7Cx%20-%20z%5C%7C%5E2%7D"></p>
<p>It expands the polynomial kernel to the extreme by considering an <strong>infinite</strong> number of interactions.</p>
<p>To see why, expand the exponent:</p>
<p><img src="https://latex.codecogs.com/png.latex?e%5E%7B-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D(x-z)%5ET(x-z)%7D%20=%20e%5E%7B-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D(x%5ET%20x%20-%202x%5ET%20z%20+%20z%5ET%20z)%7D%20=%20e%5E%7B-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D(x%5ET%20x%20+%20z%5ET%20z)%7D%20%5Ccdot%20e%5E%7Bx%5ET%20z%7D"></p>
<p><img src="https://latex.codecogs.com/png.latex?=%20e%5E%7B-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D(x%5ET%20x%20+%20z%5ET%20z)%7D%20%5Ccdot%20e%5E%7Bx%5ET%20z%20+%201%7D%20%5Ccdot%20e%5E%7B-1%7D"></p>
<p>Gathering all terms except <img src="https://latex.codecogs.com/png.latex?e%5E%7Bx%5ET%20z%20+%201%7D"> into a constant <img src="https://latex.codecogs.com/png.latex?C">:</p>
<p><img src="https://latex.codecogs.com/png.latex?=%20C%20%5Ccdot%20e%5E%7Bx%5ET%20z%20+%201%7D"></p>
<p>By definition, <img src="https://latex.codecogs.com/png.latex?e%5Ex%20=%20%5Csum_%7Bn=0%7D%5E%7B%5Cinfty%7D%20%5Cdfrac%7Bx%5En%7D%7Bn!%7D">, so:</p>
<p><img src="https://latex.codecogs.com/png.latex?e%5E%7Bx%5ET%20z%20+%201%7D%20=%20%5Csum_%7Bn=0%7D%5E%7B%5Cinfty%7D%20%5Cfrac%7B(1%20+%20x%5ET%20z)%5En%7D%7Bn!%7D"></p>
<p>Notice that <img src="https://latex.codecogs.com/png.latex?(1%20+%20%5Cmathbf%7Bx%7D%5ET%20%5Cmathbf%7Bz%7D)%5En"> is exactly the <img src="https://latex.codecogs.com/png.latex?n">-degree polynomial kernel <img src="https://latex.codecogs.com/png.latex?K_%7B%5Ctext%7Bpoly%7D(n)%7D">. Therefore, the RBF kernel is an <strong>infinite sum of polynomial kernels</strong> from degree 1 to <img src="https://latex.codecogs.com/png.latex?%5Cinfty">.</p>
<p>The RBF kernel is a very powerful kernel because it can capture complex relationships in the data by considering an infinite number of interactions. It is also widely used in machine learning due to its flexibility and ability to handle non-linear data. The most famous example is Support Vector Machines (SVM) with RBF kernels.</p>
</section>
</section>
<section id="kernelized-support-vector-machines-ksvm" class="level2">
<h2 class="anchored" data-anchor-id="kernelized-support-vector-machines-ksvm">Kernelized Support Vector Machines (KSVM)</h2>
<p>Support Vector Machines (SVM) is a powerful classification algorithm that finds the optimal hyperplane to separate data points of different classes. With all the mathematical details stripped out, the algorithm makes the classification decision based on the inner products between pairs of observations. The decision rule for a new observation <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bz%7D"> is:</p>
<p><img src="https://latex.codecogs.com/png.latex?h(%5Cmathbf%7Bz%7D)%20=%20%5Ctext%7Bsign%7D%5C!%5Cleft(%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Calpha_i%20y_i%5C,%20k(x_i,%20%5Cmathbf%7Bz%7D)%20+%20b%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?x_i"> is the feature vector of the ith training observation, <img src="https://latex.codecogs.com/png.latex?y_i"> is the label of the ith training observation, <img src="https://latex.codecogs.com/png.latex?%5Calpha_i"> is the weight of the ith training observation, <img src="https://latex.codecogs.com/png.latex?k(x_i,%20%5Cmathbf%7Bz%7D)"> is the kernel function that computes the inner product between the ith training observation and the new observation <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bz%7D">, and <img src="https://latex.codecogs.com/png.latex?b"> is the bias term.</p>
<p>Since it takes inner products as input, the kernel trick can be applied. By using a kernel function, we can implicitly map the data into a high-dimensional feature space. This allows SVM to find a non-linear decision boundary in the original input space, which can lead to better classification performance on non-linearly separable data.</p>
<section id="svm-as-a-smart-nearest-neighbor" class="level3">
<h3 class="anchored" data-anchor-id="svm-as-a-smart-nearest-neighbor">SVM as a Smart Nearest Neighbor</h3>
<p>An interesting way to understand SVM is to compare it with the k-nearest neighbor (KNN) algorithm. KNN classifies a new observation <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bz%7D"> based on the majority class of its <img src="https://latex.codecogs.com/png.latex?k"> nearest neighbors in the training data. The decision rule for KNN can be expressed as:</p>
<p><img src="https://latex.codecogs.com/png.latex?h(%5Cmathbf%7Bz%7D)%20=%20%5Ctext%7Bsign%7D%5C!%5Cleft(%5Csum_%7Bi=1%7D%5E%7Bn%7D%20y_i%5C,%20%5Cdelta%5E%7Bnn%7D(x_i,%20%5Cmathbf%7Bz%7D)%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cdelta%5E%7Bnn%7D(x_i,%20%5Cmathbf%7Bz%7D)%20=%201"> if <img src="https://latex.codecogs.com/png.latex?x_i"> is among the <img src="https://latex.codecogs.com/png.latex?k"> nearest neighbors of <img src="https://latex.codecogs.com/png.latex?%5Cmathbf%7Bz%7D">, and <img src="https://latex.codecogs.com/png.latex?0"> otherwise.</p>
<p>SVM can be seen as a smarter version of KNN with three additional components: <img src="https://latex.codecogs.com/png.latex?k(x_i,%20%5Cmathbf%7Bz%7D),%5C%20%5Calpha_i,%5C%20b">.</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?k(x_i,%20%5Cmathbf%7Bz%7D)"> acts as a <strong>distance-based weight</strong> — with the RBF kernel, the test point places a Gaussian around itself and weighs nearby points more heavily.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Calpha_i"> <strong>removes redundant training points</strong> that are already classified correctly (support vectors are the only ones with <img src="https://latex.codecogs.com/png.latex?%5Calpha_i%20%3E%200">).</li>
<li><img src="https://latex.codecogs.com/png.latex?b"> is the <strong>bias term</strong>.</li>
</ul>
<p>Remember the kernel function is a similarity function, so the more similar (or closer) a training point is to the test point, the higher the kernel value, and thus the more influence it has on the classification decision. In the case of the RBF kernel, the influence of a training point decreases exponentially as the distance from the test point increases; whereas the k-nearest neighbor algorithm uses a fixed number of neighbors regardless of their distance, each training point’s influence is equal within the neighborhood.</p>
</section>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>I hope this blog gives you a better understanding of what kernels are, why they are important, and how they work in the context of machine learning algorithms. Kernels are a powerful tool that allows us to capture complex relationships in the data without the computational burden of explicitly calculating high-dimensional features.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li>K. Weinberger. <a href="https://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote13.html">Kernel Methods.</a> Cornell CS4780 Lecture 13. 2018.</li>
<li>K. Weinberger. <a href="https://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote14.html">Support Vector Machines.</a> Cornell CS4780 Lecture 14. 2018.</li>
<li>K. Weinberger. <a href="https://www.youtube.com/watch?v=RwF1esLCG4U">Lecture video: Kernel Methods.</a> Cornell CS4780. 2018.</li>
<li>K. Weinberger. <a href="https://www.youtube.com/watch?v=_PwhiWxHK8o">Lecture video: SVM.</a> Cornell CS4780. 2018.</li>
<li>C. Wu. <a href="https://www.youtube.com/watch?v=b8P9EOJf1h8&amp;list=PLdk2fd27CQzQo1DEthJ5MDBHoC66_1aDN&amp;index=19">1st Lecture on Foundations of Kernel Methods.</a> Northeastern University.</li>
<li>C. Wu. <a href="https://www.youtube.com/watch?v=qdL8kGnmIeo&amp;list=PLdk2fd27CQzQo1DEthJ5MDBHoC66_1aDN&amp;index=20">The 2nd Lecture on Kernels: Moore Aronszajn, Representer Theorems, Kernel Regression.</a> Northeastern University.</li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Kernel Methods and SVM.”</span> June 1. <a href="https://changruiraywang.com/blog/2025-06-01-kernel-methods-and-svm/">https://changruiraywang.com/blog/2025-06-01-kernel-methods-and-svm/</a>.
</div></div></section></div> ]]></description>
  <category>Machine Learning</category>
  <category>SVM</category>
  <category>Kernels</category>
  <guid>https://changruiraywang.com/blog/2025-06-01-kernel-methods-and-svm/</guid>
  <pubDate>Mon, 01 Jun 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2025-06-01-kernel-methods-and-svm/sidebar.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Regularization: Bayesian’s Perspective</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>Regularization is a fundamental concept in machine learning that helps prevent overfitting by adding a penalty term to the loss function. The most common types of regularization are Lasso (L1), Ridge (L2), and Elastic Net (a combination of L1 and L2).</p>
<p>Suppose we have a linear regression model:</p>
<p><img src="https://latex.codecogs.com/png.latex?y_i%20=%20X_i%5ET%5Cbeta%20+%20%5Cepsilon_i"> where <img src="https://latex.codecogs.com/png.latex?%5Cepsilon_i%20%5Csim%20%5Cmathcal%7BN%7D(0,%20%5Csigma%5E2)">.</p>
<p>Lasso (L1) Regularization is formulated as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmin_%7B%5Cmathbf%7B%5Cbeta%7D%7D%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(%5Cmathbf%7B%5Cbeta%7D%5E%5Cintercal%20x_i%20-%20y_i)%5E2%20+%20%5Clambda%20%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_1"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_1%20=%20%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C"> is the L1 norm of the weight vector; <img src="https://latex.codecogs.com/png.latex?%5Clambda"> is the regularization parameter that controls the strength of the penalty.</p>
<p>Ridge (L2) Regularization:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmin_%7B%5Cmathbf%7B%5Cbeta%7D%7D%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(%5Cmathbf%7B%5Cbeta%7D%5E%5Cintercal%20x_i%20-%20y_i)%5E2%20+%20%5Clambda%20%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_2%5E2"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_2%5E2%20=%20%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2"> is the L2 norm of the weight vector; <img src="https://latex.codecogs.com/png.latex?%5Clambda"> is the regularization parameter that controls the strength of the penalty.</p>
<p>Elastic Net:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmin_%7B%5Cmathbf%7B%5Cbeta%7D%7D%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(%5Cmathbf%7B%5Cbeta%7D%5E%5Cintercal%20x_i%20-%20y_i)%5E2%20+%20%5Clambda_1%20%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_1%20+%20%5Clambda_2%20%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_2%5E2"></p>
<p>where the penalty terms are a combination of L1 and L2 norms, with <img src="https://latex.codecogs.com/png.latex?%5Clambda_1"> and <img src="https://latex.codecogs.com/png.latex?%5Clambda_2"> controlling the strength of each penalty.</p>
<p>When I first learned the concept and saw the formulations, the word ‘penalty’ made conceptual sense but little mathematical sense. I understand the intent to ‘penalize’ the model to help prevent overfitting. But why is it done by adding a penalty term consisting of the norm of the coefficients? How does it work mathematically?</p>
<p>When searching for L1 and L2 regularization, one usually comes aross the following graph that shows the constraint regions for L1 and L2 regularization:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="regularization.jpg" class="lightbox" data-gallery="quarto-lightbox-gallery-1" title="L1 and L2 regularization graphically represented. Source: Wikimedia Commons"><img src="https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/regularization.jpg" class="img-fluid quarto-figure quarto-figure-center figure-img" style="width:80.0%" alt="L1 and L2 regularization graphically represented. Source: Wikimedia Commons"></a></p>
</figure>
</div>
<figcaption>L1 and L2 regularization graphically represented. Source: <a href="https://commons.wikimedia.org/wiki/File:Regularization.jpg">Wikimedia Commons</a></figcaption>
</figure>
</div>
<p>The idea is the regularization term controls the values the coefficients can take. For L1 regularization, the constraint is a diamond-shaped region (the L1 norm), while for L2 regularization, the constraint is a circular region (the L2 norm). And because the L1 constraint has corners, it encourages sparsity in the coefficients, while the L2 constraint encourages small but non-zero coefficients.</p>
<p>Where do the constraint shapes come from? It turns out that according to optimization theory, the minimization problem with regularization terms can be reformulated as a constrained optimization problem. For example, the L1 regularization problem:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmin_%7B%5Cmathbf%7B%5Cbeta%7D%7D%20%5Cfrac%7B1%7D%7Bn%7D%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20(%5Cmathbf%7B%5Cbeta%7D%5E%5Cintercal%20x_i%20-%20y_i)%5E2%20+%20%5Clambda%20%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_1"></p>
<p>can be rewritten as:</p>
<p>$<em>{} </em>{i=1}^{n} (^x_i - y_i)^2 $</p>
<p>subject to <img src="https://latex.codecogs.com/png.latex?%5C%7C%5Cmathbf%7B%5Cbeta%7D%5C%7C_1%20%5Cleq%20B"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?B"> is a constant that depends on <img src="https://latex.codecogs.com/png.latex?%5Clambda">. This means that the regularization term can be interpreted as a constraint on the coefficients, which leads to the specific shapes of the constraint regions.</p>
<p>The interpretation makes mathematical sense now. But the chain of thought - adding penalty terms -&gt; reformulating as constrained optimization -&gt; specific shapes of constraint regions - is long and not intuitive. For a long time, I try to remember the steps but still feel it’s a bit of a stretch. Until I came across the Bayesian interpretation of regularization.</p>
</section>
<section id="bayesian-rethinking" class="level2">
<h2 class="anchored" data-anchor-id="bayesian-rethinking">Bayesian Rethinking</h2>
<p>The idea of bayesian interpretation of regularization is simple: we are just telling the model, “Hey, let’s not get too excited about the data.”</p>
<p>The paradigm of Bayesian inference is about jointly considering the likelihood of the data and the prior beliefs of the coefficients, mathematically expressed as:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(%5Cmathbf%7B%5Cbeta%7D%20%7C%20%5Cmathbf%7BX%7D,%20%5Cmathbf%7By%7D)%20%5Cpropto%20P(%5Cmathbf%7By%7D%20%7C%20%5Cmathbf%7BX%7D,%20%5Cmathbf%7B%5Cbeta%7D)%20P(%5Cmathbf%7B%5Cbeta%7D)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?P(%5Cmathbf%7B%5Cbeta%7D%20%7C%20%5Cmathbf%7BX%7D,%20%5Cmathbf%7By%7D)"> is the posterior distribution over the coefficients given the data, <img src="https://latex.codecogs.com/png.latex?P(%5Cmathbf%7By%7D%20%7C%20%5Cmathbf%7BX%7D,%20%5Cmathbf%7B%5Cbeta%7D)"> is the likelihood of the data given the coefficients, <img src="https://latex.codecogs.com/png.latex?P(%5Cmathbf%7B%5Cbeta%7D)"> is the prior distribution over the coefficients.</p>
<p>Frequentists let the data speak for itself and find the best regression coefficients based on the likelihood function (a method called maximum likelihood estimation); whereas bayesians consider both the likelihood function and the prior distribution, saying, “Let’s not get too excited by the data, we put some boundaries on the coefficients based on our prior beliefs.” In fact, Frequentists’ approach is actually equivalent to using a uniform prior distribution in Bayesian’s framework, which means the coefficients are weighted equally and can take any value without any preference.</p>
<p>Why the ‘let the data speak for itself’ and ‘all coefficients are created equal’ approach is not ideal? Because the data can be noisy, and if we rely solely on the likelihood function, we might end up with coefficients that are too large or too small, or coefficientsthat only fit well with the dataset at hand but do not generalize well to new data. By incorporating a prior distribution that’s not uniform distribution, we have a leash to pull the coefficients back towards more reasonable values.</p>
<p>As shown on Figure.1, the uniform distribution, the probability of the coefficient being somewhere between -0.5 and 0.5 is the same as the probability of it being somewhere between 2 and 3. In contrast, the Gaussian distribution concentrates more probability mass around zero, which means we are saying, “We believe the coefficients should be near zero, but we are open to them being larger or smaller if the data strongly suggests it.”</p>
<div id="cell-fig-uniform-vs-gaussian" class="cell" data-execution_count="1">
<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> 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> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-3"><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> norm</span>
<span id="cb1-4"></span>
<span id="cb1-5">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;">5</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;">1000</span>)</span>
<span id="cb1-6"></span>
<span id="cb1-7">uniform <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;">&gt;=</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;">3</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> (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;">3</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;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-8">gaussian <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> norm.pdf(x, scale<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="cb1-9"></span>
<span id="cb1-10">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(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;">8</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.5</span>))</span>
<span id="cb1-11"></span>
<span id="cb1-12">ax.plot(x, uniform,  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;">"#E07B54"</span>, lw<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;">2.5</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;">"Uniform  — all β equally likely"</span>)</span>
<span id="cb1-13">ax.fill_between(x, uniform,  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.10</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;">"#E07B54"</span>)</span>
<span id="cb1-14"></span>
<span id="cb1-15">ax.plot(x, gaussian, 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;">"#7F77DD"</span>, lw<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;">2.5</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;">"Gaussian (σ=1)  — β near zero preferred"</span>)</span>
<span id="cb1-16">ax.fill_between(x, gaussian, 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.10</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;">"#7F77DD"</span>)</span>
<span id="cb1-17"></span>
<span id="cb1-18">ax.annotate(</span>
<span id="cb1-19">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Frequentists: Any value — no preference"</span>,</span>
<span id="cb1-20">    xy<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;">2.2</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;">6</span>), xytext<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;">3.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.28</span>),</span>
<span id="cb1-21">    fontsize<span 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>, 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;">"#E07B54"</span>,</span>
<span id="cb1-22">    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>(arrowstyle<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;">"-&gt;"</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;">"#E07B54"</span>),</span>
<span id="cb1-23">)</span>
<span id="cb1-24">ax.annotate(</span>
<span id="cb1-25">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Bayesians: Concentrated at zero"</span>,</span>
<span id="cb1-26">    xy<span 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>, norm.pdf(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, scale<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>)), xytext<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.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.44</span>),</span>
<span id="cb1-27">    fontsize<span 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>, 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;">"#7F77DD"</span>,</span>
<span id="cb1-28">    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>(arrowstyle<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;">"-&gt;"</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;">"#7F77DD"</span>),</span>
<span id="cb1-29">)</span>
<span id="cb1-30"></span>
<span id="cb1-31">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"β"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb1-32">ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p(β)"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb1-33">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Uniform vs Gaussian prior: equal vs weighted beliefs over β"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb1-34">ax.legend(fontsize<span 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>, framealpha<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>)</span>
<span id="cb1-35">ax.set_xlim(<span 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;">5</span>)</span>
<span id="cb1-36">ax.set_ylim(<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.55</span>)</span>
<span id="cb1-37">ax.spines[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"right"</span>]].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb1-38"></span>
<span id="cb1-39">plt.tight_layout()</span>
<span id="cb1-40">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-uniform-vs-gaussian" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Uniform and Gaussian distributions on the same axes, showing how the Gaussian concentrates probability mass near zero while the uniform treats all values equally">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-uniform-vs-gaussian-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-uniform-vs-gaussian-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2" title="Figure&nbsp;1: Uniform vs Gaussian prior: equal vs weighted beliefs over β"><img src="https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/index_files/figure-html/fig-uniform-vs-gaussian-output-1.png" alt="Uniform and Gaussian distributions on the same axes, showing how the Gaussian concentrates probability mass near zero while the uniform treats all values equally" width="770" height="422" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-uniform-vs-gaussian-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Uniform vs Gaussian prior: equal vs weighted beliefs over β
</figcaption>
</figure>
</div>
</div>
</div>
<p>The shape of the prior distribution corresponds to the type of regularization we are applying. For example, a Laplace prior leads to L1 regularization. On the other hand, a Gaussian prior leads to L2 regularization.</p>
<section id="posterior-formulation" class="level3">
<h3 class="anchored" data-anchor-id="posterior-formulation">Posterior Formulation</h3>
<p>The likelihood function for linear regression is given by:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BL%7D(Y%7CX,%20%5Cbeta)%20=%20%5Cprod_%7Bi=1%7D%5E%7Bn%7D%20%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D%20%5Cexp%5Cleft(-%5Cfrac%7B%5Cepsilon_i%5E2%7D%7B2%5Csigma%5E2%7D%5Cright)%20=%20%5Cleft(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D%5Cright)%5En%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%5Cright)"></p>
<p>The prior distribution over the coefficients <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> can be defined as:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(%5Cbeta)%20=%20%5Cprod_%7Bj=1%7D%5E%7Bp%7D%20P(%5Cbeta_j)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?P(%5Cbeta_j)"> is the prior distribution for each coefficient <img src="https://latex.codecogs.com/png.latex?%5Cbeta_j">.</p>
<p>The posterior distribution over the coefficients is then:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(%5Cbeta%20%7C%20X,%20Y)%20%5Cpropto%20%5Cmathcal%7BL%7D(Y%20%7C%20X,%20%5Cbeta)%20P(%5Cbeta)"></p>
<p><img src="https://latex.codecogs.com/png.latex?=%5Cleft(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D%5Cright)%5En%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%5Cright)*%5Cprod_%7Bj=1%7D%5E%7Bp%7D%20P(%5Cbeta_j)"></p>
<p>Now we plug in the specific prior distributions for Lasso, Ridge, and Elastic Net to see how the posterior distribution leads to the regularization terms in the optimization problem.</p>
</section>
<section id="lasso" class="level3">
<h3 class="anchored" data-anchor-id="lasso">Lasso</h3>
<p>Lasso corresponds to a Laplace prior distribution:</p>
<p><img src="https://latex.codecogs.com/png.latex?P(%5Cbeta)%20=%20%5Cfrac%7B1%7D%7B2b%7D%20%5Cexp%5Cleft(-%5Cfrac%7B%7C%5Cbeta%7C%7D%7Bb%7D%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?b"> is a scale parameter, <img src="https://latex.codecogs.com/png.latex?%7C%5Cbeta%7C"> is the absolute value of the coefficient.</p>
<div id="cell-fig-laplace" 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> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb2-3"></span>
<span id="cb2-4">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;">5</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;">1000</span>)</span>
<span id="cb2-5"></span>
<span id="cb2-6">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb2-7">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#E07B54"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b = 0.5  (tight, sparse)"</span>},</span>
<span id="cb2-8">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#1D9E75"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b = 1.0  (default)"</span>},</span>
<span id="cb2-9">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#7F77DD"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b = 2.0  (flat, less sparse)"</span>},</span>
<span id="cb2-10">]</span>
<span id="cb2-11"></span>
<span id="cb2-12">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(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;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb2-13"></span>
<span id="cb2-14"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> p <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> params:</span>
<span id="cb2-15">    b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b"</span>]</span>
<span id="cb2-16">    density <span 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 class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> np.exp(<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>(x) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> b)</span>
<span id="cb2-17">    ax.plot(x, density, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>], lw<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;">2.5</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>])</span>
<span id="cb2-18">    ax.fill_between(x, density, 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.08</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>])</span>
<span id="cb2-19"></span>
<span id="cb2-20">ax.axvline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</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;">"#888780"</span>, lw<span 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>, 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.5</span>)</span>
<span id="cb2-21"></span>
<span id="cb2-22">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"β"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb2-23">ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p(β)"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb2-24">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Laplace prior across different scale parameters b"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb2-25">ax.legend(fontsize<span 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>, framealpha<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>)</span>
<span id="cb2-26">ax.spines[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"right"</span>]].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb2-27">ax.grid(axis<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;">"y"</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.25</span>)</span>
<span id="cb2-28"></span>
<span id="cb2-29">plt.tight_layout()</span>
<span id="cb2-30">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-laplace" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Three Laplace distributions with scale parameters b=0.5, b=1, and b=2, showing how larger b leads to a flatter, more spread out distribution while smaller b produces a sharper peak at zero">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-laplace-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-laplace-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3" title="Figure&nbsp;2: Laplace (double exponential) prior for b = 0.5, 1, 2"><img src="https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/index_files/figure-html/fig-laplace-output-1.png" alt="Three Laplace distributions with scale parameters b=0.5, b=1, and b=2, showing how larger b leads to a flatter, more spread out distribution while smaller b produces a sharper peak at zero" width="663" height="374" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-laplace-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Laplace (double exponential) prior for b = 0.5, 1, 2
</figcaption>
</figure>
</div>
</div>
</div>
<p>The joint prior distribution over all coefficients is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cprod_%7Bj=1%7D%5E%7Bp%7D%20P(%5Cbeta_j)%20=%20%5Cprod_%7Bj=1%7D%5E%7Bp%7D%20%5Cfrac%7B1%7D%7B2b%7D%20%5Cexp%5Cleft(-%5Cfrac%7B%7C%5Cbeta_j%7C%7D%7Bb%7D%5Cright)"></p>
<p><img src="https://latex.codecogs.com/png.latex?=%20%5Cleft(%5Cfrac%7B1%7D%7B2b%7D%5Cright)%5Ep%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7Bb%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%5Cright)"></p>
<p>Plugging this into the posterior distribution, we get:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BL%7D(Y%20%7C%20X,%20%5Cbeta)%20P(%5Cbeta)%20=%20%5Cleft(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D%5Cright)%5En%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%5Cright)%20*%20%5Cleft(%5Cfrac%7B1%7D%7B2b%7D%5Cright)%5Ep%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7Bb%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%5Cright)"></p>
<p>= <img src="https://latex.codecogs.com/png.latex?%5Cleft(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D%5Cright)%5En%20%5Cleft(%5Cfrac%7B1%7D%7B2b%7D%5Cright)%5Ep%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20-%20%5Cfrac%7B1%7D%7Bb%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%5Cright)"></p>
<p>Now to find the maximum a posteriori (MAP) estimate of <img src="https://latex.codecogs.com/png.latex?%5Cbeta">, we take the log of the posterior distribution:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cunderbrace%7B%5Cunderbrace%7Bnlog(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D)%20+%20plog(%5Cfrac%7B1%7D%7B2b%7D)%7D_%7BConstant%7D%20-%20%5Cunderbrace%7B(%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Cfrac%7B1%7D%7Bb%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C)%7D_%7BMinimize%20this%7D%7D_%7BIn%5C%20order%5C%20to%5C%20maximize%5C%20this%7D"></p>
<p>Now the problem becomes:</p>
<p><img src="https://latex.codecogs.com/png.latex?arg%5Cmin_%7B%5Cbeta%7D%20%5Cleft(%20%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Cfrac%7B1%7D%7Bb%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%20%5Cright)"></p>
<p><img src="https://latex.codecogs.com/png.latex?=arg%5Cmin_%7B%5Cbeta%7D%20%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Cleft(%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Cfrac%7B2%5Csigma%5E2%7D%7Bb%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%20%5Cright)"></p>
<p>Since both <img src="https://latex.codecogs.com/png.latex?%5Csigma"> and <img src="https://latex.codecogs.com/png.latex?b"> are constants, we can ignore the <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D"> term outside the brackets and use a new constant <img src="https://latex.codecogs.com/png.latex?%5Clambda"> to replace the term: <img src="https://latex.codecogs.com/png.latex?%5Clambda%20=%20%5Cfrac%7B2%5Csigma%5E2%7D%7Bb%7D">.</p>
<p>Now we have:</p>
<p><img src="https://latex.codecogs.com/png.latex?arg%5Cmin_%7B%5Cbeta%7D%20%5Cleft(%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Clambda%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%20%5Cright)"></p>
<p><img src="https://latex.codecogs.com/png.latex?=arg%5Cmin_%7B%5Cbeta%7D%20%5Cleft(%20RSS%20+%20%5Clambda%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%20%5Cright)"></p>
<p>which is exactly the Lasso regularization formulation, with <img src="https://latex.codecogs.com/png.latex?%5Clambda%20=%20%5Cfrac%7B2%5Csigma%5E2%7D%7Bb%7D">.</p>
<p>Therefore, the Lasso solutions are actually the maximum a posteriori (MAP) estimates of the coefficients under a Laplace prior distribution.</p>
<p>As we can see from Figure.2, the smaller <img src="https://latex.codecogs.com/png.latex?b"> gets, or equivamently, the larger <img src="https://latex.codecogs.com/png.latex?%5Clambda"> gets, the distribution gets a sharper peak at 0. In other words, the strongger the regularization parameter gets, the more the coefficients get pushed towards zero, encouraging sparsity in the coefficients.</p>
</section>
<section id="ridge" class="level3">
<h3 class="anchored" data-anchor-id="ridge">Ridge</h3>
<p>Ridge regularization corresponds to a Gaussian prior distribution for the coefficients:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(%5Cbeta)%20=%20%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%20%5Ctau%7D%20%5Cexp%5Cleft(-%5Cfrac%7B%5Cbeta%5E2%7D%7B2%5Ctau%5E2%7D%5Cright)%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Ctau%5E2"> is the variance parameter.</p>
<div id="cell-fig-gaussian" 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="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> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb3-2"><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-3"><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> norm</span>
<span id="cb3-4"></span>
<span id="cb3-5">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;">5</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;">1000</span>)</span>
<span id="cb3-6"></span>
<span id="cb3-7">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb3-8">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sigma"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#E07B54"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"σ = 0.5  (tight, strong regularization)"</span>},</span>
<span id="cb3-9">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sigma"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#1D9E75"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"σ = 1.0  (default)"</span>},</span>
<span id="cb3-10">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sigma"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#7F77DD"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"σ = 2.0  (flat, weak regularization)"</span>},</span>
<span id="cb3-11">]</span>
<span id="cb3-12"></span>
<span id="cb3-13">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(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;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb3-14"></span>
<span id="cb3-15"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> p <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> params:</span>
<span id="cb3-16">    density <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> norm.pdf(x, scale<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sigma"</span>])</span>
<span id="cb3-17">    ax.plot(x, density, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>], lw<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;">2.5</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>])</span>
<span id="cb3-18">    ax.fill_between(x, density, 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.08</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>])</span>
<span id="cb3-19"></span>
<span id="cb3-20">ax.axvline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</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;">"#888780"</span>, lw<span 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>, 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.5</span>)</span>
<span id="cb3-21"></span>
<span id="cb3-22">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"β"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb3-23">ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p(β)"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb3-24">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Gaussian prior across different scale parameters σ"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb3-25">ax.legend(fontsize<span 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>, framealpha<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>)</span>
<span id="cb3-26">ax.spines[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"right"</span>]].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb3-27">ax.grid(axis<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;">"y"</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.25</span>)</span>
<span id="cb3-28"></span>
<span id="cb3-29">plt.tight_layout()</span>
<span id="cb3-30">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-gaussian" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Three Gaussian distributions with scale parameters sigma=0.5, sigma=1, and sigma=2, showing how larger sigma leads to a flatter, more spread out distribution while smaller sigma produces a sharper peak at zero">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-gaussian-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-gaussian-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-4" title="Figure&nbsp;3: Gaussian prior for σ = 0.5, 1, 2"><img src="https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/index_files/figure-html/fig-gaussian-output-1.png" alt="Three Gaussian distributions with scale parameters sigma=0.5, sigma=1, and sigma=2, showing how larger sigma leads to a flatter, more spread out distribution while smaller sigma produces a sharper peak at zero" width="663" height="374" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-gaussian-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Gaussian prior for σ = 0.5, 1, 2
</figcaption>
</figure>
</div>
</div>
</div>
<p>With the same posterior formulation as in Lasso, we can plug in the Gaussian prior to get:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BL%7D(Y%20%7C%20X,%20%5Cbeta)%20P(%5Cbeta)%20=%20%5Cleft(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D%5Cright)%5En%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%5Cright)%20*%20%5Cleft(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%20%5Ctau%7D%5Cright)%5Ep%20%5Cexp%5Cleft(-%5Cfrac%7B1%7D%7B2%5Ctau%5E2%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2%5Cright)"></p>
<p>To get the MAP estimate, we take the log of the posterior distribution:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cunderbrace%7B%5Cunderbrace%7Bnlog(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%5Csigma%7D)%20+%20plog(%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%20%5Ctau%7D)%7D_%7BConstant%7D%20-%20%5Cunderbrace%7B(%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Cfrac%7B1%7D%7B2%5Ctau%5E2%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2)%7D_%7BMinimize%20this%7D%7D_%7BIn%5C%20order%5C%20to%5C%20maximize%5C%20this%7D"></p>
<p>Now the problem becomes:</p>
<p><img src="https://latex.codecogs.com/png.latex?arg%5Cmin_%7B%5Cbeta%7D%20%5Cleft(%20%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Cfrac%7B1%7D%7B2%5Ctau%5E2%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2%20%5Cright)"></p>
<p><img src="https://latex.codecogs.com/png.latex?=arg%5Cmin_%7B%5Cbeta%7D%20%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Cleft(%20%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Cfrac%7B%5Csigma%5E2%7D%7B%5Ctau%5E2%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2%20%5Cright)"></p>
<p>which is equivalent to:</p>
<p><img src="https://latex.codecogs.com/png.latex?arg%5Cmin_%7B%5Cbeta%7D%20%5Cleft(%20RSS%20+%20%5Clambda%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2%20%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Clambda%20=%20%5Cfrac%7B%5Csigma%5E2%7D%7B%5Ctau%5E2%7D">.</p>
<p>Therefore, the Ridge solutions are the maximum a posteriori (MAP) estimates under a Gaussian prior.</p>
<p>From Figure.3, we can see that the smaller <img src="https://latex.codecogs.com/png.latex?%5Csigma"> gets, or equivalently, the larger <img src="https://latex.codecogs.com/png.latex?%5Clambda"> gets, the distribution gets more concentrated around zero.</p>
</section>
<section id="elastic-net" class="level3">
<h3 class="anchored" data-anchor-id="elastic-net">Elastic Net</h3>
<p>Elastic Net regularization, we use the product of Laplace and Gaussian prior distributions for the coefficients:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AP(%5Cbeta)%20=%20%5Cfrac%7B1%7D%7B2b%7D%20%5Cexp%5Cleft(-%5Cfrac%7B%7C%5Cbeta%7C%7D%7Bb%7D%5Cright)%20*%20%5Cfrac%7B1%7D%7B%5Csqrt%7B2%5Cpi%7D%20%5Ctau%7D%20%5Cexp%5Cleft(-%5Cfrac%7B%5Cbeta%5E2%7D%7B2%5Ctau%5E2%7D%5Cright)%0A"></p>
<p><img src="https://latex.codecogs.com/png.latex?P(%5Cbeta)%20%5Cpropto%20%5Cexp%5Cleft(-%5Cfrac%7B%7C%5Cbeta%7C%7D%7Bb%7D-%5Cfrac%7B%5Cbeta%5E2%7D%7B2%5Ctau%5E2%7D%5Cright)"></p>
<div id="cell-fig-elastic-net" 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="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> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb4-2"><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="cb4-3"></span>
<span id="cb4-4">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;">5</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;">1000</span>)</span>
<span id="cb4-5">dx <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;">1</span>] <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>
<span id="cb4-6"></span>
<span id="cb4-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> elastic_net_prior(x, lambda1, lambda2):</span>
<span id="cb4-8">    unnorm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.exp(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>lambda1 <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>(x) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> lambda2 <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;">2</span>)</span>
<span id="cb4-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> unnorm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (unnorm.<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> dx)</span>
<span id="cb4-10"></span>
<span id="cb4-11">params <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb4-12">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda1"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda2"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#E07B54"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"λ₁=2.0, λ₂=0.2  (Lasso-like)"</span>},</span>
<span id="cb4-13">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda1"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda2"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#1D9E75"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"λ₁=1.0, λ₂=1.0  (balanced)"</span>},</span>
<span id="cb4-14">    {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda1"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda2"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#7F77DD"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"λ₁=0.2, λ₂=2.0  (Ridge-like)"</span>},</span>
<span id="cb4-15">]</span>
<span id="cb4-16"></span>
<span id="cb4-17">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(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;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb4-18"></span>
<span id="cb4-19"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> p <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> params:</span>
<span id="cb4-20">    density <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> elastic_net_prior(x, p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda1"</span>], p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lambda2"</span>])</span>
<span id="cb4-21">    ax.plot(x, density, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>], lw<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;">2.5</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label"</span>])</span>
<span id="cb4-22">    ax.fill_between(x, density, 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.08</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>p[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"color"</span>])</span>
<span id="cb4-23"></span>
<span id="cb4-24">ax.axvline(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</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;">"#888780"</span>, lw<span 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>, 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.5</span>)</span>
<span id="cb4-25"></span>
<span id="cb4-26">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"β"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb4-27">ax.set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p(β)"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb4-28">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Elastic Net prior across different λ₁ and λ₂ combinations"</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb4-29">ax.legend(fontsize<span 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>, framealpha<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>)</span>
<span id="cb4-30">ax.spines[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"right"</span>]].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb4-31">ax.grid(axis<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;">"y"</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.25</span>)</span>
<span id="cb4-32"></span>
<span id="cb4-33">plt.tight_layout()</span>
<span id="cb4-34">plt.show()</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-elastic-net" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Four Elastic Net distributions showing how varying lambda1 and lambda2 shifts the prior between Laplace-like and Gaussian-like behaviour">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-elastic-net-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<a href="index_files/figure-html/fig-elastic-net-output-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-5" title="Figure&nbsp;4: Elastic Net prior for different λ₁ and λ₂ combinations"><img src="https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/index_files/figure-html/fig-elastic-net-output-1.png" alt="Four Elastic Net distributions showing how varying lambda1 and lambda2 shifts the prior between Laplace-like and Gaussian-like behaviour" width="663" height="374" class="figure-img"></a>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-elastic-net-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Elastic Net prior for different λ₁ and λ₂ combinations
</figcaption>
</figure>
</div>
</div>
</div>
<p>We proceed the same way as in Lasso and Ridge to get the MAP estimate of <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> under the Elastic Net prior, which leads to the minimarzation problem:</p>
<p><img src="https://latex.codecogs.com/png.latex?arg%5Cmin_%7B%5Cbeta%7D%20%5Cfrac%7B1%7D%7B2%5Csigma%5E2%7D%5Cleft(%5Csum_%7Bi=1%7D%5E%7Bn%7D%20%5Cepsilon_i%5E2%20+%20%5Cfrac%7B2%5Csigma%5E2%7D%7Bb%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%20+%20%5Cfrac%7B%5Csigma%5E2%7D%7B%5Ctau%5E2%7D%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2%20%5Cright)"></p>
<p><img src="https://latex.codecogs.com/png.latex?=arg%5Cmin_%7B%5Cbeta%7D%5Cleft(RSS%20+%20%5Clambda_1%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%7C%5Cbeta_j%7C%20+%20%5Clambda_2%5Csum_%7Bj=1%7D%5E%7Bp%7D%20%5Cbeta_j%5E2%20%5Cright)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Clambda_1%20=%20%5Cfrac%7B2%5Csigma%5E2%7D%7Bb%7D"> and <img src="https://latex.codecogs.com/png.latex?%5Clambda_2%20=%20%5Cfrac%7B%5Csigma%5E2%7D%7B%5Ctau%5E2%7D"> are the regularization parameters for the L1 and L2 penalties, respectively.</p>
</section>
<section id="conclusion" class="level3">
<h3 class="anchored" data-anchor-id="conclusion">Conclusion</h3>
<p>We have shown how the regularization terms in Lasso, Ridge, and Elastic Net can be derived from a Bayesian perspective by considering different prior distributions over the coefficients. For me, the Bayesian perspective provides a more intuitive understanding of regularization: it allows us to make the model less sensitive to the data by pre-specifying a shape for the coefficient distributions.</p>
</section>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li><p>E. Kamperi. <a href="https://ekamperi.github.io/mathematics/2020/08/02/bayesian-connection-to-lasso-and-ridge-regression.html">Bayesian connection to Lasso and Ridge regression.</a> 2020.</p></li>
<li><p>Q. Li and N. Lin. <a href="https://doi.org/10.1214/10-BA506">The Bayesian Elastic Net.</a> <em>Bayesian Analysis</em>, 5(1), 151–170. 2010.</p></li>
<li><p>K. Weinberger. <a href="https://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote10.html">Empirical Risk Minimization.</a> 2018.</p></li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Regularization: Bayesian’s Perspective.”</span>
May 30. <a href="https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/">https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/</a>.
</div></div></section></div> ]]></description>
  <category>Machine Learning</category>
  <category>Bayesian</category>
  <category>Regularization</category>
  <guid>https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/</guid>
  <pubDate>Sat, 30 May 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2026-05-30-bayesian-regularization/sidebar.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Boosting Methods - Gradient Boost and XGBoost</title>
  <dc:creator>Ray Wang</dc:creator>
  <link>https://changruiraywang.com/blog/2026-05-27-boosting-methods/</link>
  <description><![CDATA[ 


<!-- source: https://github.com/gadenbuie/garrickadenbuie-com/blob/main/_partials/title-block-link-buttons/title-block.html -->
<!-- 
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title"> 
-->
<!-- <header id="title-block-header" class="quarto-title-block default page-columns"> -->
<!-- <div class="quarto-title page-columns page-full featured-image p-4" style="background-image: url(featured.png), url(featured.jpg), url(../featured.jpg);"> -->



<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>Boosting methods are the Swiss Army knife for tabular data — they can be used for both regression and classification tasks, and they often outperform other algorithms. There’s no shortage of boosting hashtags: Gradient Boost, AdaBoost are two older, classical methods; XGBoost, LightGBM and CatBoost are more recent developments. They are like a famous family whose members show up at every party you go to, but you never really know what they do. You just know they are popular and everyone seems to like them.</p>
<p>In my learning journey, I have seen many articles, lectures and tutorials on Boosting methods, with a focus on either the mathematical principles or the code implementation. I have not come across a resource that connects the two together. With this blog, I intend to go over the mathematical principles of boosting methods, and map the parameters of the XGBoost Python library to the concepts we discuss.</p>
<p>The story of the Boosting family starts with a simple idea: Can we combine multiple weak learners to create a strong learner? The answer is yes. At its core, Boosting is a powerful ensemble method that combines multiple weak learners to create a strong learner. The idea is to sequentially add weak learners to the ensemble, where each new learner focuses on correcting the errors made by the previous learners.</p>
<section id="gradient-boost" class="level3">
<h3 class="anchored" data-anchor-id="gradient-boost">Gradient Boost</h3>
<p>Gradient Boost is the granddaddy of all boosting methods. It is a general boosting algorithm that can be applied to any differentiable loss function.</p>
<p>Suppose we start with T weak learners, denoted as <img src="https://latex.codecogs.com/png.latex?f_1(x),%20f_2(x),%20...,%20f_T(x)">. The combined model, or the strong model, <img src="https://latex.codecogs.com/png.latex?H_%7Bt%7D">, is a weighted sum of these weak learners:</p>
<p><img src="https://latex.codecogs.com/png.latex?H_%7Bt%7D%20=%20%5Csum%5ET_%7Bt=1%7D%5Calpha%20f_t(x)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the learning rate that controls the contribution of each weak learner to the final model.</p>
<p>The total loss function of this learner is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(H_%7Bt%7D)%20=%20%5Csum%5En_%7Bi=1%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t)%7D)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?y_i"> is the observed value for the <img src="https://latex.codecogs.com/png.latex?i">th observation, and <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i%5E%7B(t)%7D"> is the predicted value for the <img src="https://latex.codecogs.com/png.latex?i">th observation by the combined model <img src="https://latex.codecogs.com/png.latex?H_%7Bt%7D">.</p>
<p>The goal of boosting is to find the best next weak learner <img src="https://latex.codecogs.com/png.latex?f_t(x)"> that minimizes the total loss function of the next model.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(H_%7Bt+1%7D)=%5Cell(H_%7Bt%7D+%5Calpha%20f_%7Bt+1%7D)%20=%20%5Csum%5E%7Bn%7D_%7Bi=1%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t)%7D+%5Calpha%20f_%7Bt+1%7D(x_i))"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?H_%7Bt%7D"> is the current combined model, and <img src="https://latex.codecogs.com/png.latex?f_%7Bt+1%7D"> is the next weak learner we want to add to the ensemble.</p>
<p>For convenience, we denote the current combined model as <img src="https://latex.codecogs.com/png.latex?H_%7Bt-1%7D"> and the next weak learner as <img src="https://latex.codecogs.com/png.latex?f_%7Bt%7D">.</p>
<p>Now the loss function we want to minimize is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(H_%7Bt%7D)=%5Cell(H_%7Bt-1%7D+%5Calpha%20f_%7Bt%7D)%20=%20%5Csum%5E%7Bn%7D_%7Bi=1%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_%7Bt%7D(x_i))"></p>
<p>To minimize a loss function, it’s usually easier to minimize its approximation than the original loss function. We can approximate <img src="https://latex.codecogs.com/png.latex?%5Cell(H_%7Bt%7D)"> by its 1st-degree Taylor Approximation.</p>
<p>Since the loss function is the sum of all individual losses, we can examine the Taylor approximation of the loss function for each individual observation:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_%7Bt%7D(x_i))%20=%20%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D)%20+%5Calpha%5Cdfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7Df_%7Bt%7D(x_i)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7D"> is the gradient of the loss function with respect to the predicted value for the <img src="https://latex.codecogs.com/png.latex?i">th observation. Hence the name, “Gradient Boosting”.</p>
<p>Since <img src="https://latex.codecogs.com/png.latex?%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D)"> and <img src="https://latex.codecogs.com/png.latex?%5Calpha"> are constants, we can ignore them when minimizing the loss function. Summing up individual loss functions for all observations, we get the approximate loss function to minimize:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Csum%5En_%7Bi=1%7D%5Cdfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7Df_%7Bt%7D(x_i)"></p>
<p>How do we go about the minimization?</p>
<p>For convenience, let’s denote <img src="https://latex.codecogs.com/png.latex?%5Cdfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7D"> as <img src="https://latex.codecogs.com/png.latex?g_i">; and let <img src="https://latex.codecogs.com/png.latex?r_i%20=%20-g_i">.</p>
<p>Now we want to minimize:</p>
<p><img src="https://latex.codecogs.com/png.latex?-%5Csum%5En_%7Bi=1%7Dr_if_%7Bt%7D(x_i)"></p>
<p>which is equivalent to minimizing:</p>
<p><img src="https://latex.codecogs.com/png.latex?-2%5Csum%5En_%7Bi=1%7Dr_if_%7Bt%7D(x_i)"></p>
<p>Now we add two constants:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Csum%5En_%7Bi=1%7Dr_i%5E2">: This part is a constant because it is independent of <img src="https://latex.codecogs.com/png.latex?f_t(x_i)">, so it doesn’t affect the minimization.</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Csum%5En_%7Bi=1%7Df%5E2(x_i)">: We can think of the squared Euclidean length (sum of all elements squared) of the output vector as fixed. Since we are combining multiple weak learners sequentially, it is the direction of the output vector that matters, not its length. So we can treat this part as a constant as well.</p>
<p>Adding all parts together, we want to minimize:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Csum%5En_%7Bi=1%7D%5Bf%5E2(x_i)-2r_if_%7Bt%7D(x_i)+r_i%5E2%5D%20=%20%5Csum%5En_%7Bi=1%7D(f_%7Bt%7D(x_i)-r_i)%5E2"></p>
<p>To recap, <img src="https://latex.codecogs.com/png.latex?r_i"> is the negative gradient of the loss function with respect to the predicted value for the <img src="https://latex.codecogs.com/png.latex?i">th observation. In fact, for both regression and classification tasks, <img src="https://latex.codecogs.com/png.latex?r_i%20=%20-g_i%20=%20y_i-%5Chat%7By%7D_i%5E%7B(t-1)%7D">, which is the residual of the <img src="https://latex.codecogs.com/png.latex?i">th prediction. Therefore, minimizing the loss function is equivalent to fitting a new model to the residuals.</p>
</section>
<section id="gradient-boosted-tree" class="level3">
<h3 class="anchored" data-anchor-id="gradient-boosted-tree">Gradient Boosted Tree</h3>
<p>So far we have been talking about the general idea of gradient boosting, which is about iteratively improving a model by fitting new weak learners to the residuals of the current model. One thing to point out is that there are actually more than one way to fit a base learner to the current residuals. For example, one can use a linear model. However, linear base learners collapse to a single linear model, which is not very powerful. On the other hand, decision trees are more flexible and can capture non-linear relationships in the data. Therefore, gradient boosted decision trees is the most common type of base learner used in boosting.</p>
<p>For gradient boosted trees, since the loss function is the sum of all individual losses on the leaves of the tree structure, we can express the loss function by summing up individual losses leaf by leaf. Define <img src="https://latex.codecogs.com/png.latex?I_j"> as the indicator function that an observation is on the leaf <img src="https://latex.codecogs.com/png.latex?j">.</p>
<p>Our goal is to find the best next weak tree <img src="https://latex.codecogs.com/png.latex?f_t"> that minimizes the loss function:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell%5E%7B(t)%7D%20=%20%5Csum%5EJ_%7Bj=1%7D%5Cleft%5B%5Csum_%7Bi%5Cin%20j%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_t(x_i))%5Cright%5D"></p>
<p>The idea of minimization is identical to the gradient boosting method we discussed above, except that we are now minimizing the loss function for each leaf instead of the whole dataset.</p>
<p>It can be thought of as a two-step process:</p>
<ol type="1">
<li><p>First we want an output value <img src="https://latex.codecogs.com/png.latex?f_t(x)"> that minimizes the loss function for each leaf: <img src="https://latex.codecogs.com/png.latex?%5Csum_%7Bi%5Cin%20j%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_t(x_i))">.</p></li>
<li><p>Then we find the best tree structure (i.e., how to split the features) that minimizes the total loss function of all leaves.</p></li>
</ol>
<p>The algorithm is identical to the regression tree algorithm. We are just fitting a regression tree to the residuals instead of the original target variable.</p>
</section>
<section id="xgboost" class="level3">
<h3 class="anchored" data-anchor-id="xgboost">XGBoost</h3>
<p>XGBoost is an optimized implementation of gradient boosting. Compared to Gradient Boost, XGBoost has two major upgrades. The first is adding regularizing terms to the total loss function. The second is using 2nd-degree Taylor Approximation instead of 1st-degree Taylor Approximation to approximate the loss function.</p>
<p>The loss function for XGBoost is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell%5E%7B(t)%7D%20=%20%5Csum%5E%7Bn%7D_%7Bi=1%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_t(x_i))+%5COmega(f_t)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5COmega(f_t)"> is the regularization term.</p>
<p>There are other improvements in terms of computational efficiency, such as parallelization and handling missing values, but we will focus on the mathematical improvements here.</p>
<section id="tree-booster" class="level4">
<h4 class="anchored" data-anchor-id="tree-booster">Tree Booster</h4>
<p>For XGBoost trees, the regularization term is defined as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5COmega(f_t(x))=%5Cgamma%20T+%5Calpha%5Csum%5EJ_%7Bj=1%7D%7Cf_j(x)%7C+%5Cdfrac%7B1%7D%7B2%7D%5Clambda%5Csum%5EJ_%7Bj=1%7Df%5E2_j(x)"></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the L1 regularization parameter.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Clambda"> is the L2 regularization parameter.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cgamma"> is a penalty term to encourage pruning.</li>
<li><img src="https://latex.codecogs.com/png.latex?T"> is the number of leaves.</li>
<li><img src="https://latex.codecogs.com/png.latex?f_j(x)"> is the output for leaf <img src="https://latex.codecogs.com/png.latex?j">.</li>
</ul>
<p>In the original XGBoost paper, only L2 regularization term was used:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell%5E%7B(t)%7D%20=%20%5Csum%5E%7Bn%7D_%7Bi=1%7D%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_t(x_i))+%5Cdfrac%7B1%7D%7B2%7D%5Clambda%5Csum%5EJ_%7Bj=1%7Df%5E2_j(x)+%5Cgamma%20T"></p>
<p>Applying the 2nd-degree Taylor Approximation to the individual loss function:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D+%5Calpha%20f_t(x_i))%20%5Capprox%20%5Cell(y_i,%5Chat%7By%7D_i%5E%7B(t-1)%7D)%20+%20g_i%20f_t(x_i)%20+%20%5Cdfrac%7B1%7D%7B2%7Dh_i%20f%5E2_t(x_i)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?g_i%20=%20%5Cdfrac%7B%5Cpartial%20%5Cell%7D%7B%5Cpartial%20%5Chat%7By%7D_i%5E%7B(t-1)%7D%7D"> is the gradient and <img src="https://latex.codecogs.com/png.latex?h_i%20=%20%5Cdfrac%7B%5Cpartial%5E2%20%5Cell%7D%7B%5Cpartial%20(%5Chat%7By%7D_i%5E%7B(t-1)%7D)%5E2%7D"> is the hessian of the loss function.</p>
<p>Summing up individual loss functions for all observations on leaf <img src="https://latex.codecogs.com/png.latex?j"> and adding the regularization term:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctilde%7B%5Cell%7D%5E%7B(t)%7D%20%5Capprox%20%5Csum%5EJ_%7Bj=1%7D%5Cleft%5B%5Cleft(%5Csum_%7Bi%5Cin%20j%7Dg_i%5Cright)f_j(x)+%5Cdfrac%7B1%7D%7B2%7D%5Cleft(%5Csum_%7Bi%5Cin%20j%7Dh_i+%5Clambda%5Cright)f%5E2_j(x)%5Cright%5D+%5Cgamma%20T"></p>
<p>Taking the derivative with respect to <img src="https://latex.codecogs.com/png.latex?f_j(x)"> and setting it to zero, the optimal output for leaf <img src="https://latex.codecogs.com/png.latex?j"> is:</p>
<p><img src="https://latex.codecogs.com/png.latex?f_j%5E*(x)%20=%20-%5Cdfrac%7B%5Csum_%7Bi%5Cin%20j%7Dg_i%7D%7B%5Csum_%7Bi%5Cin%20j%7Dh_i+%5Clambda%7D"></p>
<p>Plugging in <img src="https://latex.codecogs.com/png.latex?f%5E*_j(x)"> we get the minimum loss function for leaf <img src="https://latex.codecogs.com/png.latex?j">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctilde%7B%5Cell%7D%5E%7B(t)%7D_%7Bi%5Cin%20j%7D%20%5Capprox%20-%5Cdfrac%7B1%7D%7B2%7D%5Cdfrac%7B(%5Csum_%7Bi%20%5Cin%20j%7Dg_i)%5E2%7D%7B%5Csum_%7Bi%20%5Cin%20j%7Dh_i%7D"></p>
<p>This value is used to calculate the gain of a split, which is the reduction in loss function after the split:</p>
<p><img src="https://latex.codecogs.com/png.latex?Gain%20=%20%5Cdfrac%7B1%7D%7B2%7D%5Cleft%5B%5Cdfrac%7B(%5Csum_%7Bi%5Cin%20j_L%7Dg_i)%5E2%7D%7B%5Csum_%7Bi%5Cin%20j_L%7Dh_i+%5Clambda%7D+%5Cdfrac%7B(%5Csum_%7Bi%5Cin%20j_R%7Dg_i)%5E2%7D%7B%5Csum_%7Bi%5Cin%20j_R%7Dh_i+%5Clambda%7D-%5Cdfrac%7B(%5Csum_%7Bi%5Cin%20j%7Dg_i)%5E2%7D%7B%5Csum_%7Bi%5Cin%20j%7Dh_i+%5Clambda%7D%5Cright%5D%20-%20%5Cgamma"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?j_L"> and <img src="https://latex.codecogs.com/png.latex?j_R"> are the left and right child nodes after the split, respectively.</p>
<p>It can be seen that the parameter <img src="https://latex.codecogs.com/png.latex?%5Cgamma"> is a pruning threshold. A split will be made only if the gain of a split is greater than <img src="https://latex.codecogs.com/png.latex?%5Cgamma">.</p>
<p>One lingering question is: Where do the gradients and hessians come from? It depends on the prediction task.</p>
<p>The loss function for the regression task is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(y_i,%5Chat%7By%7D_i)%20=%5Cdfrac%7B1%7D%7B2%7D(y_i-%5Chat%7By%7D_i)%5E2"></p>
<p>The gradient is: <img src="https://latex.codecogs.com/png.latex?g_i%20=%20-(y_i-%5Chat%7By%7D_i)"></p>
<p>The hessian is: <img src="https://latex.codecogs.com/png.latex?h_i%20=%201"></p>
<p>The loss function for the classification task is:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cell(y_i,%5Chat%7By%7D_i)%20=%20-%5By_i%5Clog(%5Chat%7By%7D_i)+(1-y_i)%5Clog(1-%5Chat%7By%7D_i)%5D"></p>
<p>The gradient is: <img src="https://latex.codecogs.com/png.latex?g_i%20=%20-(y_i-%5Chat%7By%7D_i)"></p>
<p>The hessian is: <img src="https://latex.codecogs.com/png.latex?h_i%20=%20%5Chat%7By%7D_i(1-%5Chat%7By%7D_i)"></p>
<p>Here, <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D_i"> is the predicted probability for the <img src="https://latex.codecogs.com/png.latex?i">th observation.</p>
<p>The full loop of XGBoost training can be summarized as follows:</p>
<p>Once the ensemble of <img src="https://latex.codecogs.com/png.latex?M"> trees is trained, prediction for a new observation <img src="https://latex.codecogs.com/png.latex?x"> is just a sum: <img src="https://latex.codecogs.com/png.latex?%5Chat%7By%7D%20=%20%5Csum_%7Bm=1%7D%5E%7BM%7D%20%5Ceta%20%5Ccdot%20f_m(x)"></p>
</section>
<section id="linear-and-dart-booster" class="level4">
<h4 class="anchored" data-anchor-id="linear-and-dart-booster">Linear and Dart Booster</h4>
<p>The XGBoost Python package also supports two other types of boosters: linear booster and dart booster.</p>
<p>Counterintuitively, the linear booster of XGBoost is actually not many linear models combined together. It fits an Elastic Net linear model with regularization terms to the residuals using the coordinate descent algorithm. In other words, each round of boosting does not generate a new linear model, but rather updates the coefficients of the existing linear model.</p>
<p>The dart booster is a variant of the tree booster that randomly drops out trees during training to prevent overfitting.</p>
<p>The details of the linear and dart boosters are beyond the scope of this blog, but you can find more information in the XGBoost GitHub repository.</p>
</section>
</section>
<section id="xgboost-parameters" class="level3">
<h3 class="anchored" data-anchor-id="xgboost-parameters">XGBoost Parameters</h3>
<p>Now with the mathematical principles of XGBoost in mind, we can map the parameters of the XGBoost Python library to the concepts we discussed above.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Concept</th>
<th>xgboost Parameter</th>
<th>What it does</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Tree depth</td>
<td><code>max_depth</code></td>
<td>Controls how deep the trees can grow</td>
</tr>
<tr class="even">
<td>Min samples in leaf</td>
<td><code>min_child_weight</code></td>
<td>Controls the minimum sum of hessians in a leaf</td>
</tr>
<tr class="odd">
<td>Row sampling</td>
<td><code>subsample</code></td>
<td>Controls the fraction of data used for each tree</td>
</tr>
<tr class="even">
<td>Column sampling</td>
<td><code>colsample_bytree</code></td>
<td>Controls the fraction of features used for each tree</td>
</tr>
<tr class="odd">
<td>Column sampling</td>
<td><code>colsample_bylevel</code></td>
<td>Controls the fraction of features used for each level</td>
</tr>
<tr class="even">
<td>Column sampling</td>
<td><code>colsample_bynode</code></td>
<td>Controls the fraction of features used for each node</td>
</tr>
<tr class="odd">
<td>Tree method</td>
<td><code>tree_method</code></td>
<td>Controls how trees are constructed</td>
</tr>
<tr class="even">
<td>Min split gain</td>
<td><code>gamma</code></td>
<td>Controls the minimum loss reduction required to make a split</td>
</tr>
<tr class="odd">
<td>Booster type</td>
<td><code>booster</code></td>
<td>Controls the type of booster to use (gbtree, gblinear, dart)</td>
</tr>
<tr class="even">
<td>Class imbalance</td>
<td><code>scale_pos_weight</code></td>
<td>Gives more weight to the positive class</td>
</tr>
<tr class="odd">
<td>Learning rate</td>
<td><code>learning_rate</code></td>
<td>Controls the weight of each new tree in the ensemble</td>
</tr>
<tr class="even">
<td>Number of trees</td>
<td><code>n_estimators</code></td>
<td>Controls the total number of trees in the model</td>
</tr>
<tr class="odd">
<td>Early stopping</td>
<td><code>early_stopping_rounds</code></td>
<td>Stops training early if no improvement in the evaluation metric</td>
</tr>
<tr class="even">
<td>Evaluation metric</td>
<td><code>eval_metric</code></td>
<td>Controls the metric used for evaluation during training</td>
</tr>
<tr class="odd">
<td>L1 regularization</td>
<td><code>reg_alpha</code></td>
<td>Controls the amount of L1 regularization</td>
</tr>
<tr class="even">
<td>L2 regularization</td>
<td><code>reg_lambda</code></td>
<td>Controls the amount of L2 regularization</td>
</tr>
</tbody>
</table>
<p>Some notes on the parameters:</p>
<p><strong><code>colsample_bylevel</code> vs.&nbsp;<code>colsample_bytree</code> vs.&nbsp;<code>colsample_bynode</code></strong></p>
<p>These parameters control the fraction of features used for each tree, level, or node, respectively. The difference is in the granularity of feature sampling.</p>
<p>With <code>colsample_bytree</code>, each tree gets its own random subset of features:</p>
<pre><code>Tree 1:  sample once → {f1, f2, f4, f6, f7, f9}   ← all nodes in Tree 1 use these 6
Tree 2:  sample once → {f1, f3, f4, f5, f8, f10}  ← all nodes in Tree 2 use these 6
Tree 3:  sample once → {f2, f3, f5, f6, f7, f10}  ← all nodes in Tree 3 use these 6</code></pre>
<p>With <code>colsample_bylevel</code>, each level gets its own random subset of features:</p>
<pre><code>Depth 0 (root):  features sampled   → {f1, f3, f5, f7}
Depth 1:         features resampled → {f2, f3, f6, f8}
Depth 2:         features resampled → {f1, f4, f5, f8}</code></pre>
<p>With <code>colsample_bynode</code>, each node gets its own random subset of features:</p>
<pre><code>Depth 0 (root):   features sampled   → {f1, f3, f5, f7}
Depth 1, Node 1:  features resampled → {f2, f3, f6, f8}
Depth 1, Node 2:  features resampled → {f1, f4, f5, f8}
Depth 2, Node 1:  features resampled → {f1, f3, f5, f7}</code></pre>
<p><strong><code>tree_method</code></strong></p>
<p>The <code>tree_method</code> parameter controls how trees are constructed. The options are:</p>
<ul>
<li><code>exact</code>: Enumerates all possible splits across all features.</li>
<li><code>approx</code>: Uses a weighted quantile sketch to bucket continuous features into candidate split points.</li>
<li><code>hist</code>: Builds a histogram of feature values — bins data into discrete buckets first.</li>
</ul>
<p>A good reference is <a href="https://www.youtube.com/watch?v=oRrKeUCEbq8">StatsQuest: Cool Crazy Optimizations</a>.</p>
<p><strong><code>min_child_weight</code></strong></p>
<p>The <code>min_child_weight</code> parameter controls the minimum sum of hessians in a leaf to prevent overfitting.</p>
<p>For regression problems, the hessian is always 1, so <code>min_child_weight</code> is equivalent to the minimum number of samples in a leaf. You are telling the model to stop splitting a leaf if the number of samples in that leaf goes below a threshold.</p>
<p>For classification problems, the hessian is the predicted probability of the positive class multiplied by the predicted probability of the negative class — <img src="https://latex.codecogs.com/png.latex?%5Chat%7Bp%7D(1-%5Chat%7Bp%7D)">. Therefore, you are telling the model to stop trying to split once you reach a certain degree of purity in a node.</p>
</section>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<ul>
<li>Jerome H. Friedman. <a href="https://projecteuclid.org/journals/annals-of-statistics/volume-29/issue-5/Greedy-function-approximation-A-gradient-boosting-machine/10.1214/aos/1013203451.full">Greedy function approximation: A gradient boosting machine.</a> 2002.</li>
<li>T. Chen, C. Guestrin. <a href="https://arxiv.org/abs/1603.02754">XGBoost: A Scalable Tree Boosting System.</a> 2016.</li>
<li>P. Seeburger. <a href="https://math.libretexts.org/Bookshelves/Calculus/Supplemental_Modules_(Calculus)/Multivariable_Calculus/3%3A_Topics_in_Partial_Derivatives/Taylor__Polynomials_of_Functions_of_Two_Variables">Taylor Polynomials of Functions of Two Variables.</a> 2025.</li>
<li>Geeksforgeeks. <a href="https://www.geeksforgeeks.org/machine-learning/xgboost-parameters/">XGBoost Parameters.</a> 2025.</li>
<li>K. Weinberger. <a href="https://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote19.html">XGBoost Tutorial.</a> 2018.</li>
<li>Analytics Vidhya. <a href="https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/">Complete Guide to Parameter Tuning in XGBoost with Codes in Python.</a> 2016.</li>
<li>XGBoost GitHub. <a href="https://github.com/dmlc/xgboost/blob/master/src/gbm/gblinear.cc">Linear Booster.</a> 2025.</li>
<li>XGBoost GitHub. <a href="https://github.com/dmlc/xgboost/blob/master/src/linear/updater_shotgun.cc">Linear Updater.</a> 2025.</li>
<li>Stack Exchange. <a href="https://stats.stackexchange.com/questions/317073/explanation-of-min-child-weight-in-xgboost-algorithm">Explanation of min_child_weight in xgboost algorithm.</a> 2017.</li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a><div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-reuse"><h2 class="anchored quarto-appendix-heading">Reuse</h2><div class="quarto-appendix-contents"><div><a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a></div></div></section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-wang2026" class="csl-entry quarto-appendix-citeas">
Wang, Ray. 2026. <span>“Boosting Methods - Gradient Boost and
XGBoost.”</span> May 27. <a href="https://changruiraywang.com/blog/2026-05-27-boosting-methods/">https://changruiraywang.com/blog/2026-05-27-boosting-methods/</a>.
</div></div></section></div> ]]></description>
  <category>Machine Learning</category>
  <category>Boosting</category>
  <category>XGBoost</category>
  <guid>https://changruiraywang.com/blog/2026-05-27-boosting-methods/</guid>
  <pubDate>Wed, 27 May 2026 04:00:00 GMT</pubDate>
  <media:content url="https://changruiraywang.com/blog/2026-05-27-boosting-methods/sidebar.jpg" medium="image" type="image/jpeg"/>
</item>
</channel>
</rss>
