Coursework Part 1 focuses on implementing some of the requisite calculations and manipulations for applying Bayesian linear regression models covered in Lectures 02 - 05.
Exercises include:
computing the posterior distribution,
computing the marginal likelihood,
evaluating and choosing regularisation parameters,
obtaining posterior mean models,
calculating error-bars (the predictive variance),
... some presentation of results.
The data will be derived from a synthetic, noisy, sine wave and our model will be a linearly-weighted set of "Gaussian" (RBF) basis functions. In a change from the lectures, a modification has been made to the data: there are no observations from one particular region of the data space. One of the aims of the lab is to see how this aspect impacts on the uncertainty of the model predictions.
There are 3 principal tasks (detailed below), with varying marks. In summary here:
Task 1: Fit various Gaussian RBF-based linear models to the training data using penalised least-squares (OLS), and visualise the results (4 marks)
Task 2: Replicate the example slide attached along with this notebook file using the model and data here - that is, compute the train, validation and test set errors, plus the marginal likelihood (the red dashed curve in the example slide), over a range of
(or
) values (9 marks + 1 bonus mark)
Task 3: Identify the best posterior mean model, visualise it along with its error-bars (predictive variance), and consider how those error-bars might be usefully exploited (2 marks + 1 bonus mark)
Setup
Support code
To get started, the code cell below imports the requisite standard Python modules, plus a setup module CM50268_CWP1_Setup specific to this lab. This module contains:
the class DataGenerator to synthesise all the data sets needed,
the class RBFGenerator to create the necessary Gaussian "RBF" basis matrices for varying data sets,
the function error_rms to simply calculate errors for a given target values
and corresponding model output
.
We also set some "constants" below: data set sizes and the generative noise standard deviation, which we fix at
for the entire exercise.
CM50268_CW1_Setup
Support code for Coursework 1 :: Bayesian Linear Regression
import numpy as np
from scipy import stats, spatial
class DataGenerator:
code
"""Generate data for simple prediction modelling
- this is a sine wave with a blank region"""
def __init__(self, noise=0.25, rs=4):
# Ensure different random seeds for the data sets
self._States = {'TRAIN': 0+rs, 'VALIDATION': 1+rs, 'TEST': 2+rs}
#
self.xmin = 0
self.xmax = 2.5 * np.pi
self._noise_std = noise
# Private
#
def _make_data_test(self, name, N, noise_std=0.0):
# The full sine wave
x = np.linspace(self.xmin, self.xmax, N).reshape((N, 1))
t = np.sin(x)
if noise_std:
state = self._States[name]
t += stats.norm.rvs(size=(N, 1), scale=noise_std,
random_state=state)
#
return x, t
def _make_data(self, name, N, noiseStd=0.0):
# Portions of the sine wave
start = [0.25*np.pi, 6]
width = [0.6*np.pi, 0.4*np.pi]
K = len(start)
Nper = int(N/K)
x = np.empty(0)
for k in range(K):
xk = np.linspace(start[k], start[k]+width[k], Nper)
x = np.append(x, xk)
x = x.reshape((N, 1))
t = np.sin(x)
if noiseStd:
state = self._States[name]
t += stats.norm.rvs(size=(N, 1), scale=noiseStd,
random_state=state)
#
return x, t
# Public interface
#
def get_data(self, name, N):
name = name.upper()
if name == 'TRAIN':
return self._make_data(name, N, self._noise_std)
elif name == 'VALIDATION':
return self._make_data(name, N, self._noise_std)
elif name == 'TEST':
return self._make_data_test(name, N, 0)
else:
raise ValueError('Invalid data set name')
def error_rms(t, y):
"""Compute RMS error for a prediction vector"""
err = np.sqrt(np.mean((y - t) ** 2))
return err
The coursework you're undertaking involves applying Bayesian Linear Regression (BLR) models to a dataset derived from a synthetic, noisy sine wave. The tasks are designed to deepen your understanding of BLR by engaging in practical implementation of its concepts, such as computing posterior distributions, evaluating regularization parameters, and understanding the impact of missing data on model uncertainty. Here's a brief overview of what each task entails and some guidance on approaching them.
Task 1: Fit Gaussian RBF-based Linear Models
In this task, you're expected to fit linear models to the training data using penalized least squares, otherwise known as Ordinary Least Squares (OLS), with Gaussian Radial Basis Function (RBF) as basis functions. This involves:
Generating RBF Basis Matrices: Use the RBFGenerator class to create the Gaussian RBF basis matrices for your data. The RBF centres and widths are crucial parameters that can significantly impact model performance.
Fitting the Model: You can fit the model to the training data by solving the normal equations for linear regression or using more sophisticated optimization algorithms if preferred. Penalization or regularization will require adding a penalty term to the loss function to control model complexity.
Visualization: Plot the fitted models against the actual data to visualize how well the models capture the underlying trend.
Task 2: Error Analysis and Marginal Likelihood
This task requires replicating an example by computing error metrics and marginal likelihoods over a range of regularization (lambda) or noise variance ((\sigma^2)) values.
Computing Errors: Use the provided error_rms function to compute the Root Mean Square (RMS) error for the training, validation, and test sets. This will involve making predictions with your model and comparing them to the actual data.
Marginal Likelihood (Evidence): You'll need to implement the computation of the marginal likelihood, which is an integral over all possible parameter values weighted by how well they fit the data and the prior. This is a crucial step for Bayesian model selection.
Optimization: Experiment with different values of the regularization parameter or noise variance to understand their impact on model performance and the marginal likelihood. Plot these relationships, identifying the optimal parameter value.
Task 3: Optimal Model and Uncertainty Visualization
After identifying the best regularization parameter, your task is to visualize the optimal model and its uncertainty, typically through error bars representing predictive variance.
Best Model: Use the regularization parameter identified in Task 2 to build the model that best fits the data according to Bayesian criteria.
Predictive Variance: Calculate the predictive variance of the model to quantify uncertainty in the predictions. This is crucial for understanding the reliability of the model's predictions, especially in regions with no observations.
Visualization: Plot this model against the data, including error bars to represent uncertainty. This helps in communicating not just the predictions but also the model's confidence in those predictions.
Tips for Implementation
Matrix Operations: Familiarize yourself with NumPy for efficient matrix operations, crucial for tasks like evaluating the RBF basis and solving for model parameters.
Visualization: Use plotting libraries such as Matplotlib or Seaborn for visualizing data, model fits, and errors, which are vital for understanding model performance and communicating your results.
Bayesian Framework: Keep in mind the Bayesian perspective as you work through these tasks. Bayesian methods are inherently probabilistic, providing a powerful framework for model selection and expressing uncertainty.
Code Structure: Organize your code effectively. Break down your implementation into smaller functions or blocks, which can help in debugging and understanding each step of the process.
This coursework offers a practical hands-on experience with Bayesian linear regression models, emphasizing understanding model behaviors and interpreting results from a Bayesian viewpoint. Good luck!
The code snippet you've presented sets up an environment for conducting experiments with Bayesian linear regression, particularly in a context that involves a synthetic dataset derived from a sine wave with introduced noise. Here's a step-by-step guide that elaborates on each part of the code and what comes next:
Setting Up the Environment
Matplotlib Inline: %matplotlib inline is a magic command for Jupyter Notebooks that tells the notebook to display plots inline, i.e., directly under the code cells that produce them.
Importing Modules:
NumPy for numerical operations.
Matplotlib.pyplot for plotting graphs.
Scipy.stats for statistical tools.
CM50268_CWP1_Setup is a custom module provided for this coursework, containing utilities for data generation, basis function (RBF) evaluation, and error computation.
Setting Up Parameters:
N_train, N_val, and N_test define the sizes of the training, validation, and test datasets, respectively.
sigma represents the standard deviation of the noise introduced in the data.
s2 is the variance of the noise (sigma squared), which you might need when calculating likelihoods or when accounting for noise in your Bayesian model.
Next Steps
Given this setup, the typical next steps in a coursework or a project involving Bayesian Linear Regression might include:
Data Generation: Utilizing the DataGenerator class from the CM50268_CWP1_Setup module to create simulated datasets for training, validation, and testing. For example:
RBF Basis Setup: Choose centers and widths for your RBF functions. This can be crucial and may require experimentation to find the optimal setup. Use the RBFGenerator to create your basis matrices. For instance:
python
# Example centers spread evenly across the data range, and a given width
centers = np.linspace(0, 2.5 * np.pi, 10) # 10 RBF centres as an example
rbf_width = 1 # Example width
rbf_gen = CWP1.RBFGenerator(centers, width=rbf_width, bias=True)
# Generate RBF features for datasets
PHI_train = rbf_gen.evaluate(x_train)
Model Fitting and Evaluation:
Fit your Bayesian Linear Regression model to the training data. This involves computing the posterior distribution over the weights.
Evaluate model performance on the validation set, possibly adjusting hyperparameters (like the regularization parameter) based on validation performance.
Test set performance gives you the unbiased estimate of the model's predictive capabilities.
Visualization and Analysis:
Plot the model's predictions along with the actual data points to visualize fit.
Calculate and plot predictive variances to understand and communicate uncertainty in model predictions, especially informative in regions without observations.
Remember to iterate over your model's configurations (like the choice of RBF centers and width, noise variance, and regularization parameter) to find the one that best generalizes from the training data to unseen data. Also, take advantage of the visualizations to understand how different parts of the dataset influence your model's learning and predictions.