{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Generalization: Model Validation\n", "\n", "### 2022-02-27" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Abstract**: Generalization is the main objective of a machine learning\n", "algorithm. The models we design should work on data they have not seen\n", "before. Confirming whether a model generalizes well or not is the domain\n", "of *model validation*. In this review we introduce approaches to model\n", "validation such as hold out validation and cross validation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "::: {.cell .markdown}\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setup\n", "\n", "\\[edit\\]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "plt.rcParams.update({'font.size': 22})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## notutils\n", "\n", "\\[edit\\]\n", "\n", "This small package is a helper package for various notebook utilities\n", "used\n", "\n", "The software can be installed using" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install notutils" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "from the command prompt where you can access your python installation.\n", "\n", "The code is also available on GitHub:\n", "\n", "\n", "Once `notutils` is installed, it can be imported in the usual manner." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import notutils" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## mlai\n", "\n", "\\[edit\\]\n", "\n", "The `mlai` software is a suite of helper functions for teaching and\n", "demonstrating machine learning algorithms. It was first used in the\n", "Machine Learning and Adaptive Intelligence course in Sheffield in 2013.\n", "\n", "The software can be installed using" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install mlai" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "from the command prompt where you can access your python installation.\n", "\n", "The code is also available on GitHub: \n", "\n", "Once `mlai` is installed, it can be imported in the usual manner." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import mlai" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Review\n", "\n", "- Last time: introduced basis functions.\n", "- Showed how to maximize the likelihood of a non-linear model that’s\n", " linear in parameters.\n", "- Explored the different characteristics of different basis function\n", " models" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Alan Turing\n", "\n", "\\[edit\\]\n", "\n", "\n", "\n", "\n", "\n", "\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
\n", "\n", "Figure: Alan Turing, in 1946 he was only 11 minutes slower than the\n", "winner of the 1948 games. Would he have won a hypothetical games held in\n", "1946? Source:\n", "Alan\n", "Turing Internet Scrapbook.\n", "\n", "If we had to summarise the objectives of machine learning in one word, a\n", "very good candidate for that word would be *generalization*. What is\n", "generalization? From a human perspective it might be summarised as the\n", "ability to take lessons learned in one domain and apply them to another\n", "domain. If we accept the definition given in the first session for\n", "machine learning, $$\n", "\\text{data} + \\text{model} \\stackrel{\\text{compute}}{\\rightarrow} \\text{prediction}\n", "$$ then we see that without a model we can’t generalise: we only have\n", "data. Data is fine for answering very specific questions, like “Who won\n", "the Olympic Marathon in 2012?” because we have that answer stored,\n", "however, we are not given the answer to many other questions. For\n", "example, Alan Turing was a formidable marathon runner, in 1946 he ran a\n", "time 2 hours 46 minutes (just under four minutes per kilometer, faster\n", "than I and most of the other [Endcliffe Park\n", "Run](http://www.parkrun.org.uk/sheffieldhallam/) runners can do 5 km).\n", "What is the probability he would have won an Olympics if one had been\n", "held in 1946?\n", "\n", "To answer this question we need to generalize, but before we formalize\n", "the concept of generalization let’s introduce some formal representation\n", "of what it means to generalize in machine learning." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Expected Loss\n", "\n", "\\[edit\\]\n", "\n", "Our objective function so far has been the negative log likelihood,\n", "which we have minimized (via the sum of squares error) to obtain our\n", "model. However, there is an alternative perspective on an objective\n", "function, that of a *loss function*. A loss function is a cost function\n", "associated with the penalty you might need to pay for a particular\n", "incorrect decision. One approach to machine learning involves specifying\n", "a loss function and considering how much a particular model is likely to\n", "cost us across its lifetime. We can represent this with an expectation.\n", "If our loss function is given as $L(y, x, \\mathbf{ w})$ for a particular\n", "model that predicts $y$ given $x$ and $\\mathbf{ w}$ then we are\n", "interested in minimizing the expected loss under the likely distribution\n", "of $y$ and $x$. To understand this formally we define the *true*\n", "distribution of the data samples, $y$, $x$. This is a particular\n", "distribution that we don’t typically have access to. To represent it we\n", "define a variant of the letter ‘P,’ $\\mathbb{P}(y, x)$. If we genuinely\n", "pay $L(y, x, \\mathbf{ w})$ for every mistake we make, and the future\n", "test data is genuinely drawn from $\\mathbb{P}(y, x)$ then we can define\n", "our expected loss, or risk, to be, $$\n", "R(\\mathbf{ w}) = \\int L(y, x, \\mathbf{ w}) \\mathbb{P}(y, x) \\text{d}y\n", "\\text{d}x.\n", "$$ Of course, in practice, this value can’t be computed *but* it serves\n", "as a reminder of what it is we are aiming to minimize and under certain\n", "circumstances it can be approximated." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sample Based Approximations\n", "\n", "A sample based approximation to an expectation involves replacing the\n", "true expectation with a sum over samples from the distribution. $$\n", "\\int f(z) p(z) \\text{d}z\\approx \\frac{1}{s}\\sum_{i=1}^s f(z_i).\n", "$$ if $\\{z_i\\}_{i=1}^s$ are a set of $s$ independent and identically\n", "distributed samples from the distribution $p(z)$. This approximation\n", "becomes better for larger $s$, although the *rate of convergence* to the\n", "true integral will be very dependent on the distribution $p(z)$ *and*\n", "the function $f(z)$.\n", "\n", "That said, this means we can approximate our true integral with the sum,\n", "$$\n", "R(\\mathbf{ w}) \\approx \\frac{1}{n}\\sum_{i=1}^{n} L(y_i, x_i, \\mathbf{ w}).\n", "$$\n", "\n", "if $y_i$ and $x_i$ are independent samples from the true distribution\n", "$\\mathbb{P}(y, x)$. Minimizing this sum directly is known as *empirical\n", "risk minimization*. The sum of squares error we have been using can be\n", "recovered for this case by considering a *squared loss*, $$\n", "L(y, x, \\mathbf{ w}) = (y-\\mathbf{ w}^\\top\\boldsymbol{\\phi}(x))^2,\n", "$$ which gives an empirical risk of the form $$\n", "R(\\mathbf{ w}) \\approx \\frac{1}{n} \\sum_{i=1}^{n}\n", "(y_i - \\mathbf{ w}^\\top \\boldsymbol{\\phi}(x_i))^2\n", "$$ which up to the constant $\\frac{1}{n}$ is identical to the objective\n", "function we have been using so far." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Estimating Risk through Validation\n", "\n", "\\[edit\\]\n", "\n", "Unfortuantely, minimising the empirial risk only guarantees something\n", "about our performance on the training data. If we don’t have enough data\n", "for the approximation to the risk to be valid, then we can end up\n", "performing significantly worse on test data. Fortunately, we can also\n", "estimate the risk for test data through estimating the risk for unseen\n", "data. The main trick here is to ‘hold out’ a portion of our data from\n", "training and use the models performance on that sub-set of the data as a\n", "proxy for the true risk. This data is known as ‘validation’ data. It\n", "contrasts with test data, because its values are known at the model\n", "design time. However, in contrast to test date we don’t use it to fit\n", "our model. This means that it doesn’t exhibit the same bias that the\n", "empirical risk does when estimating the true risk." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Validation\n", "\n", "\\[edit\\]\n", "\n", "In this lab we will explore techniques for model selection that make use\n", "of validation data. Data that isn’t seen by the model in the learning\n", "(or fitting) phase, but is used to *validate* our choice of model from\n", "amoungst the different designs we have selected.\n", "\n", "In machine learning, we are looking to minimise the value of our\n", "objective function $E$ with respect to its parameters $\\mathbf{ w}$. We\n", "do this by considering our training data. We minimize the value of the\n", "objective function as it’s observed at each training point. However we\n", "are really interested in how the model will perform on future data. For\n", "evaluating that we choose to *hold out* a portion of the data for\n", "evaluating the quality of the model.\n", "\n", "We will review the different methods of model selection on the Olympics\n", "marathon data. Firstly we import the Olympic marathon data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Olympic Marathon Data\n", "\n", "\\[edit\\]\n", "\n", "\n", "\n", "\n", "\n", "\n", "
\n", "\n", "- Gold medal times for Olympic Marathon since 1896.\n", "- Marathons before 1924 didn’t have a standardised distance.\n", "- Present results using pace per km.\n", "- In 1904 Marathon was badly organised leading to very slow times.\n", "\n", "\n", "\n", "\n", "Image from Wikimedia Commons \n", "\n", "
\n", "\n", "The first thing we will do is load a standard data set for regression\n", "modelling. The data consists of the pace of Olympic Gold Medal Marathon\n", "winners for the Olympics from 1896 to present. First we load in the data\n", "and plot." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install pods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = pods.datasets.olympic_marathon_men()\n", "x = data['X']\n", "y = data['Y']\n", "\n", "offset = y.mean()\n", "scale = np.sqrt(y.var())\n", "yhat = (y - offset)/scale" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import mlai.plot as plot\n", "import mlai" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xlim = (1875,2030)\n", "ylim = (2.5, 6.5)\n", "\n", "fig, ax = plt.subplots(figsize=plot.big_wide_figsize)\n", "_ = ax.plot(x, y, 'r.',markersize=10)\n", "ax.set_xlabel('year', fontsize=20)\n", "ax.set_ylabel('pace min/km', fontsize=20)\n", "ax.set_xlim(xlim)\n", "ax.set_ylim(ylim)\n", "\n", "mlai.write_figure(filename='olympic-marathon.svg', \n", " directory='./datasets')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Figure: Olympic marathon pace times since 1896.\n", "\n", "Things to notice about the data include the outlier in 1904, in this\n", "year, the olympics was in St Louis, USA. Organizational problems and\n", "challenges with dust kicked up by the cars following the race meant that\n", "participants got lost, and only very few participants completed.\n", "\n", "More recent years see more consistently quick marathons." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Validation on the Olympic Marathon Data\n", "\n", "\\[edit\\]\n", "\n", "The first thing we’ll do is fit a standard linear model to the data. We\n", "recall from previous lectures and lab classes that to do this we need to\n", "solve the system $$\n", "\\boldsymbol{ \\Phi}^\\top \\boldsymbol{ \\Phi}\\mathbf{ w}= \\boldsymbol{ \\Phi}^\\top \\mathbf{ y}\n", "$$ for $\\mathbf{ w}$ and use the resulting vector to make predictions at\n", "the training points and test points, $$\n", "\\mathbf{ f}= \\boldsymbol{ \\Phi}\\mathbf{ w}.\n", "$$ The prediction function can be used to compute the objective\n", "function, $$\n", "E(\\mathbf{ w}) = \\sum_{i}^{n} (y_i - \\mathbf{ w}^\\top\\phi(\\mathbf{ y}_i))^2\n", "$$ by substituting in the prediction in vector form we have $$\n", "E(\\mathbf{ w}) = (\\mathbf{ y}- \\mathbf{ f})^\\top(\\mathbf{ y}- \\mathbf{ f})\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 1\n", "\n", "In this question you will construct some flexible general code for\n", "fitting linear models.\n", "\n", "Create a python function that computes $\\boldsymbol{ \\Phi}$ for the\n", "linear basis,\n", "$$\\boldsymbol{ \\Phi}= \\begin{bmatrix} \\mathbf{ y}& \\mathbf{1}\\end{bmatrix}$$\n", "Name your function `linear`. `Phi` should be in the form of a *design\n", "matrix* and `x` should be in the form of a `numpy` two dimensional array\n", "with $n$ rows and 1 column Calls to your function should be in the\n", "following form:\n", "\n", "`Phi = linear(x)`\n", "\n", "Create a python function that accepts, as arguments, a python function\n", "that defines a basis (like the one you’ve just created called `linear`)\n", "as well as a set of inputs and a vector of parameters. Your new python\n", "function should return a prediction. Name your function `prediction`.\n", "The return value `f` should be a two dimensional `numpy` array with $n$\n", "rows and $1$ column, where $n$ is the number of data points. Calls to\n", "your function should be in the following form:\n", "\n", "`f = prediction(w, x, linear)`\n", "\n", "Create a python function that computes the sum of squares objective\n", "function (or error function). It should accept your input data (or\n", "covariates) and target data (or response variables) and your parameter\n", "vector `w` as arguments. It should also accept a python function that\n", "represents the basis. Calls to your function should be in the following\n", "form:\n", "\n", "`e = objective(w, x, y, linear)`\n", "\n", "Create a function that solves the linear system for the set of\n", "parameters that minimizes the sum of squares objective. It should accept\n", "input data, target data and a python function for the basis as the\n", "inputs. Calls to your function should be in the following form:\n", "\n", "`w = fit(x, y, linear)`\n", "\n", "Fit a linear model to the olympic data using these functions and plot\n", "the resulting prediction between 1890 and 2020. Set the title of the\n", "plot to be the error of the fit on the *training data*." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your answer to Exercise 1 here\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Polynomial Fit: Training Error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 2\n", "\n", "In this question we extend the code above to a non- linear basis (a\n", "quadratic function).\n", "\n", "Start by creating a python-function called `quadratic`. It should\n", "compute the quadratic basis. $$\n", "\\boldsymbol{ \\Phi}= \\begin{bmatrix} \\mathbf{1} & \\mathbf{ y}& \\mathbf{ y}^2\\end{bmatrix}\n", "$$ It should be called in the following form:\n", "\n", "`Phi = quadratic(x)`\n", "\n", "Use this to compute the quadratic fit for the model, again plotting the\n", "result titled by the error." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your answer to Exercise 2 here\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Polynomial Fits to Olympics Data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pods\n", "import mlai" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "max_basis = 26\n", "data_limits = (1888, 2020)\n", "basis = mlai.Basis(mlai.polynomial, number=1, data_limits=data_limits)\n", "num_data = x.shape[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import teaching_plots as plot" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot.rmse_fit(x, y, param_name='number', param_range=(1, max_basis+1), \n", " model=mlai.LM, basis=basis, \n", " xlim=data_limits, objective_ylim=[0, 0.8],\n", " diagrams='./ml')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from ipywidgets import IntSlider" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pods.notebook.display_plots('olympic_LM_polynomial_number{num_basis:0>3}.svg', \n", " directory='./ml', \n", " num_basis=IntSlider(1, 1, max_basis, 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Figure: Polynomial fit to olympic data with 26 basis functions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Hold Out Validation on Olympic Marathon Data\n", "\n", "\\[edit\\]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import teaching_plots as plot\n", "import mlai" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_limits=xlim\n", "basis = mlai.Basis(mlai.polynomial, number=1, data_limits=data_limits)\n", "max_basis = 11" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot.holdout_fit(x, y, param_name='number', \n", " param_range=(1, max_basis+1), \n", " model=mlai.LM, basis=basis, \n", " permute=False, objective_ylim=[0, 0.8], \n", " xlim=data_limits, prefix='olympic_val_extra', \n", " diagrams='./ml')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pods\n", "from ipywidgets import IntSlider" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pods.notebook.display_plots('olympic_val_extra_LM_polynomial_number{num_basis:0>3}.svg', \n", " directory='./ml', \n", " num_basis=IntSlider(1, 1, max_basis, 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Figure: Olympic marathon data with validation error for\n", "extrapolation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extrapolation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interpolation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import teaching_plots as plot" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot.holdout_fit(x, y, param_name='number', param_range=(1, max_basis+1), \n", " model=mlai.LM, basis=basis, \n", " xlim=data_limits, prefix='olympic_val_inter', \n", " objective_ylim=[0.1, 0.6], permute=True,\n", " diagrams='./ml')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pods\n", "from ipywidgets import IntSlider" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pods.notebook.display_plots('olympic_val_inter_LM_polynomial_number{num_basis:0>3}.svg', \n", " directory='./ml', \n", " num_basis=IntSlider(1, 1, max_basis, 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Figure: Olympic marathon data with validation error for\n", "interpolation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Choice of Validation Set" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Hold Out Data\n", "\n", "You have a conclusion as to which model fits best under the training\n", "error, but how do the two models perform in terms of validation? In this\n", "section we consider *hold out* validation. In hold out validation we\n", "remove a portion of the training data for *validating* the model on. The\n", "remaining data is used for fitting the model (training). Because this is\n", "a time series prediction, it makes sense for us to hold out data at the\n", "end of the time series. This means that we are validating on future\n", "predictions. We will hold out data from after 1980 and fit the model to\n", "the data before 1980." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# select indices of data to 'hold out'\n", "indices_hold_out = np.flatnonzero(x>1980)\n", "\n", "# Create a training set\n", "x_train = np.delete(x, indices_hold_out, axis=0)\n", "y_train = np.delete(y, indices_hold_out, axis=0)\n", "\n", "# Create a hold out set\n", "x_valid = np.take(x, indices_hold_out, axis=0)\n", "y_valid = np.take(y, indices_hold_out, axis=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 3\n", "\n", "For both the linear and quadratic models, fit the model to the data up\n", "until 1980 and then compute the error on the held out data (from 1980\n", "onwards). Which model performs better on the validation data?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your answer to Exercise 3 here\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Richer Basis Set\n", "\n", "Now we have an approach for deciding which model to retain, we can\n", "consider the entire family of polynomial bases, with arbitrary degrees." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 4\n", "\n", "Now we are going to build a more sophisticated form of basis function,\n", "one that can accept arguments to its inputs (similar to those we used in\n", "[this lab](./week4.ipynb)). Here we will start with a polynomial basis.\n", "\n", " def polynomial(x, degree, loc, scale):\n", " degrees =np.arange(degree+1)\n", " return ((x-loc)/scale)**degrees\n", "\n", "The basis as we’ve defined it has three arguments as well as the input.\n", "The degree of the polynomial, the scale of the polynomial and the\n", "offset. These arguments need to be passed to the basis functions\n", "whenever they are called. Modify your code to pass these additional\n", "arguments to the python function for creating the basis. Do this for\n", "each of your functions `predict`, `fit` and `objective`. You will find\n", "`*args` (or `**kwargs`) useful.\n", "\n", "Write code that tries to fit different models to the data with\n", "polynomial basis. Use a maximum degree for your basis from 0 to 17. For\n", "each polynomial store the *hold out validation error* and the *training\n", "error*. When you have finished the computation plot the hold out error\n", "for your models and the training error for your p. When computing your\n", "polynomial basis use `offset=1956.` and `scale=120.` to ensure that the\n", "data is mapped (roughly) to the -1, 1 range.\n", "\n", "Which polynomial has the minimum training error? Which polynomial has\n", "the minimum validation error?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your answer to Exercise 4 here\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Leave One Out Validation\n", "\n", "\\[edit\\]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import mlai\n", "import pods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_limits=xlim\n", "basis = mlai.Basis(mlai.polynomial, number=1, data_limits=data_limits)\n", "max_basis = 11" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import teaching_plots as plot" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The leave one out cross validation can be slow to run, so here it's commented.\n", "#plot.loo_fit(x, y, param_name='number', param_range=(1, max_basis+1), \n", "# model=mlai.LM, basis=basis, \n", "# xlim=data_limits, objective_ylim=[0, 0.8], prefix='olympic_loo',\n", "# diagrams='./ml')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from ipywidgets import IntSlider\n", "import pods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pods.notebook.display_plots('olympic_loo{part:0>3}_LM_polynomial_number{num_basis:0>3}.svg', \n", " directory='./ml', \n", " num_basis=IntSlider(1, 1, max_basis, 1), \n", " part=IntSlider(0, 0, x.shape[0], 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hold out validation uses a portion of the data to hold out and a portion\n", "of the data to train on. There is always a compromise between how much\n", "data to hold out and how much data to train on. The more data you hold\n", "out, the better the estimate of your performance at ‘run-time’ (when the\n", "model is used to make predictions in real applications). However, by\n", "holding out more data, you leave less data to train on, so you have a\n", "better validation, but a poorer quality model fit than you could have\n", "had if you’d used all the data for training. Leave one out cross\n", "validation leaves as much data in the training phase as possible: you\n", "only take *one point* out for your validation set. However, if you do\n", "this for hold-out validation, then the quality of your validation error\n", "is very poor because you are testing the model quality on one point\n", "only. In *cross validation* the approach is to improve this estimate by\n", "doing more than one model fit. In *leave one out cross validation* you\n", "fit $n$ different models, where $n$ is the number of your data. For each\n", "model fit you take out one data point, and train the model on the\n", "remaining $n-1$ data points. You validate the model on the data point\n", "you’ve held out, but you do this $n$ times, once for each different\n", "model. You then take the *average* of all the $n$ badly estimated hold\n", "out validation errors. The average of this estimate is a good estimate\n", "of performance of those models on the test data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 5\n", "\n", "Write code that computes the *leave one out* validation error for the\n", "olympic data and the polynomial basis. Use the functions you have\n", "created above: `objective`, `fit`, `polynomial`. Compute the\n", "*leave-one-out* cross validation error for basis functions containing a\n", "maximum degree from 0 to 17." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your answer to Exercise 5 here\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## $k$-fold Cross Validation\n", "\n", "\\[edit\\]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import mlai\n", "import pods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_limits=xlim\n", "basis = mlai.Basis(mlai.polynomial, number=1, data_limits=data_limits)\n", "max_basis = 11" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import teaching_plots as plot" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "num_parts=5 # set k\n", "plot.cv_fit(x, y, param_name='number', \n", " param_range=(1, max_basis+1),\n", " model=mlai.LM, \n", " basis=basis, \n", " xlim=data_limits, \n", " objective_ylim=[0.2,0.6], \n", " num_parts=num_parts,\n", " diagrams='./ml')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from ipywidgets import IntSlider\n", "import pods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pods.notebook.display_plots('olympic_{num_parts}'.format(num_parts=num_parts) + 'cv{part:0>2}_LM_polynomial_number{number:0>3}.svg', \n", " directory='./ml', \n", " part=IntSlider(0,0,5,1),\n", " number=IntSlider(1, 1, max_basis, 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Leave one out cross validation produces a very good estimate of the\n", "performance at test time, and is particularly useful if you don’t have a\n", "lot of data. In these cases you need to make as much use of your data\n", "for model fitting as possible, and having a large hold out data set (to\n", "validate model performance) can have a significant effect on the size of\n", "the data set you have to fit your model, and correspondingly, the\n", "complexity of the model you can fit. However, leave one out cross\n", "validation involves fitting $n$ models, where $n$ is your number of\n", "training data. For the olympics example, this is only 27 model fits, but\n", "in practice many data sets consist thousands or millions of data points,\n", "and fitting many millions of models for estimating validation error\n", "isn’t really practical. One option is to return to *hold out*\n", "validation, but another approach is to perform $k$-fold cross\n", "validation. In $k$-fold cross validation you split your data into $k$\n", "parts. Then you use $k-1$ of those parts for training, and hold out one\n", "part for validation. Just like we did for the hold out validation above.\n", "In *cross* validation, however, you repeat this process. You swap the\n", "part of the data you just used for validation back in to the training\n", "set and select another part for validation. You then fit the model to\n", "the new training data and validate on the portion of data you’ve just\n", "extracted. Each split of training/validation data is called a *fold* and\n", "since you do this process $k$ times, the procedure is known as $k$-fold\n", "cross validation. The term *cross* refers to the fact that you cross\n", "over your validation portion back into the training data every time you\n", "perform a fold." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 6\n", "\n", "Perform $k$-fold cross validation on the olympic data with your\n", "polynomial basis. Use $k$ set to 5 (e.g. five fold cross validation). Do\n", "the different forms of validation select different models? Does five\n", "fold cross validation always select the same model?\n", "\n", "*Note*: The data doesn’t divide into 5 equal size partitions for the\n", "five fold cross validation error. Don’t worry about this too much. Two\n", "of the partitions will have an extra data point. You might find\n", "`np.random.permutation?` useful." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your answer to Exercise 6 here\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Further Reading\n", "\n", "- Section 1.5 of Rogers and Girolami (2011)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Thanks!\n", "\n", "For more information on these subjects and more you might want to check\n", "the following resources.\n", "\n", "- twitter: [@lawrennd](https://twitter.com/lawrennd)\n", "- podcast: [The Talking Machines](http://thetalkingmachines.com)\n", "- newspaper: [Guardian Profile\n", " Page](http://www.theguardian.com/profile/neil-lawrence)\n", "- blog:\n", " [http://inverseprobability.com](http://inverseprobability.com/blog.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Rogers, S., Girolami, M., 2011. A first course in machine learning. CRC\n", "Press." ] } ], "nbformat": 4, "nbformat_minor": 5, "metadata": {} }