added files

This commit is contained in:
mhjensen
2020-12-18 07:00:56 +01:00
parent 5a4824462a
commit cd09587f60
261 changed files with 148731 additions and 26854 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
# Sphinx build info version 1
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
config: fdb4c65fe6fdd143bcbae649c1ee1a55
config: 29159f964fb7395f0e429ef40b5eaa8d
tags: 645f666f9bcd5a90fca523b33c5a78b7
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,583 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Logistic Regression\n",
"\n",
"## Introduction\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",
"\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",
"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",
"\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": [
"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",
"\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",
"\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",
"\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": {
"collapsed": false
},
"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": [
"## 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": [
"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",
"\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": [
"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": [
"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",
"\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)."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,224 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction\n",
"\n",
"Classical mechanics is a topic which has been taught intensively over\n",
"several centuries. It is, with its many variants and ways of\n",
"presenting the educational material, normally the first **real** physics\n",
"course many of us meet and it lays the foundation for further physics\n",
"studies. Many of the equations and ways of reasoning about the\n",
"underlying laws of motion and pertinent forces, shape our approaches and understanding\n",
"of the scientific method and discourse, as well as the way we develop our insights\n",
"and deeper understanding about physical systems. \n",
"\n",
"There is a wealth of\n",
"well-tested (from both a physics point of view and a pedagogical\n",
"standpoint) exercises and problems which can be solved\n",
"analytically. However, many of these problems represent idealized and\n",
"less realistic situations. The large majority of these problems are\n",
"solved by paper and pencil and are traditionally aimed\n",
"at what we normally refer to as continuous models from which we may find an analytical solution. As a consequence,\n",
"when teaching mechanics, it implies that we can seldomly venture beyond an idealized case\n",
"in order to develop our understandings and insights about the\n",
"underlying forces and laws of motion.\n",
"\n",
"\n",
"On the other hand, numerical algorithms call for approximate discrete\n",
"models and much of the development of methods for continuous models\n",
"are nowadays being replaced by methods for discrete models in science and\n",
"industry, simply because **much larger classes of problems can be addressed** with discrete models, often by simpler and more\n",
"generic methodologies.\n",
"\n",
"As we will see below, when properly scaling the equations at hand,\n",
"discrete models open up for more advanced abstractions and the possibility to\n",
"study real life systems, with the added bonus that we can explore and\n",
"deepen our basic understanding of various physical systems\n",
"\n",
"Analytical solutions are as important as before. In addition, such\n",
"solutions provide us with invaluable benchmarks and tests for our\n",
"discrete models. Such benchmarks, as we will see below, allow us \n",
"to discuss possible sources of errors and their behaviors. And\n",
"finally, since most of our models are based on various algorithms from\n",
"numerical mathematics, we have a unique oppotunity to gain a deeper\n",
"understanding of the mathematical approaches we are using.\n",
"\n",
"\n",
"\n",
"With computing and data science as important elements in essentially\n",
"all aspects of a modern society, we could then try to define Computing as\n",
"**solving scientific problems using all possible tools, including\n",
"symbolic computing, computers and numerical algorithms, and analytical\n",
"paper and pencil solutions**. \n",
"Computing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.\n",
"\n",
"\n",
"The way we will teach this course reflects\n",
"this definition of computing. The course contains both classical paper\n",
"and pencil exercises as well as computational projects and exercises. The\n",
"hope is that this will allow you to explore the physics of systems\n",
"governed by the degrees of freedom of classical mechanics at a deeper\n",
"level, and that these insights about the scientific method will help\n",
"you to develop a better understanding of how the underlying forces and\n",
"equations of motion and how they impact a given system. Furthermore, by introducing various numerical methods\n",
"via computational projects and exercises, we aim at developing your competences and skills about these topics.\n",
"\n",
"\n",
"These competences will enable you to\n",
"\n",
"* understand how algorithms are used to solve mathematical problems,\n",
"\n",
"* derive, verify, and implement algorithms,\n",
"\n",
"* understand what can go wrong with algorithms,\n",
"\n",
"* use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and\n",
"\n",
"* think algorithmically for the purposes of gaining deeper insights about scientific problems.\n",
"\n",
"All these elements are central for maturing and gaining a better understanding of the modern scientific process *per se*.\n",
"\n",
"The power of the scientific method lies in identifying a given problem\n",
"as a special case of an abstract class of problems, identifying\n",
"general solution methods for this class of problems, and applying a\n",
"general method to the specific problem (applying means, in the case of\n",
"computing, calculations by pen and paper, symbolic computing, or\n",
"numerical computing by ready-made and/or self-written software). This\n",
"generic view on problems and methods is particularly important for\n",
"understanding how to apply available, generic software to solve a\n",
"particular problem.\n",
"\n",
"*However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.*\n",
"\n",
"\n",
"\n",
"## A well-known examples to illustrate many of the above concepts\n",
"\n",
"Before we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the\n",
"abovementioned topics using an example many of you may have seen before in for example CMSE201. \n",
"A simple algorithm for integration is the Trapezoidal rule. \n",
"Integration of a function $f(x)$ by the Trapezoidal Rule is given by following algorithm for an interval $x \\in [a,b]$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\int_a^b(f(x) dx = \\frac{1}{2}\\left [f(a)+2f(a+h)+\\dots+2f(b-h)+f(b)\\right] +O(h^2),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $h$ is the so-called stepsize defined by the number of integration points $N$ as $h=(b-a)/(n)$.\n",
"Python offers an extremely versatile programming environment, allowing for\n",
"the inclusion of analytical studies in a numerical program. Here we show an\n",
"example code with the **trapezoidal rule**. We use also **SymPy** to evaluate the exact value of the integral and compute the absolute error\n",
"with respect to the numerically evaluated one of the integral\n",
"$\\int_0^1 dx x^2 = 1/3$.\n",
"The following code for the trapezoidal rule allows you to plot the relative error by comparing with the exact result. By increasing to $10^8$ points one arrives at a region where numerical errors start to accumulate."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"from math import log10\n",
"import numpy as np\n",
"from sympy import Symbol, integrate\n",
"import matplotlib.pyplot as plt\n",
"# function for the trapezoidal rule\n",
"def Trapez(a,b,f,n):\n",
" h = (b-a)/float(n)\n",
" s = 0\n",
" x = a\n",
" for i in range(1,n,1):\n",
" x = x+h\n",
" s = s+ f(x)\n",
" s = 0.5*(f(a)+f(b)) +s\n",
" return h*s\n",
"# function to compute pi\n",
"def function(x):\n",
" return x*x\n",
"# define integration limits\n",
"a = 0.0; b = 1.0;\n",
"# find result from sympy\n",
"# define x as a symbol to be used by sympy\n",
"x = Symbol('x')\n",
"exact = integrate(function(x), (x, a, b))\n",
"# set up the arrays for plotting the relative error\n",
"n = np.zeros(9); y = np.zeros(9);\n",
"# find the relative error as function of integration points\n",
"for i in range(1, 8, 1):\n",
" npts = 10**i\n",
" result = Trapez(a,b,function,npts)\n",
" RelativeError = abs((exact-result)/exact)\n",
" n[i] = log10(npts); y[i] = log10(RelativeError);\n",
"plt.plot(n,y, 'ro')\n",
"plt.xlabel('n')\n",
"plt.ylabel('Relative error')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This example shows the potential of combining numerical algorithms with symbolic calculations, allowing us to \n",
"\n",
"* Validate and verify their algorithms. \n",
"\n",
"* Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.\n",
"\n",
"* Validation and verification are then included *naturally* and one can develop a better attitude to what is meant with an ethically sound scientific approach.\n",
"\n",
"* The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get **trained from day one to think error analysis**. \n",
"\n",
"* With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks. \n",
"\n",
"In this process we can easily bake in\n",
"1. How to structure a code in terms of functions\n",
"\n",
"2. How to make a module\n",
"\n",
"3. How to read input data flexibly from the command line\n",
"\n",
"4. How to create graphical/web user interfaces\n",
"\n",
"5. How to write unit tests (test functions or doctests)\n",
"\n",
"6. How to refactor code in terms of classes (instead of functions only)\n",
"\n",
"7. How to conduct and automate large-scale numerical experiments\n",
"\n",
"8. How to write scientific reports in various formats (LaTeX, HTML)\n",
"\n",
"The conventions and techniques outlined here will save you a lot of time when you incrementally extend software over time from simpler to more complicated problems. In particular, you will benefit from many good habits:\n",
"1. New code is added in a modular fashion to a library (modules)\n",
"\n",
"2. Programs are run through convenient user interfaces\n",
"\n",
"3. It takes one quick command to let all your code undergo heavy testing \n",
"\n",
"4. Tedious manual work with running programs is automated,\n",
"\n",
"5. Your scientific investigations are reproducible, scientific reports with top quality typesetting are produced both for paper and electronic devices."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,5 @@
Content in Jupyter Book
=======================
There are many ways to write content in Jupyter Book. This short section
covers a few tips for how to do so.
@@ -0,0 +1,180 @@
# PHY321, Classical Mechanics I, Michigan State University, Spring 2021
Here you will find a general overview of the course, with learning outcomes, teaching schedule etc.
## Teaching team, grading and other practicalities
| Lectures | | | Location |
|---------|----|----|----|
| Monday 3:00-3:50pm| Wednesday 3:00-3:50pm | Friday 3:00-3:50pm | Room 1420 BPS |
| Instructor | Email | Office | Office phone/cellphone |
|--------------|------|-----|----|
| _Morten Hjorth-Jensen_ https://github.com/mhjensen | hjensen@msu.edu | Office: NSCL/FRIB 2131 | 5179087290/5172491375/+47-48257387 |
| Office Hours| |
|----------|----------|
| Monday/Wednesday 4-5:00pm, Room 2131 NSCL/FRIB | or immediately after class |
| Homework Grader | Email |
|--------------|------|
| _Julie Butler_ | butler@frib.msu.edu |
| Office Hours Julie Butler |
|------------------|
| TBA | |
| Learning Assistant | Email |
|--------------|------|
| _Jeremy Rebenstock_ | |
| Office Hours TBA | |
|----------|----------|
| | |
| Additional Class | Location |
|---|----|
| Wednesday 5:00-6pm | Room 1400 BPS |
### Grading and dates
| Activity | Percentage of total score |
|------|-----|
|Homeworks, 9 in total and due Mondays the week after | 20% |
| First Midterm Project, due Wednesday March 11 | 25% |
| Second Midterm Project, due Friday April 17| 25% |
| Final Exam project, due May 1 | 30% |
| Extra Credit Assignment, hw10, (Due Friday April 24)| 10% |
| Grading scale | | | | | | |
|-----|-----|-------|------|--------|--------|--------|
| 4.0(90%)| 3.5(80%)| 3.0(70%)| 2.5(60%)| 2.0(50%)| 1.5(40%)| 1.0(30%)|
## Possible textbooks and lecture notes
_Recommended textbook_:
- JRT: John R. Taylor, Classical Mechanics (Univ. Sci. Books 2005), https://www.uscibooks.com/taylor2.htm, see also https://github.com/mhjensen/Physics321/tree/master/doc/Literature
_Additional textbooks_:
- AMS: Anders Malthe-Sørenssen, Elementary Mechanics using Python (Springer 2015), https://www.springer.com/gp/book/9783319195957 and https://github.com/mhjensen/Physics321/tree/master/doc/Literature
- _Lecture notes_: Posted lecture notes are in the doc/pub folder here or at https://mhjensen.github.io/Physics321/doc/web/course.html for easier viewing. They are not meant to be a replacement for textbook. These notes are updated on a weekly basis and a _git pull_ should thus always give you the latest update.
## Teaching schedule with links to material (This will be updated asap)
Weekly mails (Wednesdays or Thursdays) with updates, plans for lectures etc will sent to everybody. We use also Piazza as a discussion forum. Please use this sign-up link piazza.com/msu/spring2020/phy321. The class link is piazza.com/msu/spring2020/phy321/home
### Week 2, January 6-10, 2020
- Monday: Introduction to the course and start discussion of vectors, space, time and motion, JRT chapter 1.2 and lecture notes (https://mhjensen.github.io/Physics321/doc/pub/Introduction/html/Introduction.html)
- Wednesday: More on time,space, vectors and motion, JRT 1.2 and 1.3, AMS chapters 2 and 4 and lecture notes (https://mhjensen.github.io/Physics321/doc/pub/Introduction/html/Introduction.html), first homework available
- Friday: Forces and Newton's laws of motion. JRT chapter 1.4 and lecture notes (https://mhjensen.github.io/Physics321/doc/pub/Introduction/html/Introduction.html). Introduction to Git and GitHub and getting started with numerical exercises. Installing software (anaconda) and first homework due January 17. For solving exercise 7 in the first homework, AMS chapters 2 and 4 are very useful
- Solution to homeworks are in https://d2l.msu.edu/
### Week 3, January 13-17, 2020
- Monday: Motion and forces, Newton's laws, examples
- Wednesday: Motion and forces, Newton's laws, examples
- Friday: Motion and forces, Newton's laws, examples,2nd homework, due January 24
- Solution to homeworks are in https://d2l.msu.edu/
- Good reads are Taylor chapters 1.4, 1.5, 1.6, 2.1-2.4 and AMS chapters 4.2 and 5
### Week 4, January 20-24, 2020
- Monday: MLK day, no lectures
- Wednesday: Work and energy conservation
- Friday: Example of conservation laws and single-particle motion, 3rd homework, due January 31
- Good reads are Taylor chapters 4.1-.4.3 and AMS chapters 10-12.
### Week 5, January 27-31, 2020
- Monday: More on Conservation laws, momentum conservation
- Wednesday: Examples of applications of conservation laws, angular momentum conservation
- Friday: Conservation aws and further examples, 4th homework, due February 10
- Good reads are Taylor chapter 4 and AMS chapters 10-14.
### Week 6, February 3-7, 2020
- Monday: Conservation laws and discussion of 4th homework (exercises 6 and 7). Introducing the Velocity Verlet algorithm and the Earth Sun problem
- Wednesday: Examples of application of conservations laws (see chapter 4 of Taylor).
- Friday: Begin discussion of oscillations, and 5th homework, due February 17, paper and pencil can be handed in Friday the 21st at latest.
- Good reads are Taylor chapter 4 and AMS chapters 10-14 for the conservation laws and the first sections of chapter 5 of Taylor on oscillations.
### Week 7, February 10-14, 2020
- Monday: Oscillations, mathematical detials, the sliding block and energy conservation
- Wednesday: Oscillations, damped motion and more mathematical details
- Friday: Oscillations, resonances and more on damped motion, 6th homework, due February 24
- Good reads are chapter 5 of Taylor on oscillations.
### Week 8, February 17-21, 2020
- Monday: Oscillations, driven oscillations and resonances
- Wednesday: Oscillation examples and numerical integration
- Friday: Fourier series and end of oscillation chapter _First midterm project, available Friday Feb 21 and due March 11, 2020_
- Good reads are sections 5.5-5.8 of Taylor on oscillations.
### Week 9, February 24-28, 2020
- Monday: Fourier series and oscillations
- Wednesday: Discussiom of first midterm and wrap up of oscillations part
- Friday: No lecture!
- Good reads are chapter 8 of Taylor and Lecture notes
### Week 10, March 2-6, 2020, Spring break
- Monday: No lectures, spring break
- Wednesday: No lectures, spring break
- Friday: No lectures, spring break
### Week 11, March 9-13, 2020
- Monday: Gravity and central force problems, center of mass coordinates. Lecture notes and Taylor chapter 8. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch9.pdf
- Wednesday: Discussion of first midterm. First midterm due Friday 13
- Friday: Gravity and central force problems, centrifugal barriers. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch13.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_wk9trq9k
### Week 12, March 16-20, 2020
- Monday: Gravity and central force problems, elliptical orbits and Kepler's laws, 7th homework, due March 23. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch16.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_t1pocrww
- Wednesday: Gravity and central force problems, elliptical orbits and two-body scattering examples. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch18.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_i9hczn21
- Friday: Elliptical orbits, examples and two-body scattering problems. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch20.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_w9xc8az7
### Week 13, March 23-27, 2020
- Monday: Central force problems, summary and discussion of two-body scattering problems. 8th homework, due March 30. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch23.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_t2l86862
- Wednesday: Two-body scattering. Taylor chapter 14 covers parts of the material. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch25.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_d70czgce
- Friday: Two-body scattering (Taylor chapter 14). PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch27.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_e1cs5784
### Week 14, March 30-April 3, 2020
- Monday: Wrapping up two-body scattering and begin non-inertial frames. 9th homework, due April 6. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesMarch30.pdf and video of lecture https://mediaspace.msu.edu/media/t/0_tlsccwai
- Wednesday: Non-inertial frames, accelerating frames (Taylor sections 9.1-9.2). PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril1.pdf and video of lecture https://mediaspace.msu.edu/media/t/0_utc9il9y
- Friday: Rotating non-inertial frames and Coriolis force (Taylor sections 9.3-9.6). PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril3.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_2v439nza
### Week 15, April 6-10, 2020
- Monday: Rotating non-inertial frames, Coriolis force and Foucalt's pendulum (Taylor sections 9.7-9.9). Second midterm available, due Fryday April 17. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril6.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_utivxb87
- Wednesday: Variational calculus and the Euler-Lagrange equations, chapter 6 of Taylor and lecture notes. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril8.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_rz8vr2ht
- Friday: Euler-Lagrange equations and Lagrangian formalism. Taylor chapter 6 and lecture notes. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril10.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_j5ugthfg
### Week 16, April 13-17, 2020
- Monday: Langrangian formalism, discussion of examples. Taylor chapters 6 and 7. 10th homework and extra assignments, due April 24. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril13.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_hxxec3uc
- Wednesday: Lagrangian formalism, constraints and Lagrangian multipliers and examples. These topics are covered by Taylor's sections 7.1,7.2, 7.3, 7.4. Sections 7.5-7.7 contain several nice examples while section 7.8 goes through conservation laws. The lecture notes cover many of these topics as well. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril15.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_2v2se359
- Friday: Lagrangian Formalism, conservation laws and examples, from the classical pendulum to Foucault's pendulum. Taylor chapter 7 and lecture notes. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril17.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_ftgzt035
### Week 17, April 20-24, 2020
- Monday: Lagrangian formalism, conservation laws. Examples. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril20.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_b81t0tta
- Wednesday: Lagrangian formalim, examples such as the linear chain and double pendulum. PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril22.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_sp7p28vk
- Friday: Summary and discussions of final exam project. _Final exam project project, due May 1_ PDF file for notes https://github.com/mhjensen/Physics321/blob/master/doc/HandWrittenNotes/NotesApril24.pdf and video of lecture https://mediaspace.msu.edu/media/t/1_azwo1s2r
### Week 18, April 27- May 1, 2020, Finals week
- Final Exam: Due to the Corona virus the final exam will be a project similar to the two midterm projects. Deadline May 1. We will have questions sessions Monday 27 and Wednesday 29 at 2.30pm to 4pm. Other sessions can always be arranged. Just send Morten an email or a text.
## Learning outcomes
After the course you should:
- be able to analyze forces that act on objects, apply Newtons laws to determine the equations of motion, and solve these analytically and numerically,
- Know about inertial frames and their relation to accelerating and rotating frames (non-inertial frames)
- Know about forces, work, energy, angular momentum, linear momentum and conservation laws
- Know about various types of motions, falling objects, objects moving in various fields
- Know how to analyze energy diagrams and defining effective potential
- Have knowledge about small oscillations, Harmonic oscillator potential and equations of motion
- Have knowledge about transformation of variables that allow for analytical solutions, example two-body problems
- Have knowledge about central forces and two-body problems, center-of-mass and relative coordinates as reference frame
- Have knowledge about two-body scattering problems, classical scattering cross section
- Have knowledge about Variational calculus and Lagrangian formalism
- Know how to derive the equations of motion from the Lagrangian formalism with and without constraints (Lagrangian multipliers)
To solve many of these problems, we have through different projects and weekly exercises studied many systems numerically, from falling objects with and without friction/air resistance, small oscillations (harmonic oscillator), gravitational problems and other central force problems, rotations and the classical pendulum. To solve these systems, we have applied different algorithms for solving differential equations. These are
- Euler-Cromer and Velocity-Verlet as energy conserving algorithms (time-independent forces)
- Runge-Kutta family of algorithms for time-dependent forces
We have also, in connection with for example the work-energy theorem studied methods for evaluating integrals. These are
- Numerical integration using the Trapezoidal, midpoint and Simpson's rule.
You should also have acquired skills in structuring a numerical project, as well as having developed a critical understanding of the pros and cons of the methods and an understanding of their limits and what can go wrong. Computing means solving scientific problems using computers. It covers numerical as well as symbolic computing. Computing is also about developing an understanding of the scientific process by enhancing algorithmic thinking when solving problems. Computing competence has
always been a central part of the science and engineering education.
In particular, some of the competences that are important in the development of your own understanding of
computations, we would like to emphasize
- derivation, verification, and implementation of algorithms
- understanding what can go wrong with algorithms
- overview of important, known algorithms for solving mechanics problems (To a extent large differential equations and integration)
- understanding how algorithms are used to solve mathematical problems
- Making science (your results) reproducible
- algorithmic thinking for gaining deeper insights about scientific problems
@@ -0,0 +1,44 @@
# Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant, version 1.4](http://contributor-covenant.org/version/1/4).
@@ -0,0 +1,56 @@
# Contributing
Contributions are welcome, and they are greatly appreciated! Every little bit
helps, and credit will always be given. You can contribute in the ways listed below.
## Report Bugs
Report bugs using GitHub issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
## Fix Bugs
Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
wanted" is open to whoever wants to implement it.
## Implement Features
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
## Write Documentation
LectureNotes could always use more documentation, whether as part of the
official LectureNotes docs, in docstrings, or even on the web in blog posts,
articles, and such.
## Submit Feedback
The best way to send feedback is to file an issue on GitHub.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
## Get Started
Ready to contribute? Here's how to set up `LectureNotes` for local development.
1. Fork the repo on GitHub.
2. Clone your fork locally.
3. Install your local copy into a virtualenv, e.g., using `conda`.
4. Create a branch for local development and make changes locally.
5. Commit your changes and push your branch to GitHub.
6. Submit a pull request through the GitHub website.
## Code of Conduct
Please note that the LectureNotes project is released with a [Contributor Code of Conduct](CONDUCT.md). By contributing to this project you agree to abide by its terms.
@@ -0,0 +1,35 @@
# LectureNotes
Test book
## Usage
### Building the book
If you'd like to develop on and build the LectureNotes book, you should:
- Clone this repository and run
- Run `pip install -r requirements.txt` (it is recommended you do this within a virtual environment)
- (Recommended) Remove the existing `LectureNotes/_build/` directory
- Run `jupyter-book build LectureNotes/`
A fully-rendered HTML version of the book will be built in `LectureNotes/_build/html/`.
### Hosting the book
The html version of the book is hosted on the `gh-pages` branch of this repo. A GitHub actions workflow has been created that automatically builds and pushes the book to this branch on a push or pull request to main.
If you wish to disable this automation, you may remove the GitHub actions workflow and build the book manually by:
- Navigating to your local build; and running,
- `ghp-import -n -p -f LectureNotes/_build/html`
This will automatically push your build to the `gh-pages` branch. More information on this hosting process can be found [here](https://jupyterbook.org/publish/gh-pages.html#manually-host-your-book-with-github-pages).
## Contributors
We welcome and recognize all contributions. You can see a list of current contributors in the [contributors tab](https://github.com/mhjensen/lecturenotes/graphs/contributors).
## Credits
This project is created using the excellent open source [Jupyter Book project](https://jupyterbook.org/) and the [executablebooks/cookiecutter-jupyter-book template](https://github.com/executablebooks/cookiecutter-jupyter-book).
@@ -0,0 +1,5 @@
Content in Jupyter Book
=======================
There are many ways to write content in Jupyter Book. This short section
covers a few tips for how to do so.
@@ -0,0 +1,7 @@
Welcome to your Jupyter Book
============================
This is a small sample book to give you a feel for how book content is
structured.
Check out the content pages bundled with this sample book to get started.
@@ -0,0 +1,125 @@
# Markdown Files
Whether you write your book's content in Jupyter Notebooks (`.ipynb`) or
in regular markdown files (`.md`), you'll write in the same flavor of markdown
called **MyST Markdown**.
## What is MyST?
MyST stands for "Markedly Structured Text". It
is a slight variation on a flavor of markdown called "CommonMark" markdown,
with small syntax extensions to allow you to write **roles** and **directives**
in the Sphinx ecosystem.
## What are roles and directives?
Roles and directives are two of the most powerful tools in Jupyter Book. They
are kind of like functions, but written in a markup language. They both
serve a similar purpose, but **roles are written in one line**, whereas
**directives span many lines**. They both accept different kinds of inputs,
and what they do with those inputs depends on the specific role or directive
that is being called.
### Using a directive
At its simplest, you can insert a directive into your book's content like so:
````
```{mydirectivename}
My directive content
```
````
This will only work if a directive with name `mydirectivename` already exists
(which it doesn't). There are many pre-defined directives associated with
Jupyter Book. For example, to insert a note box into your content, you can
use the following directive:
````
```{note}
Here is a note
```
````
This results in:
```{note}
Here is a note
```
In your built book.
For more information on writing directives, see the
[MyST documentation](https://myst-parser.readthedocs.io/).
### Using a role
Roles are very similar to directives, but they are less-complex and written
entirely on one line. You can insert a role into your book's content with
this pattern:
```
Some content {rolename}`and here is my role's content!`
```
Again, roles will only work if `rolename` is a valid role's name. For example,
the `doc` role can be used to refer to another page in your book. You can
refer directly to another page by its relative path. For example, the
role syntax `` {doc}`intro` `` will result in: {doc}`intro`.
For more information on writing roles, see the
[MyST documentation](https://myst-parser.readthedocs.io/).
### Adding a citation
You can also cite references that are stored in a `bibtex` file. For example,
the following syntax: `` {cite}`holdgraf_evidence_2014` `` will render like
this: {cite}`holdgraf_evidence_2014`.
Moreover, you can insert a bibliography into your page with this syntax.
The `{bibliography}` directive must be used for all the `{cite}` roles to
render properly.
For example, if the references for your book are stored in `references.bib`,
then the bibliography is inserted with:
````
```{bibliography} references.bib
```
````
Resulting in a rendered bibliography that looks like:
```{bibliography} references.bib
```
### Executing code in your markdown files
If you'd like to include computational content inside these markdown files,
you can use MyST Markdown to define cells that will be executed when your
book is built. Jupyter Book uses *jupytext* to do this.
First, add Jupytext metadata to the file. For example, to add Jupytext metadata
to this markdown page, run this command:
```
jupyter-book myst init markdown.md
```
Once a markdown file has Jupytext metadata in it, you can add the following
directive to run the code at build time:
````
```{code-cell}
print("Here is some code to execute")
```
````
When your book is built, the contents of any `{code-cell}` blocks will be
executed with your default Jupyter kernel, and their outputs will be displayed
in-line with the rest of your content.
For more information about executing computational content with Jupyter Book,
see [The MyST-NB documentation](https://myst-nb.readthedocs.io/).
@@ -0,0 +1,122 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Content with notebooks\n",
"\n",
"You can also create content with Jupyter Notebooks. This means that you can include\n",
"code blocks and their outputs in your book.\n",
"\n",
"## Markdown + notebooks\n",
"\n",
"As it is markdown, you can embed images, HTML, etc into your posts!\n",
"\n",
"![](https://myst-parser.readthedocs.io/en/latest/_static/logo.png)\n",
"\n",
"You an also $add_{math}$ and\n",
"\n",
"$$\n",
"math^{blocks}\n",
"$$\n",
"\n",
"or\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mbox{mean} la_{tex} \\\\ \\\\\n",
"math blocks\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"But make sure you \\$Escape \\$your \\$dollar signs \\$you want to keep!\n",
"\n",
"## MyST markdown\n",
"\n",
"MyST markdown works in Jupyter Notebooks as well. For more information about MyST markdown, check\n",
"out [the MyST guide in Jupyter Book](https://jupyterbook.org/content/myst.html),\n",
"or see [the MyST markdown documentation](https://myst-parser.readthedocs.io/en/latest/).\n",
"\n",
"## Code blocks and outputs\n",
"\n",
"Jupyter Book will also embed your code blocks and output in your book.\n",
"For example, here's some sample Matplotlib code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import rcParams, cycler\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"plt.ion()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Fixing random state for reproducibility\n",
"np.random.seed(19680801)\n",
"\n",
"N = 10\n",
"data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]\n",
"data = np.array(data).T\n",
"cmap = plt.cm.coolwarm\n",
"rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))\n",
"\n",
"\n",
"from matplotlib.lines import Line2D\n",
"custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),\n",
" Line2D([0], [0], color=cmap(.5), lw=4),\n",
" Line2D([0], [0], color=cmap(1.), lw=4)]\n",
"\n",
"fig, ax = plt.subplots(figsize=(10, 5))\n",
"lines = ax.plot(data)\n",
"ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is a lot more that you can do with outputs (such as including interactive outputs)\n",
"with your book. For more information about this, see [the Jupyter Book documentation](https://jupyterbook.org)."
]
}
],
"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.8.0"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
@@ -0,0 +1,125 @@
# Markdown Files
Whether you write your book's content in Jupyter Notebooks (`.ipynb`) or
in regular markdown files (`.md`), you'll write in the same flavor of markdown
called **MyST Markdown**.
## What is MyST?
MyST stands for "Markedly Structured Text". It
is a slight variation on a flavor of markdown called "CommonMark" markdown,
with small syntax extensions to allow you to write **roles** and **directives**
in the Sphinx ecosystem.
## What are roles and directives?
Roles and directives are two of the most powerful tools in Jupyter Book. They
are kind of like functions, but written in a markup language. They both
serve a similar purpose, but **roles are written in one line**, whereas
**directives span many lines**. They both accept different kinds of inputs,
and what they do with those inputs depends on the specific role or directive
that is being called.
### Using a directive
At its simplest, you can insert a directive into your book's content like so:
````
```{mydirectivename}
My directive content
```
````
This will only work if a directive with name `mydirectivename` already exists
(which it doesn't). There are many pre-defined directives associated with
Jupyter Book. For example, to insert a note box into your content, you can
use the following directive:
````
```{note}
Here is a note
```
````
This results in:
```{note}
Here is a note
```
In your built book.
For more information on writing directives, see the
[MyST documentation](https://myst-parser.readthedocs.io/).
### Using a role
Roles are very similar to directives, but they are less-complex and written
entirely on one line. You can insert a role into your book's content with
this pattern:
```
Some content {rolename}`and here is my role's content!`
```
Again, roles will only work if `rolename` is a valid role's name. For example,
the `doc` role can be used to refer to another page in your book. You can
refer directly to another page by its relative path. For example, the
role syntax `` {doc}`intro` `` will result in: {doc}`intro`.
For more information on writing roles, see the
[MyST documentation](https://myst-parser.readthedocs.io/).
### Adding a citation
You can also cite references that are stored in a `bibtex` file. For example,
the following syntax: `` {cite}`holdgraf_evidence_2014` `` will render like
this: {cite}`holdgraf_evidence_2014`.
Moreoever, you can insert a bibliography into your page with this syntax:
The `{bibliography}` directive must be used for all the `{cite}` roles to
render properly.
For example, if the references for your book are stored in `references.bib`,
then the bibliography is inserted with:
````
```{bibliography} references.bib
```
````
Resulting in a rendered bibliography that looks like:
```{bibliography} references.bib
```
### Executing code in your markdown files
If you'd like to include computational content inside these markdown files,
you can use MyST Markdown to define cells that will be executed when your
book is built. Jupyter Book uses *jupytext* to do this.
First, add Jupytext metadata to the file. For example, to add Jupytext metadata
to this markdown page, run this command:
```
jupyter-book myst init markdown.md
```
Once a markdown file has Jupytext metadata in it, you can add the following
directive to run the code at build time:
````
```{code-cell}
print("Here is some code to execute")
```
````
When your book is built, the contents of any `{code-cell}` blocks will be
executed with your default Jupyter kernel, and their outputs will be displayed
in-line with the rest of your content.
For more information about executing computational content with Jupyter Book,
see [The MyST-NB documentation](https://myst-nb.readthedocs.io/).
+85 -18
View File
@@ -38,7 +38,7 @@
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="1. Getting started, our first data and Machine Learning encounters" href="chapter2.html" />
<link rel="next" title="1. Elements of Probability Theory and Statistical Data Analysis" href="chapter2.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
@@ -78,20 +78,100 @@
</a>
</li>
</ul>
<p class="caption">
<span class="caption-text">
Supervised Learning
</span>
</p>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html">
1. Getting started, our first data and Machine Learning encounters
1. Elements of Probability Theory and Statistical Data Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers">
2. Random Numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers-better-name-pseudo-random-numbers">
3. Random Numbers, better name: pseudo random numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng">
4. Random number generator RNG
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-periodic-outputs">
5. Random number generator RNG and periodic outputs
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-its-period">
6. Random number generator RNG and its period
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-other-examples">
7. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id9">
8. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0">
9. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id10">
10. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id11">
11. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id12">
12. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0-code">
13. Random number generator RNG, RAN0 code
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#which-rng-should-i-use">
14. Which RNG should I use?
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
2. Linear Regression and more Advanced Regression Analysis
15. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
3. Logistic Regression
16. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter5.html">
17. Logistic Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter6.html">
18. Neural networks, from the simple perceptron to deep learning
</a>
</li>
</ul>
@@ -147,19 +227,6 @@
</div>
<!-- Source interaction buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Connect with source repository"><i class="fab fa-github"></i></button>
<div class="dropdown-buttons sourcebuttons">
<a class="repository-button"
href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/src/LectureNotes"><button type="button" class="btn btn-secondary topbarbtn"
data-toggle="tooltip" data-placement="left" title="Source repository"><i
class="fab fa-github"></i>repository</button></a>
</div>
</div>
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
@@ -583,7 +650,7 @@ society.</p>
<div class='prev-next-bottom'>
<a class='right-next' id="next-link" href="chapter2.html" title="next page"><span class="section-number">1. </span>Getting started, our first data and Machine Learning encounters</a>
<a class='right-next' id="next-link" href="chapter2.html" title="next page"><span class="section-number">1. </span>Elements of Probability Theory and Statistical Data Analysis</a>
</div>
<footer class="footer mt-5 mt-md-0">
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,667 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>17. Logistic Regression &#8212; Applied Machine Learning and Data Analysis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
<link rel="stylesheet" type="text/css" href="_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />
<script id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/language_data.js"></script>
<script src="_static/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="18. Neural networks, from the simple perceptron to deep learning" href="chapter6.html" />
<link rel="prev" title="16. Linear Regression and more Advanced Regression Analysis" href="chapter4.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="index.html">
<img src="_static/Picture.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">Applied Machine Learning and Data Analysis</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter1.html">
Introduction to Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<p class="caption">
<span class="caption-text">
Supervised Learning
</span>
</p>
<ul class="current nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html">
1. Elements of Probability Theory and Statistical Data Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers">
2. Random Numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers-better-name-pseudo-random-numbers">
3. Random Numbers, better name: pseudo random numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng">
4. Random number generator RNG
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-periodic-outputs">
5. Random number generator RNG and periodic outputs
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-its-period">
6. Random number generator RNG and its period
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-other-examples">
7. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id9">
8. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0">
9. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id10">
10. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id11">
11. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id12">
12. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0-code">
13. Random number generator RNG, RAN0 code
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#which-rng-should-i-use">
14. Which RNG should I use?
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
15. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
16. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1 current active">
<a class="current reference internal" href="#">
17. Logistic Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter6.html">
18. Neural networks, from the simple perceptron to deep learning
</a>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="_sources/chapter5.ipynb"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.ipynb</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
<ul class="nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#introduction">
17.1. Introduction
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#basics">
17.2. Basics
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-logistic-function">
17.3. The logistic function
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#two-parameters">
17.4. Two parameters
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#maximum-likelihood">
17.5. Maximum likelihood
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#including-more-classes">
17.6. Including more classes
</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="logistic-regression">
<h1><span class="section-number">17. </span>Logistic Regression<a class="headerlink" href="#logistic-regression" title="Permalink to this headline"></a></h1>
<div class="section" id="introduction">
<h2><span class="section-number">17.1. </span>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline"></a></h2>
<p>In linear regression our main interest was centered on learning the
coefficients of a functional fit (say a polynomial) in order to be
able to predict the response of a continuous variable on some unseen
data. The fit to the continuous variable <span class="math notranslate nohighlight">\(y_i\)</span> is based on some
independent variables <span class="math notranslate nohighlight">\(\hat{x}_i\)</span>. Linear regression resulted in
analytical expressions for standard ordinary Least Squares or Ridge
regression (in terms of matrices to invert) for several quantities,
ranging from the variance and thereby the confidence intervals of the
parameters <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> to the mean squared error. If we can invert
the product of the design matrices, linear regression gives then a
simple recipe for fitting our data.</p>
<p>Classification problems, however, are concerned with outcomes taking
the form of discrete variables (i.e. categories). We may for example,
on the basis of DNA sequencing for a number of patients, like to find
out which mutations are important for a certain disease; or based on
scans of various patients brains, figure out if there is a tumor or
not; or given a specific physical system, wed like to identify its
state, say whether it is an ordered or disordered system (typical
situation in solid state physics); or classify the status of a
patient, whether she/he has a stroke or not and many other similar
situations.</p>
<p>The most common situation we encounter when we apply logistic
regression is that of two possible outcomes, normally denoted as a
binary outcome, true or false, positive or negative, success or
failure etc.</p>
<p>Logistic regression will also serve as our stepping stone towards
neural network algorithms and supervised deep learning. For logistic
learning, the minimization of the cost function leads to a non-linear
equation in the parameters <span class="math notranslate nohighlight">\(\hat{\beta}\)</span>. The optimization of the
problem calls therefore for minimization algorithms. This forms the
bottle neck of all machine learning algorithms, namely how to find
reliable minima of a multi-variable function. This leads us to the
family of gradient descent methods. The latter are the working horses
of basically all modern machine learning algorithms.</p>
<p>We note also that many of the topics discussed here on logistic
regression are also commonly used in modern supervised Deep Learning
models, as we will see later.</p>
</div>
<div class="section" id="basics">
<h2><span class="section-number">17.2. </span>Basics<a class="headerlink" href="#basics" title="Permalink to this headline"></a></h2>
<p>We consider the case where the dependent variables, also called the
responses or the outcomes, <span class="math notranslate nohighlight">\(y_i\)</span> are discrete and only take values
from <span class="math notranslate nohighlight">\(k=0,\dots,K-1\)</span> (i.e. <span class="math notranslate nohighlight">\(K\)</span> classes).</p>
<p>The goal is to predict the
output classes from the design matrix <span class="math notranslate nohighlight">\(\hat{X}\in\mathbb{R}^{n\times p}\)</span>
made of <span class="math notranslate nohighlight">\(n\)</span> samples, each of which carries <span class="math notranslate nohighlight">\(p\)</span> features or predictors. The
primary goal is to identify the classes to which new unseen samples
belong.</p>
<p>Let us specialize to the case of two classes only, with outputs
<span class="math notranslate nohighlight">\(y_i=0\)</span> and <span class="math notranslate nohighlight">\(y_i=1\)</span>. Our outcomes could represent the status of a
credit card user that could default or not on her/his credit card
debt. That is</p>
<div class="math notranslate nohighlight">
\[\begin{split}
y_i = \begin{bmatrix} 0 &amp; \mathrm{no}\\ 1 &amp; \mathrm{yes} \end{bmatrix}.
\end{split}\]</div>
<p>Before moving to the logistic model, let us try to use our linear
regression model to classify these two outcomes. We could for example
fit a linear model to the default case if <span class="math notranslate nohighlight">\(y_i &gt; 0.5\)</span> and the no
default case <span class="math notranslate nohighlight">\(y_i \leq 0.5\)</span>.</p>
<p>We would then have our
weighted linear combination, namely</p>
<!-- Equation labels as ordinary links -->
<div id="_auto1"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}
\hat{y} = \hat{X}^T\hat{\beta} + \hat{\epsilon},
\label{_auto1} \tag{1}
\end{equation}
\]</div>
<p>where <span class="math notranslate nohighlight">\(\hat{y}\)</span> is a vector representing the possible outcomes, <span class="math notranslate nohighlight">\(\hat{X}\)</span> is our
<span class="math notranslate nohighlight">\(n\times p\)</span> design matrix and <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> represents our estimators/predictors.</p>
<p>The main problem with our function is that it takes values on the
entire real axis. In the case of logistic regression, however, the
labels <span class="math notranslate nohighlight">\(y_i\)</span> are discrete variables. A typical example is the credit
card data discussed below here, where we can set the state of
defaulting the debt to <span class="math notranslate nohighlight">\(y_i=1\)</span> and not to <span class="math notranslate nohighlight">\(y_i=0\)</span> for one the persons
in the data set (see the full example below).</p>
<p>One simple way to get a discrete output is to have sign
functions that map the output of a linear regressor to values <span class="math notranslate nohighlight">\(\{0,1\}\)</span>,
<span class="math notranslate nohighlight">\(f(s_i)=sign(s_i)=1\)</span> if <span class="math notranslate nohighlight">\(s_i\ge 0\)</span> and 0 if otherwise.
We will encounter this model in our first demonstration of neural networks. Historically it is called the “perceptron” model in the machine learning
literature. This model is extremely simple. However, in many cases it is more
favorable to use a ``soft” classifier that outputs
the probability of a given category. This leads us to the logistic function.</p>
</div>
<div class="section" id="the-logistic-function">
<h2><span class="section-number">17.3. </span>The logistic function<a class="headerlink" href="#the-logistic-function" title="Permalink to this headline"></a></h2>
<p>The perceptron is an example of a ``hard classification” model. We
will encounter this model when we discuss neural networks as
well. Each datapoint is deterministically assigned to a category (i.e
<span class="math notranslate nohighlight">\(y_i=0\)</span> or <span class="math notranslate nohighlight">\(y_i=1\)</span>). In many cases, it is favorable to have a “soft”
classifier that outputs the probability of a given category rather
than a single value. For example, given <span class="math notranslate nohighlight">\(x_i\)</span>, the classifier
outputs the probability of being in a category <span class="math notranslate nohighlight">\(k\)</span>. Logistic regression
is the most common example of a so-called soft classifier. In logistic
regression, the probability that a data point <span class="math notranslate nohighlight">\(x_i\)</span>
belongs to a category <span class="math notranslate nohighlight">\(y_i=\{0,1\}\)</span> is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,</p>
<div class="math notranslate nohighlight">
\[
p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}.
\]</div>
<p>Note that <span class="math notranslate nohighlight">\(1-p(t)= p(-t)\)</span>.</p>
<p>The following code plots the logistic function, the step function and other functions we will encounter from here and on.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="k">matplotlib</span> inline
<span class="sd">&quot;&quot;&quot;The sigmoid function (or the logistic curve) is a</span>
<span class="sd">function that takes any real number, z, and outputs a number (0,1).</span>
<span class="sd">It is useful in neural networks for assigning weights on a relative scale.</span>
<span class="sd">The value z is the weighted sum of parameters involved in the learning algorithm.&quot;&quot;&quot;</span>
<span class="kn">import</span> <span class="nn">numpy</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">math</span> <span class="k">as</span> <span class="nn">mt</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">)</span>
<span class="n">sigma_fn</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">vectorize</span><span class="p">(</span><span class="k">lambda</span> <span class="n">z</span><span class="p">:</span> <span class="mi">1</span><span class="o">/</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="n">numpy</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="n">z</span><span class="p">)))</span>
<span class="n">sigma</span> <span class="o">=</span> <span class="n">sigma_fn</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">111</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">sigma</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_ylim</span><span class="p">([</span><span class="o">-</span><span class="mf">0.1</span><span class="p">,</span> <span class="mf">1.1</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">([</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span><span class="mi">5</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;sigmoid function&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
<span class="sd">&quot;&quot;&quot;Step Function&quot;&quot;&quot;</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="o">.</span><span class="mi">02</span><span class="p">)</span>
<span class="n">step_fn</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">vectorize</span><span class="p">(</span><span class="k">lambda</span> <span class="n">z</span><span class="p">:</span> <span class="mf">1.0</span> <span class="k">if</span> <span class="n">z</span> <span class="o">&gt;=</span> <span class="mf">0.0</span> <span class="k">else</span> <span class="mf">0.0</span><span class="p">)</span>
<span class="n">step</span> <span class="o">=</span> <span class="n">step_fn</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">111</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">step</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_ylim</span><span class="p">([</span><span class="o">-</span><span class="mf">0.5</span><span class="p">,</span> <span class="mf">1.5</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">([</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span><span class="mi">5</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;step function&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
<span class="sd">&quot;&quot;&quot;tanh Function&quot;&quot;&quot;</span>
<span class="n">z</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">)</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">numpy</span><span class="o">.</span><span class="n">tanh</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">111</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_ylim</span><span class="p">([</span><span class="o">-</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">([</span><span class="o">-</span><span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span><span class="mi">2</span><span class="o">*</span><span class="n">mt</span><span class="o">.</span><span class="n">pi</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s1">&#39;tanh function&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/chapter5_7_0.png" src="_images/chapter5_7_0.png" />
<img alt="_images/chapter5_7_1.png" src="_images/chapter5_7_1.png" />
<img alt="_images/chapter5_7_2.png" src="_images/chapter5_7_2.png" />
</div>
</div>
</div>
<div class="section" id="two-parameters">
<h2><span class="section-number">17.4. </span>Two parameters<a class="headerlink" href="#two-parameters" title="Permalink to this headline"></a></h2>
<p>We assume now that we have two classes with <span class="math notranslate nohighlight">\(y_i\)</span> either <span class="math notranslate nohighlight">\(0\)</span> or <span class="math notranslate nohighlight">\(1\)</span>. Furthermore we assume also that we have only two parameters <span class="math notranslate nohighlight">\(\beta\)</span> in our fitting of the Sigmoid function, that is we define probabilities</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{align*}
p(y_i=1|x_i,\hat{\beta}) &amp;= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\
p(y_i=0|x_i,\hat{\beta}) &amp;= 1 - p(y_i=1|x_i,\hat{\beta}),
\end{align*}
\end{split}\]</div>
<p>where <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> are the weights we wish to extract from data, in our case <span class="math notranslate nohighlight">\(\beta_0\)</span> and <span class="math notranslate nohighlight">\(\beta_1\)</span>.</p>
<p>Note that we used</p>
<div class="math notranslate nohighlight">
\[
p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}).
\]</div>
</div>
<div class="section" id="maximum-likelihood">
<h2><span class="section-number">17.5. </span>Maximum likelihood<a class="headerlink" href="#maximum-likelihood" title="Permalink to this headline"></a></h2>
<p>In order to define the total likelihood for all possible outcomes from a<br />
dataset <span class="math notranslate nohighlight">\(\mathcal{D}=\{(y_i,x_i)\}\)</span>, with the binary labels
<span class="math notranslate nohighlight">\(y_i\in\{0,1\}\)</span> and where the data points are drawn independently, we use the so-called <a class="reference external" href="https://en.wikipedia.org/wiki/Maximum_likelihood_estimation">Maximum Likelihood Estimation</a> (MLE) principle.
We aim thus at maximizing
the probability of seeing the observed data. We can then approximate the
likelihood in terms of the product of the individual probabilities of a specific outcome <span class="math notranslate nohighlight">\(y_i\)</span>, that is</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{align*}
P(\mathcal{D}|\hat{\beta})&amp; = \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 \\
\end{align*}
\end{split}\]</div>
<p>from which we obtain the log-likelihood and our <strong>cost/loss</strong> function</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>Reordering the logarithms, we can rewrite the <strong>cost/loss</strong> function as</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to <span class="math notranslate nohighlight">\(\beta\)</span>.
Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>This equation is known in statistics as the <strong>cross entropy</strong>. Finally, we note that just as in linear regression,
in practice we often supplement the cross-entropy with additional regularization terms, usually <span class="math notranslate nohighlight">\(L_1\)</span> and <span class="math notranslate nohighlight">\(L_2\)</span> regularization as we did for Ridge and Lasso regression.</p>
<p>The cross entropy is a convex function of the weights <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> and,
therefore, any local minimizer is a global minimizer.</p>
<p>Minimizing this
cost function with respect to the two parameters <span class="math notranslate nohighlight">\(\beta_0\)</span> and <span class="math notranslate nohighlight">\(\beta_1\)</span> we obtain</p>
<div class="math notranslate nohighlight">
\[
\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),
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
\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).
\]</div>
<p>Let us now define a vector <span class="math notranslate nohighlight">\(\hat{y}\)</span> with <span class="math notranslate nohighlight">\(n\)</span> elements <span class="math notranslate nohighlight">\(y_i\)</span>, an
<span class="math notranslate nohighlight">\(n\times p\)</span> matrix <span class="math notranslate nohighlight">\(\hat{X}\)</span> which contains the <span class="math notranslate nohighlight">\(x_i\)</span> values and a
vector <span class="math notranslate nohighlight">\(\hat{p}\)</span> of fitted probabilities <span class="math notranslate nohighlight">\(p(y_i\vert x_i,\hat{\beta})\)</span>. We can rewrite in a more compact form the first
derivative of cost function as</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right).
\]</div>
<p>If we in addition define a diagonal matrix <span class="math notranslate nohighlight">\(\hat{W}\)</span> with elements
<span class="math notranslate nohighlight">\(p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})\)</span>, we can obtain a compact expression of the second derivative as</p>
<div class="math notranslate nohighlight">
\[
\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}.
\]</div>
<p>Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with <span class="math notranslate nohighlight">\(p\)</span> predictors</p>
<div class="math notranslate nohighlight">
\[
\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.
\]</div>
<p>Here we defined <span class="math notranslate nohighlight">\(\hat{x}=[1,x_1,x_2,\dots,x_p]\)</span> and <span class="math notranslate nohighlight">\(\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]\)</span> leading to</p>
<div class="math notranslate nohighlight">
\[
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)}}.
\]</div>
</div>
<div class="section" id="including-more-classes">
<h2><span class="section-number">17.6. </span>Including more classes<a class="headerlink" href="#including-more-classes" title="Permalink to this headline"></a></h2>
<p>Till now we have mainly focused on two classes, the so-called binary
system. Suppose we wish to extend to <span class="math notranslate nohighlight">\(K\)</span> classes. Let us for the sake
of simplicity assume we have only two predictors. We have then
following model</p>
<p>1
5</p>
<p>&lt;
&lt;
&lt;
!
!
M
A
T
H
_
B
L
O
C
K</p>
<div class="math notranslate nohighlight">
\[
\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1,
\]</div>
<p>and so on till the class <span class="math notranslate nohighlight">\(C=K-1\)</span> class</p>
<div class="math notranslate nohighlight">
\[
\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1,
\]</div>
<p>and the model is specified in term of <span class="math notranslate nohighlight">\(K-1\)</span> so-called log-odds or
<strong>logit</strong> transformations.</p>
<p>In our discussion of neural networks we will encounter the above again
in terms of a slightly modified function, the so-called <strong>Softmax</strong> function.</p>
<p>The softmax function is used in various multiclass classification
methods, such as multinomial logistic regression (also known as
softmax regression), multiclass linear discriminant analysis, naive
Bayes classifiers, and artificial neural networks. Specifically, in
multinomial logistic regression and linear discriminant analysis, the
input to the function is the result of <span class="math notranslate nohighlight">\(K\)</span> distinct linear functions,
and the predicted probability for the <span class="math notranslate nohighlight">\(k\)</span>-th class given a sample
vector <span class="math notranslate nohighlight">\(\hat{x}\)</span> and a weighting vector <span class="math notranslate nohighlight">\(\hat{\beta}\)</span> is (with two
predictors):</p>
<div class="math notranslate nohighlight">
\[
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)}}.
\]</div>
<p>It is easy to extend to more predictors. The final class is</p>
<div class="math notranslate nohighlight">
\[
p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}},
\]</div>
<p>and they sum to one. Our earlier discussions were all specialized to
the case with two classes only. It is easy to see from the above that
what we derived earlier is compatible with these equations.</p>
<p>To find the optimal parameters we would typically use a gradient
descent method. Newtons method and gradient descent methods are
discussed in the material on <a class="reference external" href="https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html">optimization
methods</a>.</p>
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
<a class='left-prev' id="prev-link" href="chapter4.html" title="previous page"><span class="section-number">16. </span>Linear Regression and more Advanced Regression Analysis</a>
<a class='right-next' id="next-link" href="chapter6.html" title="next page"><span class="section-number">18. </span>Neural networks, from the simple perceptron to deep learning</a>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+83 -16
View File
@@ -77,20 +77,100 @@
</a>
</li>
</ul>
<p class="caption">
<span class="caption-text">
Supervised Learning
</span>
</p>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html">
1. Getting started, our first data and Machine Learning encounters
1. Elements of Probability Theory and Statistical Data Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers">
2. Random Numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers-better-name-pseudo-random-numbers">
3. Random Numbers, better name: pseudo random numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng">
4. Random number generator RNG
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-periodic-outputs">
5. Random number generator RNG and periodic outputs
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-its-period">
6. Random number generator RNG and its period
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-other-examples">
7. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id9">
8. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0">
9. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id10">
10. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id11">
11. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id12">
12. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0-code">
13. Random number generator RNG, RAN0 code
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#which-rng-should-i-use">
14. Which RNG should I use?
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
2. Linear Regression and more Advanced Regression Analysis
15. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
3. Logistic Regression
16. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter5.html">
17. Logistic Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter6.html">
18. Neural networks, from the simple perceptron to deep learning
</a>
</li>
</ul>
@@ -134,19 +214,6 @@
</div>
<!-- Source interaction buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Connect with source repository"><i class="fab fa-github"></i></button>
<div class="dropdown-buttons sourcebuttons">
<a class="repository-button"
href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/src/LectureNotes"><button type="button" class="btn btn-secondary topbarbtn"
data-toggle="tooltip" data-placement="left" title="Source repository"><i
class="fab fa-github"></i>repository</button></a>
</div>
</div>
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
Binary file not shown.
@@ -22,10 +22,10 @@ x = np.log(np.array([4.0, 7.0, 8.0])
print(x)
------------------
 File "<ipython-input-7-f6d7a289d493>", line 3
 File "<ipython-input-20-f6d7a289d493>", line 3
 print(x)
 ^
SyntaxError: invalid syntax
SyntaxError: invalid syntax (<ipython-input-7-f6d7a289d493>, line 3)
SyntaxError: invalid syntax (<ipython-input-20-f6d7a289d493>, line 3)
@@ -17,100 +17,15 @@ Traceback (most recent call last):
raise CellExecutionError.from_cell_and_msg(cell, exec_reply['content'])
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
from numpy import *
from numpy.random import randint, randn
from time import time
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# Returns mean of bootstrap samples
def stat(data):
return mean(data)
# Bootstrap algorithm
def bootstrap(data, statistic, R):
t = zeros(R); n = len(data); inds = arange(n); t0 = time()
# non-parametric bootstrap
for i in range(R):
t[i] = statistic(data[randint(0,n,n)])
# analysis
print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
print("original bias std. error")
print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
return t
mu, sigma = 100, 15
datapoints = 10000
x = mu + sigma*random.randn(datapoints)
# bootstrap returns the data sample
t = bootstrap(x, stat, datapoints)
# the histogram of the bootstrapped data
n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( binsboot, mean(t), std(t))
lt = plt.plot(binsboot, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.axis([99.5, 100.6, 0, 3.0])
plt.grid(True)
plt.show()
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x)
------------------
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-29-53990135e988> in <module>
 29 t = bootstrap(x, stat, datapoints)
 30 # the histogram of the bootstrapped data
---> 31 n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
 32 
 33 # add a 'best fit' line
 File "<ipython-input-7-f6d7a289d493>", line 3
 print(x)
 ^
SyntaxError: invalid syntax
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, data, **kwargs)
 2603 orientation='vertical', rwidth=None, log=False, color=None,
 2604 label=None, stacked=False, *, data=None, **kwargs):
-> 2605 return gca().hist(
 2606 x, bins=bins, range=range, density=density, weights=weights,
 2607 cumulative=cumulative, bottom=bottom, histtype=histtype,
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
 1563 def inner(ax, *args, data=None, **kwargs):
 1564 if data is None:
-> 1565 return func(ax, *map(sanitize_sequence, args), **kwargs)
 1566 
 1567 bound = new_sig.bind(ax, *args, **kwargs)
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in hist(self, x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
 6817 if patch:
 6818 p = patch[0]
-> 6819 p.update(kwargs)
 6820 if lbl is not None:
 6821 p.set_label(lbl)
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py in update(self, props)
 1004 
 1005 with cbook._setattr_cm(self, eventson=False):
-> 1006 ret = [_update_property(self, k, v) for k, v in props.items()]
 1007 
 1008 if len(ret):
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py in <listcomp>(.0)
 1004 
 1005 with cbook._setattr_cm(self, eventson=False):
-> 1006 ret = [_update_property(self, k, v) for k, v in props.items()]
 1007 
 1008 if len(ret):
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py in _update_property(self, k, v)
 999 func = getattr(self, 'set_' + k, None)
 1000 if not callable(func):
-> 1001 raise AttributeError('{!r} object has no property {!r}'
 1002 .format(type(self).__name__, k))
 1003 return func(v)
AttributeError: 'Rectangle' object has no property 'normed'
AttributeError: 'Rectangle' object has no property 'normed'
SyntaxError: invalid syntax (<ipython-input-7-f6d7a289d493>, line 3)
@@ -0,0 +1,116 @@
Traceback (most recent call last):
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 1082, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/util.py", line 74, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/util.py", line 53, in just_run
return loop.run_until_complete(coro)
File "/Users/hjensen/opt/anaconda3/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 535, in async_execute
await self.async_execute_cell(
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 827, in async_execute_cell
self._check_raise_for_error(cell, exec_reply)
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 735, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply['content'])
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
from numpy import *
from numpy.random import randint, randn
from time import time
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# Returns mean of bootstrap samples
def stat(data):
return mean(data)
# Bootstrap algorithm
def bootstrap(data, statistic, R):
t = zeros(R); n = len(data); inds = arange(n); t0 = time()
# non-parametric bootstrap
for i in range(R):
t[i] = statistic(data[randint(0,n,n)])
# analysis
print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
print("original bias std. error")
print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
return t
mu, sigma = 100, 15
datapoints = 10000
x = mu + sigma*random.randn(datapoints)
# bootstrap returns the data sample
t = bootstrap(x, stat, datapoints)
# the histogram of the bootstrapped data
n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( binsboot, mean(t), std(t))
lt = plt.plot(binsboot, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.axis([99.5, 100.6, 0, 3.0])
plt.grid(True)
plt.show()
------------------
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-29-53990135e988> in <module>
 29 t = bootstrap(x, stat, datapoints)
 30 # the histogram of the bootstrapped data
---> 31 n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
 32 
 33 # add a 'best fit' line
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, data, **kwargs)
 2603 orientation='vertical', rwidth=None, log=False, color=None,
 2604 label=None, stacked=False, *, data=None, **kwargs):
-> 2605 return gca().hist(
 2606 x, bins=bins, range=range, density=density, weights=weights,
 2607 cumulative=cumulative, bottom=bottom, histtype=histtype,
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
 1563 def inner(ax, *args, data=None, **kwargs):
 1564 if data is None:
-> 1565 return func(ax, *map(sanitize_sequence, args), **kwargs)
 1566 
 1567 bound = new_sig.bind(ax, *args, **kwargs)
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in hist(self, x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
 6817 if patch:
 6818 p = patch[0]
-> 6819 p.update(kwargs)
 6820 if lbl is not None:
 6821 p.set_label(lbl)
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py in update(self, props)
 1004 
 1005 with cbook._setattr_cm(self, eventson=False):
-> 1006 ret = [_update_property(self, k, v) for k, v in props.items()]
 1007 
 1008 if len(ret):
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py in <listcomp>(.0)
 1004 
 1005 with cbook._setattr_cm(self, eventson=False):
-> 1006 ret = [_update_property(self, k, v) for k, v in props.items()]
 1007 
 1008 if len(ret):
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py in _update_property(self, k, v)
 999 func = getattr(self, 'set_' + k, None)
 1000 if not callable(func):
-> 1001 raise AttributeError('{!r} object has no property {!r}'
 1002 .format(type(self).__name__, k))
 1003 return func(v)
AttributeError: 'Rectangle' object has no property 'normed'
AttributeError: 'Rectangle' object has no property 'normed'
@@ -0,0 +1,42 @@
Traceback (most recent call last):
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 1082, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/util.py", line 74, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/util.py", line 53, in just_run
return loop.run_until_complete(coro)
File "/Users/hjensen/opt/anaconda3/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 535, in async_execute
await self.async_execute_cell(
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 827, in async_execute_cell
self._check_raise_for_error(cell, exec_reply)
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 735, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply['content'])
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
def RK2(v,x,t,n,Force):
for i in range(n-1):
# Setting up k1
k1x = DeltaT*v[i]
k1v = DeltaT*Force(v[i],x[i],t[i])
# Setting up k2
vv = v[i]+k1v*0.5
xx = x[i]+k1x*0.5
k2x = DeltaT*vv
k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)
# Final result
x[i+1] = x[i]+k2x
v[i+1] = v[i]+k2v
t[i+1] = t[i]+DeltaT
------------------
 File "<ipython-input-7-ffedbda27704>", line 14
 t[i+1] = t[i]+DeltaT
 ^
TabError: inconsistent use of tabs and spaces in indentation
TabError: inconsistent use of tabs and spaces in indentation (<ipython-input-7-ffedbda27704>, line 14)
@@ -0,0 +1,39 @@
Traceback (most recent call last):
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 604, in _async_poll_for_reply
msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout))
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/util.py", line 85, in ensure_async
result = await obj
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/jupyter_client/asynchronous/channels.py", line 48, in get_msg
raise Empty
_queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 1082, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/util.py", line 74, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/util.py", line 53, in just_run
return loop.run_until_complete(coro)
File "/Users/hjensen/opt/anaconda3/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 535, in async_execute
await self.async_execute_cell(
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 811, in async_execute_cell
exec_reply = await self.task_poll_for_reply
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 628, in _async_poll_for_reply
await self._async_handle_timeout(timeout, cell)
File "/Users/hjensen/opt/anaconda3/lib/python3.8/site-packages/nbclient/client.py", line 678, in _async_handle_timeout
raise CellTimeoutError.error_from_timeout_and_cell(
nbclient.exceptions.CellTimeoutError: A cell timed out while it was being executed, after 30 seconds.
The message was: Cell execution timed out.
Here is a preview of the cell contents:
-------------------
['eta_vals = np.logspace(-5, 1, 7)', 'lmbd_vals = np.logspace(-5, 1, 7)', '# store the models for later use', 'DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)', '']
...
[' ', ' print("Learning rate = ", eta)', ' print("Lambda = ", lmbd)', ' print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))', ' print()']
-------------------
+83 -16
View File
@@ -82,20 +82,100 @@
</a>
</li>
</ul>
<p class="caption">
<span class="caption-text">
Supervised Learning
</span>
</p>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html">
1. Getting started, our first data and Machine Learning encounters
1. Elements of Probability Theory and Statistical Data Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers">
2. Random Numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-numbers-better-name-pseudo-random-numbers">
3. Random Numbers, better name: pseudo random numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng">
4. Random number generator RNG
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-periodic-outputs">
5. Random number generator RNG and periodic outputs
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-and-its-period">
6. Random number generator RNG and its period
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-other-examples">
7. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id9">
8. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0">
9. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id10">
10. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id11">
11. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#id12">
12. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#random-number-generator-rng-ran0-code">
13. Random number generator RNG, RAN0 code
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html#which-rng-should-i-use">
14. Which RNG should I use?
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
2. Linear Regression and more Advanced Regression Analysis
15. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
3. Logistic Regression
16. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter5.html">
17. Logistic Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter6.html">
18. Neural networks, from the simple perceptron to deep learning
</a>
</li>
</ul>
@@ -139,19 +219,6 @@
</div>
<!-- Source interaction buttons -->
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
aria-label="Connect with source repository"><i class="fab fa-github"></i></button>
<div class="dropdown-buttons sourcebuttons">
<a class="repository-button"
href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/src/LectureNotes"><button type="button" class="btn btn-secondary topbarbtn"
data-toggle="tooltip" data-placement="left" title="Source repository"><i
class="fab fa-github"></i>repository</button></a>
</div>
</div>
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
File diff suppressed because one or more lines are too long
@@ -0,0 +1,473 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Introduction &#8212; Applied Machine Learning and Data Analysis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="../../../_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="../../../_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../../../_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="../../../_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="../../../_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="../../../_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="../../../_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
<link rel="stylesheet" type="text/css" href="../../../_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />
<script id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
<script src="../../../_static/jquery.js"></script>
<script src="../../../_static/underscore.js"></script>
<script src="../../../_static/doctools.js"></script>
<script src="../../../_static/language_data.js"></script>
<script src="../../../_static/togglebutton.js"></script>
<script src="../../../_static/clipboard.min.js"></script>
<script src="../../../_static/copybutton.js"></script>
<script src="../../../_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="../../../_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="../../../genindex.html" />
<link rel="search" title="Search" href="../../../search.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="../../../index.html">
<img src="../../../_static/Picture.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">Applied Machine Learning and Data Analysis</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="../../../search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter1.html">
Introduction to Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<p class="caption">
<span class="caption-text">
Supervised Learning
</span>
</p>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html">
1. Elements of Probability Theory and Statistical Data Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-numbers">
2. Random Numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-numbers-better-name-pseudo-random-numbers">
3. Random Numbers, better name: pseudo random numbers
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-number-generator-rng">
4. Random number generator RNG
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-number-generator-rng-and-periodic-outputs">
5. Random number generator RNG and periodic outputs
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-number-generator-rng-and-its-period">
6. Random number generator RNG and its period
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-number-generator-rng-other-examples">
7. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#id9">
8. Random number generator RNG, other examples
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-number-generator-rng-ran0">
9. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#id10">
10. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#id11">
11. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#id12">
12. Random number generator RNG, RAN0
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#random-number-generator-rng-ran0-code">
13. Random number generator RNG, RAN0 code
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter2.html#which-rng-should-i-use">
14. Which RNG should I use?
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter3.html">
15. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter4.html">
16. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter5.html">
17. Logistic Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../../chapter6.html">
18. Neural networks, from the simple perceptron to deep learning
</a>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="../../../_sources/testbook/_build/jupyter_execute/chapter1.ipynb"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.ipynb</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
<ul class="nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#a-well-known-examples-to-illustrate-many-of-the-above-concepts">
A well-known examples to illustrate many of the above concepts
</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="introduction">
<h1>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline"></a></h1>
<p>Classical mechanics is a topic which has been taught intensively over
several centuries. It is, with its many variants and ways of
presenting the educational material, normally the first <strong>real</strong> physics
course many of us meet and it lays the foundation for further physics
studies. Many of the equations and ways of reasoning about the
underlying laws of motion and pertinent forces, shape our approaches and understanding
of the scientific method and discourse, as well as the way we develop our insights
and deeper understanding about physical systems.</p>
<p>There is a wealth of
well-tested (from both a physics point of view and a pedagogical
standpoint) exercises and problems which can be solved
analytically. However, many of these problems represent idealized and
less realistic situations. The large majority of these problems are
solved by paper and pencil and are traditionally aimed
at what we normally refer to as continuous models from which we may find an analytical solution. As a consequence,
when teaching mechanics, it implies that we can seldomly venture beyond an idealized case
in order to develop our understandings and insights about the
underlying forces and laws of motion.</p>
<p>On the other hand, numerical algorithms call for approximate discrete
models and much of the development of methods for continuous models
are nowadays being replaced by methods for discrete models in science and
industry, simply because <strong>much larger classes of problems can be addressed</strong> with discrete models, often by simpler and more
generic methodologies.</p>
<p>As we will see below, when properly scaling the equations at hand,
discrete models open up for more advanced abstractions and the possibility to
study real life systems, with the added bonus that we can explore and
deepen our basic understanding of various physical systems</p>
<p>Analytical solutions are as important as before. In addition, such
solutions provide us with invaluable benchmarks and tests for our
discrete models. Such benchmarks, as we will see below, allow us
to discuss possible sources of errors and their behaviors. And
finally, since most of our models are based on various algorithms from
numerical mathematics, we have a unique oppotunity to gain a deeper
understanding of the mathematical approaches we are using.</p>
<p>With computing and data science as important elements in essentially
all aspects of a modern society, we could then try to define Computing as
<strong>solving scientific problems using all possible tools, including
symbolic computing, computers and numerical algorithms, and analytical
paper and pencil solutions</strong>.
Computing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.</p>
<p>The way we will teach this course reflects
this definition of computing. The course contains both classical paper
and pencil exercises as well as computational projects and exercises. The
hope is that this will allow you to explore the physics of systems
governed by the degrees of freedom of classical mechanics at a deeper
level, and that these insights about the scientific method will help
you to develop a better understanding of how the underlying forces and
equations of motion and how they impact a given system. Furthermore, by introducing various numerical methods
via computational projects and exercises, we aim at developing your competences and skills about these topics.</p>
<p>These competences will enable you to</p>
<ul class="simple">
<li><p>understand how algorithms are used to solve mathematical problems,</p></li>
<li><p>derive, verify, and implement algorithms,</p></li>
<li><p>understand what can go wrong with algorithms,</p></li>
<li><p>use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and</p></li>
<li><p>think algorithmically for the purposes of gaining deeper insights about scientific problems.</p></li>
</ul>
<p>All these elements are central for maturing and gaining a better understanding of the modern scientific process <em>per se</em>.</p>
<p>The power of the scientific method lies in identifying a given problem
as a special case of an abstract class of problems, identifying
general solution methods for this class of problems, and applying a
general method to the specific problem (applying means, in the case of
computing, calculations by pen and paper, symbolic computing, or
numerical computing by ready-made and/or self-written software). This
generic view on problems and methods is particularly important for
understanding how to apply available, generic software to solve a
particular problem.</p>
<p><em>However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.</em></p>
<div class="section" id="a-well-known-examples-to-illustrate-many-of-the-above-concepts">
<h2>A well-known examples to illustrate many of the above concepts<a class="headerlink" href="#a-well-known-examples-to-illustrate-many-of-the-above-concepts" title="Permalink to this headline"></a></h2>
<p>Before we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the
abovementioned topics using an example many of you may have seen before in for example CMSE201.
A simple algorithm for integration is the Trapezoidal rule.
Integration of a function <span class="math notranslate nohighlight">\(f(x)\)</span> by the Trapezoidal Rule is given by following algorithm for an interval <span class="math notranslate nohighlight">\(x \in [a,b]\)</span></p>
<div class="math notranslate nohighlight">
\[
\int_a^b(f(x) dx = \frac{1}{2}\left [f(a)+2f(a+h)+\dots+2f(b-h)+f(b)\right] +O(h^2),
\]</div>
<p>where <span class="math notranslate nohighlight">\(h\)</span> is the so-called stepsize defined by the number of integration points <span class="math notranslate nohighlight">\(N\)</span> as <span class="math notranslate nohighlight">\(h=(b-a)/(n)\)</span>.
Python offers an extremely versatile programming environment, allowing for
the inclusion of analytical studies in a numerical program. Here we show an
example code with the <strong>trapezoidal rule</strong>. We use also <strong>SymPy</strong> to evaluate the exact value of the integral and compute the absolute error
with respect to the numerically evaluated one of the integral
<span class="math notranslate nohighlight">\(\int_0^1 dx x^2 = 1/3\)</span>.
The following code for the trapezoidal rule allows you to plot the relative error by comparing with the exact result. By increasing to <span class="math notranslate nohighlight">\(10^8\)</span> points one arrives at a region where numerical errors start to accumulate.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="k">matplotlib</span> inline
<span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">log10</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">sympy</span> <span class="kn">import</span> <span class="n">Symbol</span><span class="p">,</span> <span class="n">integrate</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="c1"># function for the trapezoidal rule</span>
<span class="k">def</span> <span class="nf">Trapez</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">f</span><span class="p">,</span><span class="n">n</span><span class="p">):</span>
<span class="n">h</span> <span class="o">=</span> <span class="p">(</span><span class="n">b</span><span class="o">-</span><span class="n">a</span><span class="p">)</span><span class="o">/</span><span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">a</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="n">n</span><span class="p">,</span><span class="mi">1</span><span class="p">):</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">x</span><span class="o">+</span><span class="n">h</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">+</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="mf">0.5</span><span class="o">*</span><span class="p">(</span><span class="n">f</span><span class="p">(</span><span class="n">a</span><span class="p">)</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">b</span><span class="p">))</span> <span class="o">+</span><span class="n">s</span>
<span class="k">return</span> <span class="n">h</span><span class="o">*</span><span class="n">s</span>
<span class="c1"># function to compute pi</span>
<span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span>
<span class="c1"># define integration limits</span>
<span class="n">a</span> <span class="o">=</span> <span class="mf">0.0</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mf">1.0</span><span class="p">;</span>
<span class="c1"># find result from sympy</span>
<span class="c1"># define x as a symbol to be used by sympy</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">Symbol</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">)</span>
<span class="n">exact</span> <span class="o">=</span> <span class="n">integrate</span><span class="p">(</span><span class="n">function</span><span class="p">(</span><span class="n">x</span><span class="p">),</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">))</span>
<span class="c1"># set up the arrays for plotting the relative error</span>
<span class="n">n</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="mi">9</span><span class="p">);</span> <span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="mi">9</span><span class="p">);</span>
<span class="c1"># find the relative error as function of integration points</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">1</span><span class="p">):</span>
<span class="n">npts</span> <span class="o">=</span> <span class="mi">10</span><span class="o">**</span><span class="n">i</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">Trapez</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">function</span><span class="p">,</span><span class="n">npts</span><span class="p">)</span>
<span class="n">RelativeError</span> <span class="o">=</span> <span class="nb">abs</span><span class="p">((</span><span class="n">exact</span><span class="o">-</span><span class="n">result</span><span class="p">)</span><span class="o">/</span><span class="n">exact</span><span class="p">)</span>
<span class="n">n</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">log10</span><span class="p">(</span><span class="n">npts</span><span class="p">);</span> <span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">log10</span><span class="p">(</span><span class="n">RelativeError</span><span class="p">);</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">n</span><span class="p">,</span><span class="n">y</span><span class="p">,</span> <span class="s1">&#39;ro&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s1">&#39;n&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s1">&#39;Relative error&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../../_images/chapter1_3_0.png" src="../../../_images/chapter1_3_0.png" />
</div>
</div>
<p>This example shows the potential of combining numerical algorithms with symbolic calculations, allowing us to</p>
<ul class="simple">
<li><p>Validate and verify their algorithms.</p></li>
<li><p>Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.</p></li>
<li><p>Validation and verification are then included <em>naturally</em> and one can develop a better attitude to what is meant with an ethically sound scientific approach.</p></li>
<li><p>The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get <strong>trained from day one to think error analysis</strong>.</p></li>
<li><p>With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks.</p></li>
</ul>
<p>In this process we can easily bake in</p>
<ol class="simple">
<li><p>How to structure a code in terms of functions</p></li>
<li><p>How to make a module</p></li>
<li><p>How to read input data flexibly from the command line</p></li>
<li><p>How to create graphical/web user interfaces</p></li>
<li><p>How to write unit tests (test functions or doctests)</p></li>
<li><p>How to refactor code in terms of classes (instead of functions only)</p></li>
<li><p>How to conduct and automate large-scale numerical experiments</p></li>
<li><p>How to write scientific reports in various formats (LaTeX, HTML)</p></li>
</ol>
<p>The conventions and techniques outlined here will save you a lot of time when you incrementally extend software over time from simpler to more complicated problems. In particular, you will benefit from many good habits:</p>
<ol class="simple">
<li><p>New code is added in a modular fashion to a library (modules)</p></li>
<li><p>Programs are run through convenient user interfaces</p></li>
<li><p>It takes one quick command to let all your code undergo heavy testing</p></li>
<li><p>Tedious manual work with running programs is automated,</p></li>
<li><p>Your scientific investigations are reproducible, scientific reports with top quality typesetting are produced both for paper and electronic devices.</p></li>
</ol>
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./testbook/_build/jupyter_execute"
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="../../../_static/js/index.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More