at University of Sheffield on Oct 27, 2015 [jupyter][google colab][reveal]
Neil D. Lawrence, University of Sheffield

#### Abstract

Generalization is the main objective of a machine learning algorithm. The models we design should work on data they have not seen before. Confirming whether a model generalizes well or not is the domain of model validation. In this lecture we introduce approaches to model validation such as hold out validation and cross validation.

## Review

• Last time: introduced basis functions.
• Showed how to maximize the likelihood of a non-linear model that’s linear in parameters.
• Explored the different characteristics of different basis function models

## Alan Turing 

If we had to summarise the objectives of machine learning in one word, a very good candidate for that word would be generalization. What is generalization? From a human perspective it might be summarised as the ability to take lessons learned in one domain and apply them to another domain. If we accept the definition given in the first session for machine learning,
$$\text{data} + \text{model} \xrightarrow{\text{compute}} \text{prediction}$$
then we see that without a model we can’t generalise: we only have data. Data is fine for answering very specific questions, like “Who won the Olympic Marathon in 2012?”, because we have that answer stored, however, we are not given the answer to many other questions. For example, Alan Turing was a formidable marathon runner, in 1946 he ran a time 2 hours 46 minutes (just under four minutes per kilometer, faster than I and most of the other Endcliffe Park Run runners can do 5 km). What is the probability he would have won an Olympics if one had been held in 1946?

To answer this question we need to generalize, but before we formalize the concept of generalization let’s introduce some formal representation of what it means to generalize in machine learning.

## Expected Loss 

Our objective function so far has been the negative log likelihood, which we have minimized (via the sum of squares error) to obtain our model. However, there is an alternative perspective on an objective function, that of a loss function. A loss function is a cost function associated with the penalty you might need to pay for a particular incorrect decision. One approach to machine learning involves specifying a loss function and considering how much a particular model is likely to cost us across its lifetime. We can represent this with an expectation. If our loss function is given as $L(\dataScalar, \inputScalar, \mappingVector)$ for a particular model that predicts $\dataScalar$ given $\inputScalar$ and $\mappingVector$ then we are interested in minimizing the expected loss under the likely distribution of $\dataScalar$ and $\inputScalar$. To understand this formally we define the true distribution of the data samples, $\dataScalar$, $\inputScalar$. This is a particularl distribution that we don’t have access to very often, and to represent that we define it with a variant of the letter ‘P’, $\mathbb{P}(\dataScalar, \inputScalar)$. If we genuinely pay $L(\dataScalar, \inputScalar, \mappingVector)$ for every mistake we make, and the future test data is genuinely drawn from $\mathbb{P}(\dataScalar, \inputScalar)$ then we can define our expected loss, or risk, to be,
$$R(\mappingVector) = \int L(\dataScalar, \inputScalar, \mappingVector) \mathbb{P}(\dataScalar, \inputScalar) \text{d}\dataScalar \text{d}\inputScalar.$$
Of course, in practice, this value can’t be computed but it serves as a reminder of what it is we are aiming to minimize and under certain circumstances it can be approximated.

## Sample Based Approximations

A sample based approximation to an expectation involves replacing the true expectation with a sum over samples from the distribution.

$$\int \mappingFunction(z) p(z) \text{d}z\approx \frac{1}{s}\sum_{i=1}^s \mappingFunction(z_i).$$
if {zi}i = 1s are a set of s independent and identically distributed samples from the distribution p(z). This approximation becomes better for larger s, although the rate of convergence to the true integral will be very dependent on the distribution p(z) and the function $\mappingFunction(z)$.

That said, this means we can approximate our true integral with the sum,
$$R(\mappingVector) \approx \frac{1}{\numData}\sum_{i=1}^{\numData} L(\dataScalar_i, \inputScalar_i, \mappingVector).$$

if $\dataScalar_i$ and $\inputScalar_i$ are independent samples from the true distribution $\mathbb{P}(\dataScalar, \inputScalar)$. Minimizing this sum directly is known as empirical risk minimization. The sum of squares error we have been using can be recovered for this case by considering a squared loss,
$$L(\dataScalar, \inputScalar, \mappingVector) = (\dataScalar-\mappingVector^\top\boldsymbol{\phi}(\inputScalar))^2,$$
which gives an empirical risk of the form
$$R(\mappingVector) \approx \frac{1}{\numData} \sum_{i=1}^{\numData} (\dataScalar_i - \mappingVector^\top \boldsymbol{\phi}(\inputScalar_i))^2$$
which up to the constant $\frac{1}{\numData}$ is identical to the objective function we have been using so far.

