Imports¶
%load_ext autoreload
%autoreload 2
import logging
import matplotlib.pyplot as plt
import seaborn as sns
# Set plotting style.
sns.set_style("whitegrid")
plt.rcParams["figure.figsize"] = (12, 6)import helpers.hintrospection as hintros
import helpers.htutorial as ut
import L05_02_01_bias_variance_utils as utils
ut.config_notebook()
# Initialize logger.
logging.basicConfig(level=logging.INFO)
_LOG = logging.getLogger(__name__)WARNING (pytensor.tensor.blas): Using NumPy C-API based implementation for BLAS functions.
vim support installed: restart the notebook, if needed
Python 3.12.3
Linux 589569fe8102 6.12.67-linuxkit #1 SMP Sun Jan 25 02:26:28 UTC 2026 aarch64 aarch64 aarch64 GNU/Linux
Part 1: Approximation vs Learning¶
Cell 1.1: Approximation¶
Goal:
- Compare how well a constant model and a linear model can approximate the true target function on , with no notion of training data yet
Implementation: cell1_approximation()
- Fits and directly to the dense true
function by least squares, in
fit_constant_model()/fit_linear_model() - Plots
True function vs constant modelandTrue function vs linear model, each shading the approximation error, plus aCommentspanel with both models’ equations and errors
# Display approximation comparison between constant and linear models.
utils.cell1_approximation()
Cell 1.2: Learning once¶
Goal:
- Contrast learning from a small training set with the pure approximation of Cell 1.1, and separate in-sample error from out-of-sample error
Implementation: cell2_learning_once()
- Draws
N_samplesrandom training points and fits / to them withfit_models_and_predict() - Computes (error on the training points) and (error against the true function) for both models
hintros.print_obj_info(utils.cell2_learning_once)Usage
Inputs
seed: random seed for the training points sampledN_samples: number of training points, 2-20
Panels
Constant model: , the fitted , and the training points, titled with /Linear model: , the fitted , and the training points, titled with /Comments: currentseed,N_samples, and both models’ /
# Display learning from N random samples with interactive controls.
utils.cell2_learning_once()Loading...
Loading...
Loading...
Guided usage
- Leave
N_samplesat 2 and changeseeda few times- Observe the linear model reaches on almost every draw (2 points fully determine a line), yet still varies widely
- Raise
N_samplesfrom 2 toward 20- Observe for the linear model rise off zero, while for both models settles down: fitting 2 points perfectly is not the same as learning
Part 2: Bias-Variance Decomposition¶
Cell 2.1: Learning: bias-variance decomposition¶
Goal:
- Repeat Cell 1.2’s experiment across many random training sets, and read bias and variance off how the resulting models scatter around
Implementation: cell3_learning_bias_variance()
- Runs
N_experimentsindependent draws ofN_samplespoints, refitting and each time - Overlays every fitted model in translucent lines, plus the average model as a dashed line, so bias (average vs ) and variance (spread around the average) are both visible at once
hintros.print_obj_info(utils.cell3_learning_bias_variance)Usage
Inputs
seed: random seed for the experimentsN_samples: training points per experiment, 2-20N_experiments: number of repeated experiments, 5-100
Panels
Constant models: , every fitted , and their averageLinear models: , every fitted , and their averageComments: average / and the bias-variance reading for both models
# Display bias-variance decomposition over multiple experiments.
utils.cell3_learning_bias_variance()Loading...
Loading...
Loading...
Loading...
Guided usage
- Compare the two panels at the default
N_samples = 2- Observe the constant lines cluster tightly (low variance) but sit far from (high bias), while the linear lines spread widely (higher variance) but average closer to (lower bias)
- Raise
N_experimentstoward 100- Observe the average line in each panel stabilize, giving a more reliable bias estimate without changing how spread out the individual fits are
Cell 2.2: Learning plots: bias-variance vs training set size¶
Goal:
- Trace how , , , and variance move as training set size grows, for both models at once
Implementation: cell4_learning_plots()
- Repeats Cell 2.1’s experiment at every training size from 2 up to
max_N_samples, averagingN_experimentstrials at each size - Plots the four error curves for and side by side, verifying for this noise-free target
hintros.print_obj_info(utils.cell4_learning_plots)Usage
Inputs
seed: random seed, fixed across training sizes for a fair comparisonN_experiments: experiments averaged per training size, 20-200max_N_samples: largest training size swept, 5-30
Panels
Constant model (g_0), bias-variance analysis: , , , and variance vs training sizeLinear model (g_1), bias-variance analysis: the same four curves forComments: the decomposition formula and both models’ values atmax_N_samples
# Display bias-variance decomposition as a function of N_samples.
utils.cell4_learning_plots()Loading...
Loading...
Loading...
Loading...
Guided usage
- Raise
max_N_samplestoward 30- Observe variance keep shrinking toward 0 for both models, while each model’s bias curve flattens out at its own level
- Compare the flattened bias level between panels
- Observe the linear model’s bias floor sits below the constant model’s: more model capacity lowers bias, at the cost of the variance seen in Cell 2.1
Part 3: Bias-Variance With Noise¶
Cell 3.1: Learning with noise: bias-variance decomposition¶
Goal:
- Repeat Cell 2.1’s multi-experiment view with Gaussian noise added to the training labels,
Implementation: cell5_learning_with_noise()
- Adds noise of standard deviation
noise_stdto each training draw before fitting /, otherwise identical tocell3_learning_bias_variance()
hintros.print_obj_info(utils.cell5_learning_with_noise)Usage
Inputs
seed: random seed for the experimentsnoise_std: standard deviation of the label noise, 0-0.5N_samples: training points per experiment, 2-20N_experiments: number of repeated experiments, 5-100
Panels
Constant models: , every fitted , and their averageLinear models: , every fitted , and their averageComments: average / for both models at the current noise level
# Display bias-variance decomposition with noise over multiple experiments.
utils.cell5_learning_with_noise()Loading...
Loading...
Loading...
Loading...
Loading...
Guided usage
- Leave
noise_stdat 0 and compare against Cell 2.1- Observe the two panels match Cell 2.1 exactly: zero noise recovers the noise-free case
- Raise
noise_stdfrom 0 toward 0.5- Observe both panels spread out further and climb for both models, since every fit now chases noise the true function never had
Cell 3.2: Learning plots with noise: bias-variance vs training set size¶
Goal:
- Trace , , , and variance against training set size, as in Cell 2.2, now with noisy training labels
Implementation: cell6_learning_plots_with_noise()
- Repeats Cell 2.2’s sweep with
noise_stdadded to every training draw before fitting, overN_samplesfrom 2 up to the current slider value
hintros.print_obj_info(utils.cell6_learning_plots_with_noise)Usage
Inputs
seed: random seed, fixed across training sizesnoise_std: standard deviation of the label noise, 0-0.5log(N_samples)(log scale): largest training size swept, 2-256log(N_experiments)(log scale): experiments averaged per training size, 16-1024
Panels
Constant model (g_0), bias-variance analysis: , , , and variance vs training sizeLinear model (g_1), bias-variance analysis: the same four curves forComments: the noisy decomposition formula and both models’ values at the largest training size
# Display bias-variance decomposition with noise as a function of N_samples.
utils.cell6_learning_plots_with_noise()Loading...
Loading...
Loading...
Loading...
Loading...
Guided usage
- Set
noise_stdto 0.1 or 0.2 and compare against Cell 2.2- Observe both curves shift up by roughly , while the bias curves barely move: noise adds an irreducible floor, it does not change what the model class can represent
- Raise
log(N_samples)toward its maximum with noise still on- Observe variance keeps shrinking as before, but levels off above 0: more data cannot remove the noise term, only the variance term