added ipynb files
This commit is contained in:
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -0,0 +1,796 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"<!-- dom:TITLE: Data Analysis and Machine Learning: Logistic Regression -->\n",
|
||||
"# Data Analysis and Machine Learning: Logistic Regression\n",
|
||||
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
|
||||
"<!-- Author: --> \n",
|
||||
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
|
||||
"\n",
|
||||
"Date: **Sep 16, 2020**\n",
|
||||
"\n",
|
||||
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## To do for log reg\n",
|
||||
"\n",
|
||||
"* Develop code for log reg step by step, with link to gradient descent part\n",
|
||||
"\n",
|
||||
"* show how to read and set up design matrix\n",
|
||||
"\n",
|
||||
"* use breast cancer data as example\n",
|
||||
"\n",
|
||||
"* develop other classification examples, pulsar example\n",
|
||||
"\n",
|
||||
"<!-- !split -->\n",
|
||||
"## Logistic Regression\n",
|
||||
"\n",
|
||||
"In linear regression our main interest was centered on learning the\n",
|
||||
"coefficients of a functional fit (say a polynomial) in order to be\n",
|
||||
"able to predict the response of a continuous variable on some unseen\n",
|
||||
"data. The fit to the continuous variable $y_i$ is based on some\n",
|
||||
"independent variables $\\hat{x}_i$. Linear regression resulted in\n",
|
||||
"analytical expressions for standard ordinary Least Squares or Ridge\n",
|
||||
"regression (in terms of matrices to invert) for several quantities,\n",
|
||||
"ranging from the variance and thereby the confidence intervals of the\n",
|
||||
"parameters $\\hat{\\beta}$ to the mean squared error. If we can invert\n",
|
||||
"the product of the design matrices, linear regression gives then a\n",
|
||||
"simple recipe for fitting our data.\n",
|
||||
"\n",
|
||||
"<!-- !split -->\n",
|
||||
"## Classification problems\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Classification problems, however, are concerned with outcomes taking\n",
|
||||
"the form of discrete variables (i.e. categories). We may for example,\n",
|
||||
"on the basis of DNA sequencing for a number of patients, like to find\n",
|
||||
"out which mutations are important for a certain disease; or based on\n",
|
||||
"scans of various patients' brains, figure out if there is a tumor or\n",
|
||||
"not; or given a specific physical system, we'd like to identify its\n",
|
||||
"state, say whether it is an ordered or disordered system (typical\n",
|
||||
"situation in solid state physics); or classify the status of a\n",
|
||||
"patient, whether she/he has a stroke or not and many other similar\n",
|
||||
"situations.\n",
|
||||
"\n",
|
||||
"The most common situation we encounter when we apply logistic\n",
|
||||
"regression is that of two possible outcomes, normally denoted as a\n",
|
||||
"binary outcome, true or false, positive or negative, success or\n",
|
||||
"failure etc.\n",
|
||||
"\n",
|
||||
"## Optimization and Deep learning\n",
|
||||
"\n",
|
||||
"Logistic regression will also serve as our stepping stone towards\n",
|
||||
"neural network algorithms and supervised deep learning. For logistic\n",
|
||||
"learning, the minimization of the cost function leads to a non-linear\n",
|
||||
"equation in the parameters $\\hat{\\beta}$. The optimization of the\n",
|
||||
"problem calls therefore for minimization algorithms. This forms the\n",
|
||||
"bottle neck of all machine learning algorithms, namely how to find\n",
|
||||
"reliable minima of a multi-variable function. This leads us to the\n",
|
||||
"family of gradient descent methods. The latter are the working horses\n",
|
||||
"of basically all modern machine learning algorithms.\n",
|
||||
"\n",
|
||||
"We note also that many of the topics discussed here on logistic \n",
|
||||
"regression are also commonly used in modern supervised Deep Learning\n",
|
||||
"models, as we will see later.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"<!-- !split -->\n",
|
||||
"## Basics\n",
|
||||
"\n",
|
||||
"We consider the case where the dependent variables, also called the\n",
|
||||
"responses or the outcomes, $y_i$ are discrete and only take values\n",
|
||||
"from $k=0,\\dots,K-1$ (i.e. $K$ classes).\n",
|
||||
"\n",
|
||||
"The goal is to predict the\n",
|
||||
"output classes from the design matrix $\\hat{X}\\in\\mathbb{R}^{n\\times p}$\n",
|
||||
"made of $n$ samples, each of which carries $p$ features or predictors. The\n",
|
||||
"primary goal is to identify the classes to which new unseen samples\n",
|
||||
"belong.\n",
|
||||
"\n",
|
||||
"Let us specialize to the case of two classes only, with outputs\n",
|
||||
"$y_i=0$ and $y_i=1$. Our outcomes could represent the status of a\n",
|
||||
"credit card user that could default or not on her/his credit card\n",
|
||||
"debt. That is"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"y_i = \\begin{bmatrix} 0 & \\mathrm{no}\\\\ 1 & \\mathrm{yes} \\end{bmatrix}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Linear classifier\n",
|
||||
"\n",
|
||||
"Before moving to the logistic model, let us try to use our linear\n",
|
||||
"regression model to classify these two outcomes. We could for example\n",
|
||||
"fit a linear model to the default case if $y_i > 0.5$ and the no\n",
|
||||
"default case $y_i \\leq 0.5$.\n",
|
||||
"\n",
|
||||
"We would then have our \n",
|
||||
"weighted linear combination, namely"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"<!-- Equation labels as ordinary links -->\n",
|
||||
"<div id=\"_auto1\"></div>\n",
|
||||
"\n",
|
||||
"$$\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\hat{y} = \\hat{X}^T\\hat{\\beta} + \\hat{\\epsilon},\n",
|
||||
"\\label{_auto1} \\tag{1}\n",
|
||||
"\\end{equation}\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"where $\\hat{y}$ is a vector representing the possible outcomes, $\\hat{X}$ is our\n",
|
||||
"$n\\times p$ design matrix and $\\hat{\\beta}$ represents our estimators/predictors.\n",
|
||||
"\n",
|
||||
"## Some selected properties\n",
|
||||
"\n",
|
||||
"The main problem with our function is that it takes values on the\n",
|
||||
"entire real axis. In the case of logistic regression, however, the\n",
|
||||
"labels $y_i$ are discrete variables. A typical example is the credit\n",
|
||||
"card data discussed below here, where we can set the state of\n",
|
||||
"defaulting the debt to $y_i=1$ and not to $y_i=0$ for one the persons\n",
|
||||
"in the data set (see the full example below).\n",
|
||||
"\n",
|
||||
"One simple way to get a discrete output is to have sign\n",
|
||||
"functions that map the output of a linear regressor to values $\\{0,1\\}$,\n",
|
||||
"$f(s_i)=sign(s_i)=1$ if $s_i\\ge 0$ and 0 if otherwise. \n",
|
||||
"We will encounter this model in our first demonstration of neural networks. Historically it is called the \"perceptron\" model in the machine learning\n",
|
||||
"literature. This model is extremely simple. However, in many cases it is more\n",
|
||||
"favorable to use a ``soft\" classifier that outputs\n",
|
||||
"the probability of a given category. This leads us to the logistic function.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## The logistic function\n",
|
||||
"\n",
|
||||
"The perceptron is an example of a ``hard classification\" model. We\n",
|
||||
"will encounter this model when we discuss neural networks as\n",
|
||||
"well. Each datapoint is deterministically assigned to a category (i.e\n",
|
||||
"$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a \"soft\"\n",
|
||||
"classifier that outputs the probability of a given category rather\n",
|
||||
"than a single value. For example, given $x_i$, the classifier\n",
|
||||
"outputs the probability of being in a category $k$. Logistic regression\n",
|
||||
"is the most common example of a so-called soft classifier. In logistic\n",
|
||||
"regression, the probability that a data point $x_i$\n",
|
||||
"belongs to a category $y_i=\\{0,1\\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"p(t) = \\frac{1}{1+\\mathrm \\exp{-t}}=\\frac{\\exp{t}}{1+\\mathrm \\exp{t}}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Note that $1-p(t)= p(-t)$.\n",
|
||||
"\n",
|
||||
"## Examples of likelihood functions used in logistic regression and nueral networks\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"The following code plots the logistic function, the step function and other functions we will encounter from here and on."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%matplotlib inline\n",
|
||||
"\n",
|
||||
"\"\"\"The sigmoid function (or the logistic curve) is a\n",
|
||||
"function that takes any real number, z, and outputs a number (0,1).\n",
|
||||
"It is useful in neural networks for assigning weights on a relative scale.\n",
|
||||
"The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n",
|
||||
"\n",
|
||||
"import numpy\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import math as mt\n",
|
||||
"\n",
|
||||
"z = numpy.arange(-5, 5, .1)\n",
|
||||
"sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n",
|
||||
"sigma = sigma_fn(z)\n",
|
||||
"\n",
|
||||
"fig = plt.figure()\n",
|
||||
"ax = fig.add_subplot(111)\n",
|
||||
"ax.plot(z, sigma)\n",
|
||||
"ax.set_ylim([-0.1, 1.1])\n",
|
||||
"ax.set_xlim([-5,5])\n",
|
||||
"ax.grid(True)\n",
|
||||
"ax.set_xlabel('z')\n",
|
||||
"ax.set_title('sigmoid function')\n",
|
||||
"\n",
|
||||
"plt.show()\n",
|
||||
"\n",
|
||||
"\"\"\"Step Function\"\"\"\n",
|
||||
"z = numpy.arange(-5, 5, .02)\n",
|
||||
"step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n",
|
||||
"step = step_fn(z)\n",
|
||||
"\n",
|
||||
"fig = plt.figure()\n",
|
||||
"ax = fig.add_subplot(111)\n",
|
||||
"ax.plot(z, step)\n",
|
||||
"ax.set_ylim([-0.5, 1.5])\n",
|
||||
"ax.set_xlim([-5,5])\n",
|
||||
"ax.grid(True)\n",
|
||||
"ax.set_xlabel('z')\n",
|
||||
"ax.set_title('step function')\n",
|
||||
"\n",
|
||||
"plt.show()\n",
|
||||
"\n",
|
||||
"\"\"\"tanh Function\"\"\"\n",
|
||||
"z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n",
|
||||
"t = numpy.tanh(z)\n",
|
||||
"\n",
|
||||
"fig = plt.figure()\n",
|
||||
"ax = fig.add_subplot(111)\n",
|
||||
"ax.plot(z, t)\n",
|
||||
"ax.set_ylim([-1.0, 1.0])\n",
|
||||
"ax.set_xlim([-2*mt.pi,2*mt.pi])\n",
|
||||
"ax.grid(True)\n",
|
||||
"ax.set_xlabel('z')\n",
|
||||
"ax.set_title('tanh function')\n",
|
||||
"\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Two parameters\n",
|
||||
"\n",
|
||||
"We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\\beta$ in our fitting of the Sigmoid function, that is we define probabilities"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\begin{align*}\n",
|
||||
"p(y_i=1|x_i,\\hat{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n",
|
||||
"p(y_i=0|x_i,\\hat{\\beta}) &= 1 - p(y_i=1|x_i,\\hat{\\beta}),\n",
|
||||
"\\end{align*}\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"where $\\hat{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n",
|
||||
"\n",
|
||||
"Note that we used"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"p(y_i=0\\vert x_i, \\hat{\\beta}) = 1-p(y_i=1\\vert x_i, \\hat{\\beta}).\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"<!-- !split -->\n",
|
||||
"## Maximum likelihood\n",
|
||||
"\n",
|
||||
"In order to define the total likelihood for all possible outcomes from a \n",
|
||||
"dataset $\\mathcal{D}=\\{(y_i,x_i)\\}$, with the binary labels\n",
|
||||
"$y_i\\in\\{0,1\\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle. \n",
|
||||
"We aim thus at maximizing \n",
|
||||
"the probability of seeing the observed data. We can then approximate the \n",
|
||||
"likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\begin{align*}\n",
|
||||
"P(\\mathcal{D}|\\hat{\\beta})& = \\prod_{i=1}^n \\left[p(y_i=1|x_i,\\hat{\\beta})\\right]^{y_i}\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]^{1-y_i}\\nonumber \\\\\n",
|
||||
"\\end{align*}\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"from which we obtain the log-likelihood and our **cost/loss** function"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left( y_i\\log{p(y_i=1|x_i,\\hat{\\beta})} + (1-y_i)\\log\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]\\right).\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## The cost function rewritten\n",
|
||||
"\n",
|
||||
"Reordering the logarithms, we can rewrite the **cost/loss** function as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\\beta$.\n",
|
||||
"Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathcal{C}(\\hat{\\beta})=-\\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n",
|
||||
"in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression.\n",
|
||||
"\n",
|
||||
"## Minimizing the cross entropy\n",
|
||||
"\n",
|
||||
"The cross entropy is a convex function of the weights $\\hat{\\beta}$ and,\n",
|
||||
"therefore, any local minimizer is a global minimizer. \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Minimizing this\n",
|
||||
"cost function with respect to the two parameters $\\beta_0$ and $\\beta_1$ we obtain"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_0} = -\\sum_{i=1}^n \\left(y_i -\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right),\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"and"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_1} = -\\sum_{i=1}^n \\left(y_ix_i -x_i\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right).\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## A more compact expression\n",
|
||||
"\n",
|
||||
"Let us now define a vector $\\hat{y}$ with $n$ elements $y_i$, an\n",
|
||||
"$n\\times p$ matrix $\\hat{X}$ which contains the $x_i$ values and a\n",
|
||||
"vector $\\hat{p}$ of fitted probabilities $p(y_i\\vert x_i,\\hat{\\beta})$. We can rewrite in a more compact form the first\n",
|
||||
"derivative of cost function as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}} = -\\hat{X}^T\\left(\\hat{y}-\\hat{p}\\right).\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"If we in addition define a diagonal matrix $\\hat{W}$ with elements \n",
|
||||
"$p(y_i\\vert x_i,\\hat{\\beta})(1-p(y_i\\vert x_i,\\hat{\\beta})$, we can obtain a compact expression of the second derivative as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T} = \\hat{X}^T\\hat{W}\\hat{X}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Extending to more predictors\n",
|
||||
"\n",
|
||||
"Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\log{ \\frac{p(\\hat{\\beta}\\hat{x})}{1-p(\\hat{\\beta}\\hat{x})}} = \\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Here we defined $\\hat{x}=[1,x_1,x_2,\\dots,x_p]$ and $\\hat{\\beta}=[\\beta_0, \\beta_1, \\dots, \\beta_p]$ leading to"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"p(\\hat{\\beta}\\hat{x})=\\frac{ \\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}{1+\\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Including more classes\n",
|
||||
"\n",
|
||||
"Till now we have mainly focused on two classes, the so-called binary\n",
|
||||
"system. Suppose we wish to extend to $K$ classes. Let us for the sake\n",
|
||||
"of simplicity assume we have only two predictors. We have then\n",
|
||||
"following model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"1\n",
|
||||
"5\n",
|
||||
" \n",
|
||||
"<\n",
|
||||
"<\n",
|
||||
"<\n",
|
||||
"!\n",
|
||||
"!\n",
|
||||
"M\n",
|
||||
"A\n",
|
||||
"T\n",
|
||||
"H\n",
|
||||
"_\n",
|
||||
"B\n",
|
||||
"L\n",
|
||||
"O\n",
|
||||
"C\n",
|
||||
"K"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\log{\\frac{p(C=2\\vert x)}{p(K\\vert x)}} = \\beta_{20}+\\beta_{21}x_1,\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"and so on till the class $C=K-1$ class"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\log{\\frac{p(C=K-1\\vert x)}{p(K\\vert x)}} = \\beta_{(K-1)0}+\\beta_{(K-1)1}x_1,\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"and the model is specified in term of $K-1$ so-called log-odds or\n",
|
||||
"**logit** transformations.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## More classes\n",
|
||||
"\n",
|
||||
"In our discussion of neural networks we will encounter the above again\n",
|
||||
"in terms of a slightly modified function, the so-called **Softmax** function.\n",
|
||||
"\n",
|
||||
"The softmax function is used in various multiclass classification\n",
|
||||
"methods, such as multinomial logistic regression (also known as\n",
|
||||
"softmax regression), multiclass linear discriminant analysis, naive\n",
|
||||
"Bayes classifiers, and artificial neural networks. Specifically, in\n",
|
||||
"multinomial logistic regression and linear discriminant analysis, the\n",
|
||||
"input to the function is the result of $K$ distinct linear functions,\n",
|
||||
"and the predicted probability for the $k$-th class given a sample\n",
|
||||
"vector $\\hat{x}$ and a weighting vector $\\hat{\\beta}$ is (with two\n",
|
||||
"predictors):"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"p(C=k\\vert \\mathbf {x} )=\\frac{\\exp{(\\beta_{k0}+\\beta_{k1}x_1)}}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"It is easy to extend to more predictors. The final class is"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"p(C=K\\vert \\mathbf {x} )=\\frac{1}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}},\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"and they sum to one. Our earlier discussions were all specialized to\n",
|
||||
"the case with two classes only. It is easy to see from the above that\n",
|
||||
"what we derived earlier is compatible with these equations.\n",
|
||||
"\n",
|
||||
"To find the optimal parameters we would typically use a gradient\n",
|
||||
"descent method. Newton's method and gradient descent methods are\n",
|
||||
"discussed in the material on [optimization\n",
|
||||
"methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## A simple classification problem"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"from sklearn import datasets, linear_model\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def generate_data():\n",
|
||||
" np.random.seed(0)\n",
|
||||
" X, y = datasets.make_moons(200, noise=0.20)\n",
|
||||
" return X, y\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def visualize(X, y, clf):\n",
|
||||
" plot_decision_boundary(lambda x: clf.predict(x), X, y)\n",
|
||||
"\n",
|
||||
"def plot_decision_boundary(pred_func, X, y):\n",
|
||||
" # Set min and max values and give it some padding\n",
|
||||
" x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\n",
|
||||
" y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n",
|
||||
" h = 0.01\n",
|
||||
" # Generate a grid of points with distance h between them\n",
|
||||
" xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n",
|
||||
" # Predict the function value for the whole gid\n",
|
||||
" Z = pred_func(np.c_[xx.ravel(), yy.ravel()])\n",
|
||||
" Z = Z.reshape(xx.shape)\n",
|
||||
" # Plot the contour and training examples\n",
|
||||
" plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n",
|
||||
" plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)\n",
|
||||
" plt.show()\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def classify(X, y):\n",
|
||||
" clf = linear_model.LogisticRegressionCV()\n",
|
||||
" clf.fit(X, y)\n",
|
||||
" return clf\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def main():\n",
|
||||
" X, y = generate_data()\n",
|
||||
" # visualize(X, y)\n",
|
||||
" clf = classify(X, y)\n",
|
||||
" visualize(X, y, clf)\n",
|
||||
"\n",
|
||||
"if __name__ == \"__main__\":\n",
|
||||
" main()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Cancer Data again now with Decision Trees and other Methods"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import numpy as np\n",
|
||||
"from sklearn.model_selection import train_test_split \n",
|
||||
"from sklearn.datasets import load_breast_cancer\n",
|
||||
"from sklearn.linear_model import LogisticRegression\n",
|
||||
"\n",
|
||||
"# Load the data\n",
|
||||
"cancer = load_breast_cancer()\n",
|
||||
"\n",
|
||||
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
|
||||
"print(X_train.shape)\n",
|
||||
"print(X_test.shape)\n",
|
||||
"# Logistic Regression\n",
|
||||
"logreg = LogisticRegression(solver='lbfgs')\n",
|
||||
"logreg.fit(X_train, y_train)\n",
|
||||
"print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
|
||||
"#now scale the data\n",
|
||||
"from sklearn.preprocessing import StandardScaler\n",
|
||||
"scaler = StandardScaler()\n",
|
||||
"scaler.fit(X_train)\n",
|
||||
"X_train_scaled = scaler.transform(X_train)\n",
|
||||
"X_test_scaled = scaler.transform(X_test)\n",
|
||||
"# Logistic Regression\n",
|
||||
"logreg.fit(X_train_scaled, y_train)\n",
|
||||
"print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Other measures in classification studies: Cancer Data again"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import numpy as np\n",
|
||||
"from sklearn.model_selection import train_test_split \n",
|
||||
"from sklearn.datasets import load_breast_cancer\n",
|
||||
"from sklearn.linear_model import LogisticRegression\n",
|
||||
"\n",
|
||||
"# Load the data\n",
|
||||
"cancer = load_breast_cancer()\n",
|
||||
"\n",
|
||||
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
|
||||
"print(X_train.shape)\n",
|
||||
"print(X_test.shape)\n",
|
||||
"# Logistic Regression\n",
|
||||
"logreg = LogisticRegression(solver='lbfgs')\n",
|
||||
"logreg.fit(X_train, y_train)\n",
|
||||
"print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
|
||||
"#now scale the data\n",
|
||||
"from sklearn.preprocessing import StandardScaler\n",
|
||||
"scaler = StandardScaler()\n",
|
||||
"scaler.fit(X_train)\n",
|
||||
"X_train_scaled = scaler.transform(X_train)\n",
|
||||
"X_test_scaled = scaler.transform(X_test)\n",
|
||||
"# Logistic Regression\n",
|
||||
"logreg.fit(X_train_scaled, y_train)\n",
|
||||
"print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"from sklearn.preprocessing import LabelEncoder\n",
|
||||
"from sklearn.model_selection import cross_validate\n",
|
||||
"#Cross validation\n",
|
||||
"accuracy = cross_validate(logreg,X_test_scaled,y_test,cv=10)['test_score']\n",
|
||||
"print(accuracy)\n",
|
||||
"print(\"Test set accuracy with Logistic Regression and scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"import scikitplot as skplt\n",
|
||||
"y_pred = logreg.predict(X_test_scaled)\n",
|
||||
"skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
|
||||
"plt.show()\n",
|
||||
"y_probas = logreg.predict_proba(X_test_scaled)\n",
|
||||
"skplt.metrics.plot_roc(y_test, y_probas)\n",
|
||||
"plt.show()\n",
|
||||
"skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
|
||||
"plt.show()"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.6.8"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,892 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"<!-- dom:TITLE: Week 42 Convolutional and Recurrent Neural Networks and Autoencoders -->\n",
|
||||
"# Week 42 Convolutional and Recurrent Neural Networks and Autoencoders\n",
|
||||
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
|
||||
"<!-- Author: --> \n",
|
||||
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
|
||||
"\n",
|
||||
"Date: **Oct 15, 2020**\n",
|
||||
"\n",
|
||||
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Plan for week 42\n",
|
||||
"\n",
|
||||
"* Thursday: Convolutional Neural Networks and examples\n",
|
||||
"\n",
|
||||
"* Friday: Recurrent Neural Networks and Autoencoders\n",
|
||||
"\n",
|
||||
"Reading suggestions for both days: [Aurelien Geron's chapters 13 and 14](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf). Autoencoders are discussed in chapter 15 of Geron's text.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Convolutional Neural Networks (recognizing images)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Convolutional neural networks (CNNs) were developed during the last\n",
|
||||
"decade of the previous century, with a focus on character recognition\n",
|
||||
"tasks. Nowadays, CNNs are a central element in the spectacular success\n",
|
||||
"of deep learning methods. The success in for example image\n",
|
||||
"classifications have made them a central tool for most machine\n",
|
||||
"learning practitioners.\n",
|
||||
"\n",
|
||||
"CNNs are very similar to ordinary Neural Networks.\n",
|
||||
"They are made up of neurons that have learnable weights and\n",
|
||||
"biases. Each neuron receives some inputs, performs a dot product and\n",
|
||||
"optionally follows it with a non-linearity. The whole network still\n",
|
||||
"expresses a single differentiable score function: from the raw image\n",
|
||||
"pixels on one end to class scores at the other. And they still have a\n",
|
||||
"loss function (for example Softmax) on the last (fully-connected) layer\n",
|
||||
"and all the tips/tricks we developed for learning regular Neural\n",
|
||||
"Networks still apply (back propagation, gradient descent etc etc).\n",
|
||||
"\n",
|
||||
"What is the difference? **CNN architectures make the explicit assumption that\n",
|
||||
"the inputs are images, which allows us to encode certain properties\n",
|
||||
"into the architecture. These then make the forward function more\n",
|
||||
"efficient to implement and vastly reduce the amount of parameters in\n",
|
||||
"the network.**\n",
|
||||
"\n",
|
||||
"Here we provide only a superficial overview, for the more interested, we recommend highly the course\n",
|
||||
"[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
|
||||
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).\n",
|
||||
"\n",
|
||||
"Another good read is the article here <https://arxiv.org/pdf/1603.07285.pdf>. \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Neural Networks vs CNNs\n",
|
||||
"\n",
|
||||
"Neural networks are defined as **affine transformations**, that is \n",
|
||||
"a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an\n",
|
||||
"output (to which a bias vector is usually added before passing the result\n",
|
||||
"through a nonlinear activation function). This is applicable to any type of input, be it an\n",
|
||||
"image, a sound clip or an unordered collection of features: whatever their\n",
|
||||
"dimensionality, their representation can always be flattened into a vector\n",
|
||||
"before the transformation.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Why CNNS for images, sound files, medical images from CT scans etc?\n",
|
||||
"\n",
|
||||
"However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic\n",
|
||||
"structure. More formally, they share these important properties:\n",
|
||||
"* They are stored as multi-dimensional arrays (think of the pixels of a figure) .\n",
|
||||
"\n",
|
||||
"* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).\n",
|
||||
"\n",
|
||||
"* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).\n",
|
||||
"\n",
|
||||
"These properties are not exploited when an affine transformation is applied; in\n",
|
||||
"fact, all the axes are treated in the same way and the topological information\n",
|
||||
"is not taken into account. Still, taking advantage of the implicit structure of\n",
|
||||
"the data may prove very handy in solving some tasks, like computer vision and\n",
|
||||
"speech recognition, and in these cases it would be best to preserve it. This is\n",
|
||||
"where discrete convolutions come into play.\n",
|
||||
"\n",
|
||||
"A discrete convolution is a linear transformation that preserves this notion of\n",
|
||||
"ordering. It is sparse (only a few input units contribute to a given output\n",
|
||||
"unit) and reuses parameters (the same weights are applied to multiple locations\n",
|
||||
"in the input).\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Regular NNs don’t scale well to full images\n",
|
||||
"\n",
|
||||
"As an example, consider\n",
|
||||
"an image of size $32\\times 32\\times 3$ (32 wide, 32 high, 3 color channels), so a\n",
|
||||
"single fully-connected neuron in a first hidden layer of a regular\n",
|
||||
"Neural Network would have $32\\times 32\\times 3 = 3072$ weights. This amount still\n",
|
||||
"seems manageable, but clearly this fully-connected structure does not\n",
|
||||
"scale to larger images. For example, an image of more respectable\n",
|
||||
"size, say $200\\times 200\\times 3$, would lead to neurons that have \n",
|
||||
"$200\\times 200\\times 3 = 120,000$ weights. \n",
|
||||
"\n",
|
||||
"We could have\n",
|
||||
"several such neurons, and the parameters would add up quickly! Clearly,\n",
|
||||
"this full connectivity is wasteful and the huge number of parameters\n",
|
||||
"would quickly lead to possible overfitting.\n",
|
||||
"\n",
|
||||
"<!-- dom:FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network. -->\n",
|
||||
"<!-- begin figure -->\n",
|
||||
"\n",
|
||||
"<p>A regular 3-layer Neural Network.</p>\n",
|
||||
"<img src=\"figslides/nn.jpeg\" width=500>\n",
|
||||
"\n",
|
||||
"<!-- end figure -->\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## 3D volumes of neurons\n",
|
||||
"\n",
|
||||
"Convolutional Neural Networks take advantage of the fact that the\n",
|
||||
"input consists of images and they constrain the architecture in a more\n",
|
||||
"sensible way. \n",
|
||||
"\n",
|
||||
"In particular, unlike a regular Neural Network, the\n",
|
||||
"layers of a CNN have neurons arranged in 3 dimensions: width,\n",
|
||||
"height, depth. (Note that the word depth here refers to the third\n",
|
||||
"dimension of an activation volume, not to the depth of a full Neural\n",
|
||||
"Network, which can refer to the total number of layers in a network.)\n",
|
||||
"\n",
|
||||
"To understand it better, the above example of an image \n",
|
||||
"with an input volume of\n",
|
||||
"activations has dimensions $32\\times 32\\times 3$ (width, height,\n",
|
||||
"depth respectively). \n",
|
||||
"\n",
|
||||
"The neurons in a layer will\n",
|
||||
"only be connected to a small region of the layer before it, instead of\n",
|
||||
"all of the neurons in a fully-connected manner. Moreover, the final\n",
|
||||
"output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n",
|
||||
"because by the\n",
|
||||
"end of the CNN architecture we will reduce the full image into a\n",
|
||||
"single vector of class scores, arranged along the depth\n",
|
||||
"dimension. \n",
|
||||
"\n",
|
||||
"<!-- dom:FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). -->\n",
|
||||
"<!-- begin figure -->\n",
|
||||
"\n",
|
||||
"<p>A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).</p>\n",
|
||||
"<img src=\"figslides/cnn.jpeg\" width=500>\n",
|
||||
"\n",
|
||||
"<!-- end figure -->\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"<!-- !split -->\n",
|
||||
"## Layers used to build CNNs\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"A simple CNN is a sequence of layers, and every layer of a CNN\n",
|
||||
"transforms one volume of activations to another through a\n",
|
||||
"differentiable function. We use three main types of layers to build\n",
|
||||
"CNN architectures: Convolutional Layer, Pooling Layer, and\n",
|
||||
"Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n",
|
||||
"will stack these layers to form a full CNN architecture.\n",
|
||||
"\n",
|
||||
"A simple CNN for image classification could have the architecture:\n",
|
||||
"\n",
|
||||
"* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n",
|
||||
"\n",
|
||||
"* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n",
|
||||
"\n",
|
||||
"* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n",
|
||||
"\n",
|
||||
"* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n",
|
||||
"\n",
|
||||
"* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.\n",
|
||||
"\n",
|
||||
"## Transforming images\n",
|
||||
"\n",
|
||||
"CNNs transform the original image layer by layer from the original\n",
|
||||
"pixel values to the final class scores. \n",
|
||||
"\n",
|
||||
"Observe that some layers contain\n",
|
||||
"parameters and other don’t. In particular, the CNN layers perform\n",
|
||||
"transformations that are a function of not only the activations in the\n",
|
||||
"input volume, but also of the parameters (the weights and biases of\n",
|
||||
"the neurons). On the other hand, the RELU/POOL layers will implement a\n",
|
||||
"fixed function. The parameters in the CONV/FC layers will be trained\n",
|
||||
"with gradient descent so that the class scores that the CNN computes\n",
|
||||
"are consistent with the labels in the training set for each image.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## CNNs in brief\n",
|
||||
"\n",
|
||||
"In summary:\n",
|
||||
"\n",
|
||||
"* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n",
|
||||
"\n",
|
||||
"* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n",
|
||||
"\n",
|
||||
"* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n",
|
||||
"\n",
|
||||
"* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n",
|
||||
"\n",
|
||||
"* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n",
|
||||
"\n",
|
||||
"For more material on convolutional networks, we strongly recommend\n",
|
||||
"the course\n",
|
||||
"[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
|
||||
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"As discussed above, CNNs are neural networks built from the assumption that the inputs\n",
|
||||
"to the network are 2D images. This is important because the number of features or pixels in images\n",
|
||||
"grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n",
|
||||
"\n",
|
||||
"As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n",
|
||||
"are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n",
|
||||
"In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n",
|
||||
"matrices, typically 1 for each color dimension (Red, Green, Blue). \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Setting it up\n",
|
||||
"\n",
|
||||
"It means that to represent the entire\n",
|
||||
"dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## The MNIST dataset again\n",
|
||||
"\n",
|
||||
"The MNIST dataset consists of grayscale images with a pixel size of\n",
|
||||
"$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n",
|
||||
"neuron in the first hidden layer.\n",
|
||||
"\n",
|
||||
"If we were to analyze images of size $128\\times 128$ we would require\n",
|
||||
"$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n",
|
||||
"dealing with color images, as most images are, we have an image matrix\n",
|
||||
"of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n",
|
||||
"meaning 3 times the number of weights $= 49152$ are required for every\n",
|
||||
"single neuron in the first hidden layer.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Strong correlations\n",
|
||||
"\n",
|
||||
"Images typically have strong local correlations, meaning that a small\n",
|
||||
"part of the image varies little from its neighboring regions. If for\n",
|
||||
"example we have an image of a blue car, we can roughly assume that a\n",
|
||||
"small blue part of the image is surrounded by other blue regions.\n",
|
||||
"\n",
|
||||
"Therefore, instead of connecting every single pixel to a neuron in the\n",
|
||||
"first hidden layer, as we have previously done with deep neural\n",
|
||||
"networks, we can instead connect each neuron to a small part of the\n",
|
||||
"image (in all 3 RGB depth dimensions). The size of each small area is\n",
|
||||
"fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"<!-- !split -->\n",
|
||||
"## Layers of a CNN\n",
|
||||
"The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n",
|
||||
"The input image is typically a square matrix of depth 3. \n",
|
||||
"\n",
|
||||
"A **convolution** is performed on the image which outputs\n",
|
||||
"a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Each filter slides along the input image, taking the dot product\n",
|
||||
"between each small part of the image and the filter, in all depth\n",
|
||||
"dimensions. This is then passed through a non-linear function,\n",
|
||||
"typically the **Rectified Linear (ReLu)** function, which serves as the\n",
|
||||
"activation of the neurons in the first convolutional layer. This is\n",
|
||||
"further passed through a **pooling layer**, which reduces the size of the\n",
|
||||
"convolutional layer, e.g. by taking the maximum or average across some\n",
|
||||
"small regions, and this serves as input to the next convolutional\n",
|
||||
"layer.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Systematic reduction\n",
|
||||
"\n",
|
||||
"By systematically reducing the size of the input volume, through\n",
|
||||
"convolution and pooling, the network should create representations of\n",
|
||||
"small parts of the input, and then from them assemble representations\n",
|
||||
"of larger areas. The final pooling layer is flattened to serve as\n",
|
||||
"input to a hidden layer, such that each neuron in the final pooling\n",
|
||||
"layer is connected to every single neuron in the hidden layer. This\n",
|
||||
"then serves as input to the output layer, e.g. a softmax output for\n",
|
||||
"classification.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Prerequisites: Collect and pre-process data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%matplotlib inline\n",
|
||||
"\n",
|
||||
"# import necessary packages\n",
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"from sklearn import datasets\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# ensure the same random numbers appear every time\n",
|
||||
"np.random.seed(0)\n",
|
||||
"\n",
|
||||
"# display images in notebook\n",
|
||||
"%matplotlib inline\n",
|
||||
"plt.rcParams['figure.figsize'] = (12,12)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# download MNIST dataset\n",
|
||||
"digits = datasets.load_digits()\n",
|
||||
"\n",
|
||||
"# define inputs and labels\n",
|
||||
"inputs = digits.images\n",
|
||||
"labels = digits.target\n",
|
||||
"\n",
|
||||
"# RGB images have a depth of 3\n",
|
||||
"# our images are grayscale so they should have a depth of 1\n",
|
||||
"inputs = inputs[:,:,:,np.newaxis]\n",
|
||||
"\n",
|
||||
"print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n",
|
||||
"print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# choose some random images to display\n",
|
||||
"n_inputs = len(inputs)\n",
|
||||
"indices = np.arange(n_inputs)\n",
|
||||
"random_indices = np.random.choice(indices, size=5)\n",
|
||||
"\n",
|
||||
"for i, image in enumerate(digits.images[random_indices]):\n",
|
||||
" plt.subplot(1, 5, i+1)\n",
|
||||
" plt.axis('off')\n",
|
||||
" plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n",
|
||||
" plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Importing Keras and Tensorflow"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from tensorflow.keras import datasets, layers, models\n",
|
||||
"from tensorflow.keras.layers import Input\n",
|
||||
"from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n",
|
||||
"from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n",
|
||||
"from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n",
|
||||
"from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n",
|
||||
"from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n",
|
||||
"#from tensorflow.keras import Conv2D\n",
|
||||
"#from tensorflow.keras import MaxPooling2D\n",
|
||||
"#from tensorflow.keras import Flatten\n",
|
||||
"\n",
|
||||
"from sklearn.model_selection import train_test_split\n",
|
||||
"\n",
|
||||
"# representation of labels\n",
|
||||
"labels = to_categorical(labels)\n",
|
||||
"\n",
|
||||
"# split into train and test data\n",
|
||||
"# one-liner from scikit-learn library\n",
|
||||
"train_size = 0.8\n",
|
||||
"test_size = 1 - train_size\n",
|
||||
"X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n",
|
||||
" test_size=test_size)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"<!-- !split -->\n",
|
||||
"## Running with Keras"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
|
||||
" n_filters, n_neurons_connected, n_categories,\n",
|
||||
" eta, lmbd):\n",
|
||||
" model = Sequential()\n",
|
||||
" model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n",
|
||||
" activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
|
||||
" model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n",
|
||||
" model.add(layers.Flatten())\n",
|
||||
" model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n",
|
||||
" model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n",
|
||||
" \n",
|
||||
" sgd = optimizers.SGD(lr=eta)\n",
|
||||
" model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
|
||||
" \n",
|
||||
" return model\n",
|
||||
"\n",
|
||||
"epochs = 100\n",
|
||||
"batch_size = 100\n",
|
||||
"input_shape = X_train.shape[1:4]\n",
|
||||
"receptive_field = 3\n",
|
||||
"n_filters = 10\n",
|
||||
"n_neurons_connected = 50\n",
|
||||
"n_categories = 10\n",
|
||||
"\n",
|
||||
"eta_vals = np.logspace(-5, 1, 7)\n",
|
||||
"lmbd_vals = np.logspace(-5, 1, 7)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Final part"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
|
||||
" \n",
|
||||
"for i, eta in enumerate(eta_vals):\n",
|
||||
" for j, lmbd in enumerate(lmbd_vals):\n",
|
||||
" CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
|
||||
" n_filters, n_neurons_connected, n_categories,\n",
|
||||
" eta, lmbd)\n",
|
||||
" CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n",
|
||||
" scores = CNN.evaluate(X_test, Y_test)\n",
|
||||
" \n",
|
||||
" CNN_keras[i][j] = CNN\n",
|
||||
" \n",
|
||||
" print(\"Learning rate = \", eta)\n",
|
||||
" print(\"Lambda = \", lmbd)\n",
|
||||
" print(\"Test accuracy: %.3f\" % scores[1])\n",
|
||||
" print()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Final visualization"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# visual representation of grid search\n",
|
||||
"# uses seaborn heatmap, could probably do this in matplotlib\n",
|
||||
"import seaborn as sns\n",
|
||||
"\n",
|
||||
"sns.set()\n",
|
||||
"\n",
|
||||
"train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
|
||||
"test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
|
||||
"\n",
|
||||
"for i in range(len(eta_vals)):\n",
|
||||
" for j in range(len(lmbd_vals)):\n",
|
||||
" CNN = CNN_keras[i][j]\n",
|
||||
"\n",
|
||||
" train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n",
|
||||
" test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n",
|
||||
"\n",
|
||||
" \n",
|
||||
"fig, ax = plt.subplots(figsize = (10, 10))\n",
|
||||
"sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
|
||||
"ax.set_title(\"Training Accuracy\")\n",
|
||||
"ax.set_ylabel(\"$\\eta$\")\n",
|
||||
"ax.set_xlabel(\"$\\lambda$\")\n",
|
||||
"plt.show()\n",
|
||||
"\n",
|
||||
"fig, ax = plt.subplots(figsize = (10, 10))\n",
|
||||
"sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
|
||||
"ax.set_title(\"Test Accuracy\")\n",
|
||||
"ax.set_ylabel(\"$\\eta$\")\n",
|
||||
"ax.set_xlabel(\"$\\lambda$\")\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## The CIFAR01 data set\n",
|
||||
"\n",
|
||||
"The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n",
|
||||
"6,000 images in each class. The dataset is divided into 50,000\n",
|
||||
"training images and 10,000 testing images. The classes are mutually\n",
|
||||
"exclusive and there is no overlap between them."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import tensorflow as tf\n",
|
||||
"\n",
|
||||
"from tensorflow.keras import datasets, layers, models\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"\n",
|
||||
"# We import the data set\n",
|
||||
"(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n",
|
||||
"\n",
|
||||
"# Normalize pixel values to be between 0 and 1 by dividing by 255. \n",
|
||||
"train_images, test_images = train_images / 255.0, test_images / 255.0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Verifying the data set\n",
|
||||
"\n",
|
||||
"To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n",
|
||||
" 'dog', 'frog', 'horse', 'ship', 'truck']\n",
|
||||
"\n",
|
||||
"plt.figure(figsize=(10,10))\n",
|
||||
"for i in range(25):\n",
|
||||
" plt.subplot(5,5,i+1)\n",
|
||||
" plt.xticks([])\n",
|
||||
" plt.yticks([])\n",
|
||||
" plt.grid(False)\n",
|
||||
" plt.imshow(train_images[i], cmap=plt.cm.binary)\n",
|
||||
" # The CIFAR labels happen to be arrays, \n",
|
||||
" # which is why you need the extra index\n",
|
||||
" plt.xlabel(class_names[train_labels[i][0]])\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Set up the model\n",
|
||||
"\n",
|
||||
"The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n",
|
||||
"\n",
|
||||
"As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"model = models.Sequential()\n",
|
||||
"model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n",
|
||||
"model.add(layers.MaxPooling2D((2, 2)))\n",
|
||||
"model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
|
||||
"model.add(layers.MaxPooling2D((2, 2)))\n",
|
||||
"model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
|
||||
"\n",
|
||||
"# Let's display the architecture of our model so far.\n",
|
||||
"\n",
|
||||
"model.summary()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Add Dense layers on top\n",
|
||||
"\n",
|
||||
"To complete our model, you will feed the last output tensor from the\n",
|
||||
"convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n",
|
||||
"to perform classification. Dense layers take vectors as input (which\n",
|
||||
"are 1D), while the current output is a 3D tensor. First, you will\n",
|
||||
"flatten (or unroll) the 3D output to 1D, then add one or more Dense\n",
|
||||
"layers on top. CIFAR has 10 output classes, so you use a final Dense\n",
|
||||
"layer with 10 outputs and a softmax activation."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"model.add(layers.Flatten())\n",
|
||||
"model.add(layers.Dense(64, activation='relu'))\n",
|
||||
"model.add(layers.Dense(10))\n",
|
||||
"Here's the complete architecture of our model.\n",
|
||||
"\n",
|
||||
"model.summary()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.\n",
|
||||
"\n",
|
||||
"## Compile and train the model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"model.compile(optimizer='adam',\n",
|
||||
" loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
|
||||
" metrics=['accuracy'])\n",
|
||||
"\n",
|
||||
"history = model.fit(train_images, train_labels, epochs=10, \n",
|
||||
" validation_data=(test_images, test_labels))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Finally, evaluate the model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"plt.plot(history.history['accuracy'], label='accuracy')\n",
|
||||
"plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n",
|
||||
"plt.xlabel('Epoch')\n",
|
||||
"plt.ylabel('Accuracy')\n",
|
||||
"plt.ylim([0.5, 1])\n",
|
||||
"plt.legend(loc='lower right')\n",
|
||||
"\n",
|
||||
"test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n",
|
||||
"\n",
|
||||
"print(test_acc)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Recurrent neural networks: Overarching view\n",
|
||||
"\n",
|
||||
"Till now our focus has been, including convolutional neural networks\n",
|
||||
"as well, on feedforward neural networks. The output or the activations\n",
|
||||
"flow only in one direction, from the input layer to the output layer.\n",
|
||||
"\n",
|
||||
"A recurrent neural network (RNN) looks very much like a feedforward\n",
|
||||
"neural network, except that it also has connections pointing\n",
|
||||
"backward. \n",
|
||||
"\n",
|
||||
"RNNs are used to analyze time series data such as stock prices, and\n",
|
||||
"tell you when to buy or sell. In autonomous driving systems, they can\n",
|
||||
"anticipate car trajectories and help avoid accidents. More generally,\n",
|
||||
"they can work on sequences of arbitrary lengths, rather than on\n",
|
||||
"fixed-sized inputs like all the nets we have discussed so far. For\n",
|
||||
"example, they can take sentences, documents, or audio samples as\n",
|
||||
"input, making them extremely useful for natural language processing\n",
|
||||
"systems such as automatic translation and speech-to-text.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## A simple example"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start importing packages\n",
|
||||
"import pandas as pd\n",
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import tensorflow as tf\n",
|
||||
"from tensorflow.keras import datasets, layers, models\n",
|
||||
"from tensorflow.keras.layers import Input\n",
|
||||
"from tensorflow.keras.models import Model, Sequential \n",
|
||||
"from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
|
||||
"from tensorflow.keras import optimizers \n",
|
||||
"from tensorflow.keras import regularizers \n",
|
||||
"from tensorflow.keras.utils import to_categorical \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# convert into dataset matrix\n",
|
||||
"def convertToMatrix(data, step):\n",
|
||||
" X, Y =[], []\n",
|
||||
" for i in range(len(data)-step):\n",
|
||||
" d=i+step \n",
|
||||
" X.append(data[i:d,])\n",
|
||||
" Y.append(data[d,])\n",
|
||||
" return np.array(X), np.array(Y)\n",
|
||||
"\n",
|
||||
"step = 4\n",
|
||||
"N = 1000 \n",
|
||||
"Tp = 800 \n",
|
||||
"\n",
|
||||
"t=np.arange(0,N)\n",
|
||||
"x=np.sin(0.02*t)+2*np.random.rand(N)\n",
|
||||
"df = pd.DataFrame(x)\n",
|
||||
"df.head()\n",
|
||||
"\n",
|
||||
"plt.plot(df)\n",
|
||||
"plt.show()\n",
|
||||
"\n",
|
||||
"values=df.values\n",
|
||||
"train,test = values[0:Tp,:], values[Tp:N,:]\n",
|
||||
"\n",
|
||||
"# add step elements into train and test\n",
|
||||
"test = np.append(test,np.repeat(test[-1,],step))\n",
|
||||
"train = np.append(train,np.repeat(train[-1,],step))\n",
|
||||
" \n",
|
||||
"trainX,trainY =convertToMatrix(train,step)\n",
|
||||
"testX,testY =convertToMatrix(test,step)\n",
|
||||
"trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n",
|
||||
"testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n",
|
||||
"\n",
|
||||
"model = Sequential()\n",
|
||||
"model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n",
|
||||
"model.add(Dense(8, activation=\"relu\")) \n",
|
||||
"model.add(Dense(1))\n",
|
||||
"model.compile(loss='mean_squared_error', optimizer='rmsprop')\n",
|
||||
"model.summary()\n",
|
||||
"\n",
|
||||
"model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n",
|
||||
"trainPredict = model.predict(trainX)\n",
|
||||
"testPredict= model.predict(testX)\n",
|
||||
"predicted=np.concatenate((trainPredict,testPredict),axis=0)\n",
|
||||
"\n",
|
||||
"trainScore = model.evaluate(trainX, trainY, verbose=0)\n",
|
||||
"print(trainScore)\n",
|
||||
"\n",
|
||||
"index = df.index.values\n",
|
||||
"plt.plot(index,df)\n",
|
||||
"plt.plot(index,predicted)\n",
|
||||
"plt.axvline(df.index[Tp], c=\"r\")\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Set up of an RNN\n",
|
||||
"\n",
|
||||
"The figure here displays a simple example of an RNN, with inputs $x_t$\n",
|
||||
"at a given time $t$ and outputs $y_t$. Introducing time as a variable\n",
|
||||
"offers an intutitive way of understanding these networks. In addition\n",
|
||||
"to the inputs $x_t$, the layer at a time $t$ receives also as input\n",
|
||||
"the output from the previous layer $t-1$, that is $y_{t1}$.\n",
|
||||
"\n",
|
||||
"This means also that we need to have weights that link both the inputs\n",
|
||||
"$x_t$ to the outputs $y_t$ as well as weights that link the output\n",
|
||||
"from the previous time $y_{t-1}$ and $y_t$. The figure here shows an\n",
|
||||
"example of a simple RNN.\n",
|
||||
"\n",
|
||||
"More material will be added here.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Solving differential equations and eigenvalue problems with RNNs\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"In our discussions of ordinary differential equations and partial\n",
|
||||
"differential equations using neural networks. Here we will discuss how\n",
|
||||
"we can solve say ordinary differential equations and eigenvalue\n",
|
||||
"problems using RNNs. Eigenvalue problems can be solved using RNNs by\n",
|
||||
"rewriting such a problems as a non-linear differential equation.\n",
|
||||
"\n",
|
||||
"Instead of starting with a well-known ordinary differential equation,\n",
|
||||
"we start directly with an eigenvaule problem.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Long-Short Time Memory\n",
|
||||
"\n",
|
||||
"Discussions about dynamic unrolling through time. discuss memory cells, input and output\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Autoencoders: Overarching view\n",
|
||||
"\n",
|
||||
"Autoencoders are artificial neural networks capable of learning\n",
|
||||
"efficient representations of the input data (these representations are called codings) without\n",
|
||||
"any supervision (i.e., the training set is unlabeled). These codings\n",
|
||||
"typically have a much lower dimensionality than the input data, making\n",
|
||||
"autoencoders useful for dimensionality reduction. \n",
|
||||
"\n",
|
||||
"More importantly, autoencoders act as powerful feature detectors, and\n",
|
||||
"they can be used for unsupervised pretraining of deep neural networks.\n",
|
||||
"\n",
|
||||
"Lastly, they are capable of randomly generating new data that looks\n",
|
||||
"very similar to the training data; this is called a generative\n",
|
||||
"model. For example, you could train an autoencoder on pictures of\n",
|
||||
"faces, and it would then be able to generate new faces. Surprisingly,\n",
|
||||
"autoencoders work by simply learning to copy their inputs to their\n",
|
||||
"outputs. This may sound like a trivial task, but we will see that\n",
|
||||
"constraining the network in various ways can make it rather\n",
|
||||
"difficult. For example, you can limit the size of the internal\n",
|
||||
"representation, or you can add noise to the inputs and train the\n",
|
||||
"network to recover the original inputs. These constraints prevent the\n",
|
||||
"autoencoder from trivially copying the inputs directly to the outputs,\n",
|
||||
"which forces it to learn efficient ways of representing the data. In\n",
|
||||
"short, the codings are byproducts of the autoencoder’s attempt to\n",
|
||||
"learn the identity function under some constraints.\n",
|
||||
"\n",
|
||||
"## Simple examples of Autoencoders"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.6.8"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
-3.077640548999999864e-02
|
||||
-8.336233265999999642e-02
|
||||
-1.446729566999999939e-01
|
||||
-2.116753731999999888e-01
|
||||
-2.830637391999999974e-01
|
||||
-3.581341341000000011e-01
|
||||
-4.364624349999999819e-01
|
||||
-5.177783846000000301e-01
|
||||
-6.019067271000000385e-01
|
||||
-6.887363571000000295e-01
|
||||
-7.782028951999999666e-01
|
||||
-8.702784033999999558e-01
|
||||
-9.657189846038818359e-01
|
||||
-1.063057661056518555e+00
|
||||
-1.162679433822631836e+00
|
||||
-1.263875484466552734e+00
|
||||
-1.366456151008605957e+00
|
||||
-1.469873309135437012e+00
|
||||
-1.573707580566406250e+00
|
||||
-1.677412390708923340e+00
|
||||
|
File diff suppressed because one or more lines are too long
Vendored
BIN
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,45 @@
|
||||
digraph Tree {
|
||||
node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ;
|
||||
edge [fontname=helvetica] ;
|
||||
0 [label="X[1] <= 0.115\ngini = 0.5\nsamples = 75\nvalue = [37, 38]", fillcolor="#fafcfe"] ;
|
||||
1 [label="X[0] <= -0.686\ngini = 0.225\nsamples = 31\nvalue = [4, 27]", fillcolor="#56ace9"] ;
|
||||
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
|
||||
2 [label="gini = 0.0\nsamples = 2\nvalue = [2, 0]", fillcolor="#e58139"] ;
|
||||
1 -> 2 ;
|
||||
3 [label="X[1] <= 0.058\ngini = 0.128\nsamples = 29\nvalue = [2, 27]", fillcolor="#48a4e7"] ;
|
||||
1 -> 3 ;
|
||||
4 [label="X[0] <= 1.207\ngini = 0.077\nsamples = 25\nvalue = [1, 24]", fillcolor="#41a1e6"] ;
|
||||
3 -> 4 ;
|
||||
5 [label="gini = 0.0\nsamples = 17\nvalue = [0, 17]", fillcolor="#399de5"] ;
|
||||
4 -> 5 ;
|
||||
6 [label="X[1] <= -0.43\ngini = 0.219\nsamples = 8\nvalue = [1, 7]", fillcolor="#55abe9"] ;
|
||||
4 -> 6 ;
|
||||
7 [label="gini = 0.0\nsamples = 1\nvalue = [1, 0]", fillcolor="#e58139"] ;
|
||||
6 -> 7 ;
|
||||
8 [label="gini = 0.0\nsamples = 7\nvalue = [0, 7]", fillcolor="#399de5"] ;
|
||||
6 -> 8 ;
|
||||
9 [label="X[1] <= 0.09\ngini = 0.375\nsamples = 4\nvalue = [1, 3]", fillcolor="#7bbeee"] ;
|
||||
3 -> 9 ;
|
||||
10 [label="gini = 0.0\nsamples = 1\nvalue = [1, 0]", fillcolor="#e58139"] ;
|
||||
9 -> 10 ;
|
||||
11 [label="gini = 0.0\nsamples = 3\nvalue = [0, 3]", fillcolor="#399de5"] ;
|
||||
9 -> 11 ;
|
||||
12 [label="X[0] <= 1.36\ngini = 0.375\nsamples = 44\nvalue = [33, 11]", fillcolor="#eeab7b"] ;
|
||||
0 -> 12 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
|
||||
13 [label="X[0] <= -0.189\ngini = 0.26\nsamples = 39\nvalue = [33, 6]", fillcolor="#ea985d"] ;
|
||||
12 -> 13 ;
|
||||
14 [label="gini = 0.0\nsamples = 18\nvalue = [18, 0]", fillcolor="#e58139"] ;
|
||||
13 -> 14 ;
|
||||
15 [label="X[0] <= 0.479\ngini = 0.408\nsamples = 21\nvalue = [15, 6]", fillcolor="#efb388"] ;
|
||||
13 -> 15 ;
|
||||
16 [label="X[1] <= 0.781\ngini = 0.5\nsamples = 12\nvalue = [6, 6]", fillcolor="#ffffff"] ;
|
||||
15 -> 16 ;
|
||||
17 [label="gini = 0.0\nsamples = 6\nvalue = [0, 6]", fillcolor="#399de5"] ;
|
||||
16 -> 17 ;
|
||||
18 [label="gini = 0.0\nsamples = 6\nvalue = [6, 0]", fillcolor="#e58139"] ;
|
||||
16 -> 18 ;
|
||||
19 [label="gini = 0.0\nsamples = 9\nvalue = [9, 0]", fillcolor="#e58139"] ;
|
||||
15 -> 19 ;
|
||||
20 [label="gini = 0.0\nsamples = 5\nvalue = [0, 5]", fillcolor="#399de5"] ;
|
||||
12 -> 20 ;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user