## Estimating Risk through Validation 

Unfortuantely, minimising the empirial risk only guarantees something about our performance on the training data. If we don’t have enough data for the approximation to the risk to be valid, then we can end up performing significantly worse on test data. Fortunately, we can also estimate the risk for test data through estimating the risk for unseen data. The main trick here is to ‘hold out’ a portion of our data from training and use the models performance on that sub-set of the data as a proxy for the true risk. This data is known as ‘validation’ data. It contrasts with test data, because its values are known at the model design time. However, in contrast to test date we don’t use it to fit our model. This means that it doesn’t exhibit the same bias that the empirical risk does when estimating the true risk.

## Validation 

In this lab we will explore techniques for model selection that make use of validation data. Data that isn’t seen by the model in the learning (or fitting) phase, but is used to validate our choice of model from amoungst the different designs we have selected.

In machine learning, we are looking to minimise the value of our objective function E with respect to its parameters $\mappingVector$. We do this by considering our training data. We minimize the value of the objective function as it’s observed at each training point. However we are really interested in how the model will perform on future data. For evaluating that we choose to hold out a portion of the data for evaluating the quality of the model.

We will review the different methods of model selection on the Olympics marathon data. Firstly we import the Olympic marathon data.

## Olympic Marathon Data

 Gold medal times for Olympic Marathon since 1896. Marathons before 1924 didn’t have a standardised distance. Present results using pace per km. In 1904 Marathon was badly organised leading to very slow times. Image from Wikimedia Commons http://bit.ly/16kMKHQ

The first thing we will do is load a standard data set for regression modelling. The data consists of the pace of Olympic Gold Medal Marathon winners for the Olympics from 1896 to present. First we load in the data and plot.

import numpy as np
import pods
data = pods.datasets.olympic_marathon_men()
x = data['X']
y = data['Y']

offset = y.mean()
scale = np.sqrt(y.var())
import matplotlib.pyplot as plt
import teaching_plots as plot
import mlai

xlim = (1875,2030)
ylim = (2.5, 6.5)
yhat = (y-offset)/scale

fig, ax = plt.subplots(figsize=plot.big_wide_figsize)
_ = ax.plot(x, y, 'r.',markersize=10)
ax.set_xlabel('year', fontsize=20)
ax.set_ylabel('pace min/km', fontsize=20)
ax.set_xlim(xlim)
ax.set_ylim(ylim)

mlai.write_figure(figure=fig,
filename='../slides/diagrams/datasets/olympic-marathon.svg',
transparent=True,
frameon=True)

Things to notice about the data include the outlier in 1904, in this year, the olympics was in St Louis, USA. Organizational problems and challenges with dust kicked up by the cars following the race meant that participants got lost, and only very few participants completed.

More recent years see more consistently quick marathons.

## Validation on the Olympic Marathon Data 

The first thing we’ll do is fit a standard linear model to the data. We recall from previous lectures and lab classes that to do this we need to solve the system
$$\basisMatrix^\top \basisMatrix \mappingVector = \basisMatrix^\top \dataVector$$
for $\mappingVector$ and use the resulting vector to make predictions at the training points and test points,
$$\mappingFunctionVector = \basisMatrix \mappingVector.$$
The prediction function can be used to compute the objective function,
$$E(\mappingVector) = \sum_{i}^{\numData} (\dataScalar_i - \mappingVector^\top\phi(\dataVector_i))^2$$
by substituting in the prediction in vector form we have
$$E(\mappingVector) = (\dataVector - \mappingFunctionVector)^\top(\dataVector - \mappingFunctionVector)$$

## Polynomial Fits to Olympics Data

from ipywidgets import IntSlider
pods.notebook.display_plots('olympic_LM_polynomial_number{num_basis:0>3}.svg',
directory='../slides/diagrams/ml',
num_basis=IntSlider(1, 1, max_basis, 1))

## Hold Out Validation on Olympic Marathon Data 

import pods
from ipywidgets import IntSlider
pods.notebook.display_plots('olympic_val_extra_LM_polynomial_number{num_basis:0>3}.svg',
directory='../slides/diagrams/ml',
num_basis=IntSlider(1, 1, max_basis, 1))

## Interpolation

import pods
from ipywidgets import IntSlider
pods.notebook.display_plots('olympic_val_inter_LM_polynomial_number{num_basis:0>3}.svg',
directory='../slides/diagrams/ml',
num_basis=IntSlider(1, 1, max_basis, 1))

## Hold Out Data

You have a conclusion as to which model fits best under the training error, but how do the two models perform in terms of validation? In this section we consider hold out validation. In hold out validation we remove a portion of the training data for validating the model on. The remaining data is used for fitting the model (training). Because this is a time series prediction, it makes sense for us to hold out data at the end of the time series. This means that we are validating on future predictions. We will hold out data from after 1980 and fit the model to the data before 1980.

# select indices of data to 'hold out'
indices_hold_out = np.flatnonzero(x>1980)

# Create a training set
x_train = np.delete(x, indices_hold_out, axis=0)
y_train = np.delete(y, indices_hold_out, axis=0)

# Create a hold out set
x_valid = np.take(x, indices_hold_out, axis=0)
y_valid = np.take(y, indices_hold_out, axis=0)

## Richer Basis Set

Now we have an approach for deciding which model to retain, we can consider the entire family of polynomial bases, with arbitrary degrees.

## Leave One Out Validation 

from ipywidgets import IntSlider
import pods
pods.notebook.display_plots('olympic_loo{part:0>3}_LM_polynomial_number{num_basis:0>3}.svg',
directory='../slides/diagrams/ml',
num_basis=IntSlider(1, 1, max_basis, 1),
part=IntSlider(0, 0, x.shape[0], 1))

Hold out validation uses a portion of the data to hold out and a portion of the data to train on. There is always a compromise between how much data to hold out and how much data to train on. The more data you hold out, the better the estimate of your performance at ‘run-time’ (when the model is used to make predictions in real applications). However, by holding out more data, you leave less data to train on, so you have a better validation, but a poorer quality model fit than you could have had if you’d used all the data for training. Leave one out cross validation leaves as much data in the training phase as possible: you only take one point out for your validation set. However, if you do this for hold-out validation, then the quality of your validation error is very poor because you are testing the model quality on one point only. In cross validation the approach is to improve this estimate by doing more than one model fit. In leave one out cross validation you fit $\numData$ different models, where $\numData$ is the number of your data. For each model fit you take out one data point, and train the model on the remaining n − 1 data points. You validate the model on the data point you’ve held out, but you do this $\numData$ times, once for each different model. You then take the average of all the $\numData$ badly estimated hold out validation errors. The average of this estimate is a good estimate of performance of those models on the test data.

## k-fold Cross Validation 

from ipywidgets import IntSlider
import pods
pods.notebook.display_plots('olympic_{num_parts}'.format(num_parts=num_parts) + 'cv{part:0>2}_LM_polynomial_number{number:0>3}.svg',
directory='../slides/diagrams/ml',
part=IntSlider(0,0,5,1),
number=IntSlider(1, 1, max_basis, 1))

Leave one out cross validation produces a very good estimate of the performance at test time, and is particularly useful if you don’t have a lot of data. In these cases you need to make as much use of your data for model fitting as possible, and having a large hold out data set (to validate model performance) can have a significant effect on the size of the data set you have to fit your model, and correspondingly, the complexity of the model you can fit. However, leave one out cross validation involves fitting $\numData$ models, where $\numData$ is your number of training data. For the olympics example, this is only 27 model fits, but in practice many data sets consist thousands or millions of data points, and fitting many millions of models for estimating validation error isn’t really practical. One option is to return to hold out validation, but another approach is to perform k-fold cross validation. In k-fold cross validation you split your data into k parts. Then you use k − 1 of those parts for training, and hold out one part for validation. Just like we did for the hold out validation above. In cross validation, however, you repeat this process. You swap the part of the data you just used for validation back in to the training set and select another part for validation. You then fit the model to the new training data and validate on the portion of data you’ve just extracted. Each split of training/validation data is called a fold and since you do this process k times, the procedure is known as k-fold cross validation. The term cross refers to the fact that you cross over your validation portion back into the training data every time you perform a fold.

## Bias Variance Decomposition 

Expected test error for different variations of the training data sampled from, $\Pr(\dataVector, \dataScalar)$
$$\mathbb{E}\left[ \left(\dataScalar - \mappingFunction^*(\dataVector)\right)^2 \right]$$
Decompose as
$$\mathbb{E}\left[ \left(\dataScalar - \mappingFunction(\dataVector)\right)^2 \right] = \text{bias}\left[\mappingFunction^*(\dataVector)\right]^2 + \text{variance}\left[\mappingFunction^*(\dataVector)\right] +\sigma^2$$

• Given by
$$\text{bias}\left[\mappingFunction^*(\dataVector)\right] = \mathbb{E}\left[\mappingFunction^*(\dataVector)\right] * \mappingFunction(\dataVector)$$
• Error due to bias comes from a model that’s too simple.

• Given by
$$\text{variance}\left[\mappingFunction^*(\dataVector)\right] = \mathbb{E}\left[\left(\mappingFunction^*(\dataVector) - \mathbb{E}\left[\mappingFunction^*(\dataVector)\right]\right)^2\right]$$
• Slight variations in the training set cause changes in the prediction. Error due to variance is error in the model due to an overly complex model.

## Bias vs Variance Error Plots 

Helper function for sampling data from two different classes.

import numpy as np
def create_data(per_cluster=30):
"""Create a randomly sampled data set

:param per_cluster: number of points in each cluster
"""
X = []
y = []
scale = 3
prec = 1/(scale*scale)
pos_mean = [[-1, 0],[0,0.5],[1,0]]
pos_cov = [[prec, 0.], [0., prec]]
neg_mean = [[0, -0.5],[0,-0.5],[0,-0.5]]
neg_cov = [[prec, 0.], [0., prec]]
for mean in pos_mean:
X.append(np.random.multivariate_normal(mean=mean, cov=pos_cov, size=per_class))
y.append(np.ones((per_class, 1)))
for mean in neg_mean:
X.append(np.random.multivariate_normal(mean=mean, cov=neg_cov, size=per_class))
y.append(np.zeros((per_class, 1)))
return np.vstack(X), np.vstack(y).flatten()

Helper function for plotting the decision boundary of the SVM.

def plot_contours(ax, cl, xx, yy, **params):
"""Plot the decision boundaries for a classifier.

:param ax: matplotlib axes object
:param cl: a classifier
:param xx: meshgrid ndarray
:param yy: meshgrid ndarray
:param params: dictionary of params to pass to contourf, optional
"""
Z = cl.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# Plot decision boundary and regions
out = ax.contour(xx, yy, Z,
levels=[-1., 0., 1],
colors='black',
linestyles=['dashed', 'solid', 'dashed'])
out = ax.contourf(xx, yy, Z,
levels=[Z.min(), 0, Z.max()],
colors=[[0.5, 1.0, 0.5], [1.0, 0.5, 0.5]])
return out
import mlai
import os
def decision_boundary_plot(models, X, y, axs, filename, titles, xlim, ylim):
"""Plot a decision boundary on the given axes

:param axs: the axes to plot on.
:param models: the SVM models to plot
:param titles: the titles for each axis
:param X: input training data
:param y: target training data"""
for ax in axs.flatten():
ax.clear()
X0, X1 = X[:, 0], X[:, 1]
if xlim is None:
xlim = [X0.min()-1, X0.max()+1]
if ylim is None:
ylim = [X1.min()-1, X1.max()+1]
xx, yy = np.meshgrid(np.arange(xlim[0], xlim[1], 0.02),
np.arange(ylim[0], ylim[1], 0.02))
for cl, title, ax in zip(models, titles, axs.flatten()):
plot_contours(ax, cl, xx, yy,
cmap=plt.cm.coolwarm, alpha=0.8)
ax.plot(X0[y==1], X1[y==1], 'r.', markersize=10)
ax.plot(X0[y==0], X1[y==0], 'g.', markersize=10)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)
mlai.write_figure(os.path.join(filename),
figure=fig,
transparent=True)
return xlim, ylim
import matplotlib
font = {'family' : 'sans',
'weight' : 'bold',
'size'   : 22}

matplotlib.rc('font', **font)
import matplotlib.pyplot as plt
# Create an instance of SVM and fit the data.
C = 100.0  # SVM regularization parameter
gammas = [0.001, 0.01, 0.1, 1]

per_class=30
num_samps = 20
# Set-up 2x2 grid for plotting.
fig, ax = plt.subplots(1, 4, figsize=(10,3))
xlim=None
ylim=None
for samp in range(num_samps):
X, y=create_data(per_class)
models = []
titles = []
for gamma in gammas:
models.append(svm.SVC(kernel='rbf', gamma=gamma, C=C))
titles.append('$\gamma={}$'.format(gamma))
models = (cl.fit(X, y) for cl in models)
xlim, ylim = decision_boundary_plot(models, X, y,
axs=ax,
filename='../slides/diagrams/ml/bias-variance{samp:0>3}.svg'.format(samp=samp),
titles=titles,
xlim=xlim,
ylim=ylim)
import pods
from ipywidgets import IntSlider
pods.notebook.display_plots('bias-variance{samp:0>3}.svg',
directory='../slides/diagrams/ml',
samp=IntSlider(0,0,10,1))