This commit is contained in:
Morten Hjorth-Jensen
2021-12-08 06:59:22 +01:00
parent d760cdfa85
commit 7ca589a654
94 changed files with 23333 additions and 2210 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 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: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 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: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 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
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,649 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "c3edcae5",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html clustering.do.txt -->"
]
},
{
"cell_type": "markdown",
"id": "4102577e",
"metadata": {
"editable": true
},
"source": [
"# Clustering and Unsupervised Learning\n",
"\n",
"In general terms cluster analysis, or clustering, is the task of grouping a\n",
"data-set into different distinct categories based on some measure of equality of\n",
"the data. This measure is often referred to as a **metric** or **similarity\n",
"measure** in the literature (note: sometimes we deal with a **dissimilarity\n",
"measure** instead). Usually, these metrics are formulated as some kind of\n",
"distance function between points in a high-dimensional space.\n",
"\n",
"The simplest, and also the most\n",
"common is the **Euclidean distance**.\n",
"\n",
"The simplest of all clustering algorithms is the **k-means algorithm**\n",
", sometimes also referred to as *Lloyds algorithm*. It is the simplest and also\n",
"the most common. From its simplicity it obtains both strengths and weaknesses.\n",
"These will be discussed in more detail later. The $k$-means algorithm is a\n",
"**centroid based** clustering algorithm.\n",
"\n",
"Assume, we are given $n$ data points and we wish to split the data into $K < n$\n",
"different categories, or clusters. We label each cluster by an integer"
]
},
{
"cell_type": "markdown",
"id": "0deb3255",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"k\\in\\{1, \\cdots, K \\}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "cfd8fe00",
"metadata": {
"editable": true
},
"source": [
"In the basic k-means algorithm each point is assigned to only\n",
"one cluster $k$, and these assignments are *non-injective* i.e. many-to-one. We\n",
"can think of these mappings as an encoder $k = C(i)$, which assigns the $i$-th\n",
"data-point $\\bf x_i$ to the $k$-th cluster.\n",
"\n",
"$k$-means algorithm in words:\n",
"1. We start with guesses / random initializations of our $k$ cluster centers/centroids\n",
"\n",
"2. For each centroid the points that are most similar are identified\n",
"\n",
"3. Then we move / replace each centroid with a coordinate average of all the points that were assigned to that centroid.\n",
"\n",
"4. Iterate 2-3 until the centroids no longer move (to some tolerance)\n",
"\n",
"We assume we have $n$ data-points"
]
},
{
"cell_type": "markdown",
"id": "a29b7459",
"metadata": {
"editable": true
},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"eq:kmeanspoints\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\\label{eq:kmeanspoints} \\tag{1}\n",
" \\boldsymbol{x_i} = \\{x_{i, 1}, \\cdots, x_{i, p}\\}\\in\\mathbb{R}^p.\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "98f9e37b",
"metadata": {
"editable": true
},
"source": [
"which we wish to group into $K < n$ clusters. For our dissimilarity measure we\n",
"use the *squared Euclidean distance*"
]
},
{
"cell_type": "markdown",
"id": "d3c32572",
"metadata": {
"editable": true
},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"eq:squaredeuclidean\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\\label{eq:squaredeuclidean} \\tag{2}\n",
" d(\\boldsymbol{x_i}, \\boldsymbol{x_i'}) = \\sum_{j=1}^p(x_{ij} - x_{i'j})^2\n",
" = ||\\boldsymbol{x_i} - \\boldsymbol{x_{i'}}||^2\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "29d24648",
"metadata": {
"editable": true
},
"source": [
"We define the so called *within-cluster point scatter* which gives us a\n",
"measure of how close each data point assigned to the same cluster tends to be to\n",
"the all the others."
]
},
{
"cell_type": "markdown",
"id": "fce5c797",
"metadata": {
"editable": true
},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"eq:withincluster\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\\label{eq:withincluster} \\tag{3}\n",
" W(C) = \\frac{1}{2}\\sum_{k=1}^K\\sum_{C(i)=k}\n",
" \\sum_{C(i')=k}d(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}}) =\n",
" \\sum_{k=1}^KN_k\\sum_{C(i)=k}||\\boldsymbol{x_i} - \\boldsymbol{\\overline{x_k}}||^2\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "674a26b7",
"metadata": {
"editable": true
},
"source": [
"where $\\boldsymbol{\\overline{x_k}}$ is the mean vector associated with the $k$-th\n",
"cluster, and $N_k = \\sum_{i=1}^nI(C(i) = k)$, where the $I()$ notation is\n",
"similar to the Kronecker delta (*Commonly used in statistics, it just means that\n",
"when $i = k$ we have the encoder $C(i)$*). In other words, the within-cluster\n",
"scatter measures the compactness of each cluster with respect to the data points\n",
"assigned to each cluster. This is the quantity that the $k$-means algorithm aims\n",
"to minimize. We refer to this quantity $W(C)$ as the within cluster scatter\n",
"because of its relation to the *total scatter*.\n",
"\n",
"We have"
]
},
{
"cell_type": "markdown",
"id": "f200e7ff",
"metadata": {
"editable": true
},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"eq:totalscatter\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\\label{eq:totalscatter} \\tag{4}\n",
" T = W(C) + B(C) = \\frac{1}{2}\\sum_{i=1}^n\n",
" \\sum_{i'=1}^nd(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}})\n",
" = \\frac{1}{2}\\sum_{k=1}^K\\sum_{C(i)=k}\n",
" \\Big(\\sum_{C(i') = k}d(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}})\n",
" + \\sum_{C(i')\\neq k}d(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}})\\Big).\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "5471a94d",
"metadata": {
"editable": true
},
"source": [
"This is a quantity that is conserved throughout the $k$-means algorithm. It can\n",
"be thought of as the total amount of information in the data, and it is composed\n",
"of the aforementioned within-cluster scatter and the *between-cluster scatter*\n",
"$B(C)$. In methods such as principle component analysis the total scatter is not\n",
"conserved.\n",
"\n",
"Given a cluster mean $\\boldsymbol{m_k}$ we define the **total cluster variance**"
]
},
{
"cell_type": "markdown",
"id": "299a99ce",
"metadata": {
"editable": true
},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"eq:totalclustervariance\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\\label{eq:totalclustervariance} \\tag{5}\n",
" \\min_{C, \\{\\boldsymbol{m_k}\\}_1^K}\\sum_{k=1}^KN_k\\sum||\\boldsymbol{x_i} - \\boldsymbol{m_k}||^2\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "bdfa54ee",
"metadata": {
"editable": true
},
"source": [
"Now we have all the pieces necessary to formally revisit the $k$-means algorithm.\n",
"\n",
"The $k$-means clustering algorithm goes as follows \n",
"\n",
"1. For a given cluster assignment $C$, and $k$ cluster means $\\left\\{m_1, \\cdots, m_k\\right\\}$. We minimize the total cluster variance with respect to the cluster means $\\{m_k\\}$ yielding the means of the currently assigned clusters.\n",
"\n",
"2. Given a current set of $k$ means $\\{m_k\\}$ the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $$C(i) = \\underset{1\\leq k\\leq K}{\\mathrm{argmin}} ||\\boldsymbol{x_i} - \\boldsymbol{m_k}||^2$$\n",
"\n",
"3. Steps 1 and 2 are repeated until the assignments do not change."
]
},
{
"cell_type": "markdown",
"id": "f5def86c",
"metadata": {
"editable": true
},
"source": [
"## Codes and Approaches\n",
"\n",
"1. Before we start we specify a number $k$ which is the number of clusters we want to try to separate our data into.\n",
"\n",
"2. We initially choose $k$ random data points in our data as our initial centroids, *or means* (this is where the name comes from).\n",
"\n",
"3. Assign each data point to their closest centroid, based on the squared Euclidean distance.\n",
"\n",
"4. For each of the $k$ cluster we update the centroid by calculating new mean values for all the data points in the cluster.\n",
"\n",
"5. Iteratively minimize the within cluster scatter by performing steps (3, 4) until the new assignments stop changing (can be to some tolerance) or until a maximum number of iterations have passed.\n",
"\n",
"Let us now program the most basic version of the algorithm using nothing but\n",
"Python with numpy arrays. This code is kept intentionally simple to gradually\n",
"progress our understanding. There is no vectorization of any kind, and even most\n",
"helper functions are not utilized.\n",
"\n",
"We need first a dataset to do our cluster analysis on. In our case\n",
"this is a plain *vanilla* data set using random numbers using a\n",
"Gaussian distribution."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "b0260188",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"import time\n",
"import numpy as np\n",
"import tensorflow as tf\n",
"from matplotlib import image\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.cluster import KMeans\n",
"from IPython.display import display\n",
"\n",
"np.random.seed(2021)"
]
},
{
"cell_type": "markdown",
"id": "fe680e35",
"metadata": {
"editable": true
},
"source": [
"Next we define functions, for ease of use later, to generate Gaussians and to\n",
"set up our toy data set."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "9db2bbce",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def gaussian_points(dim=2, n_points=1000, mean_vector=np.array([0, 0]),\n",
" sample_variance=1):\n",
" \"\"\"\n",
" Very simple custom function to generate gaussian distributed point clusters\n",
" with variable dimension, number of points, means in each direction\n",
" (must match dim) and sample variance.\n",
"\n",
" Inputs:\n",
" dim (int)\n",
" n_points (int)\n",
" mean_vector (np.array) (where index 0 is x, index 1 is y etc.)\n",
" sample_variance (float)\n",
"\n",
" Returns:\n",
" data (np.array): with dimensions (dim x n_points)\n",
" \"\"\"\n",
"\n",
" mean_matrix = np.zeros(dim) + mean_vector\n",
" covariance_matrix = np.eye(dim) * sample_variance\n",
" data = np.random.multivariate_normal(mean_matrix, covariance_matrix,\n",
" n_points)\n",
" return data\n",
"\n",
"\n",
"\n",
"def generate_simple_clustering_dataset(dim=2, n_points=1000, plotting=True,\n",
" return_data=True):\n",
" \"\"\"\n",
" Toy model to illustrate k-means clustering\n",
" \"\"\"\n",
"\n",
" data1 = gaussian_points(mean_vector=np.array([5, 5]))\n",
" data2 = gaussian_points()\n",
" data3 = gaussian_points(mean_vector=np.array([1, 4.5]))\n",
" data4 = gaussian_points(mean_vector=np.array([5, 1]))\n",
" data = np.concatenate((data1, data2, data3, data4), axis=0)\n",
"\n",
" if plotting:\n",
" fig, ax = plt.subplots()\n",
" ax.scatter(data[:, 0], data[:, 1], alpha=0.2)\n",
" ax.set_title('Toy Model Dataset')\n",
" plt.show()\n",
"\n",
"\n",
" if return_data:\n",
" return data\n",
"\n",
"\n",
"data = generate_simple_clustering_dataset()"
]
},
{
"cell_type": "markdown",
"id": "c0bb8c76",
"metadata": {
"editable": true
},
"source": [
"With the above dataset we start\n",
"implementing the $k$-means algorithm."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "29a75065",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"\n",
"n_samples, dimensions = data.shape\n",
"n_clusters = 4\n",
"\n",
"# we randomly initialize our centroids\n",
"np.random.seed(2021)\n",
"centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]\n",
"distances = np.zeros((n_samples, n_clusters))\n",
"\n",
"# first we need to calculate the distance to each centroid from our data\n",
"for k in range(n_clusters):\n",
" for n in range(n_samples):\n",
" dist = 0\n",
" for d in range(dimensions):\n",
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
" distances[n, k] = dist\n",
"\n",
"# we initialize an array to keep track of to which cluster each point belongs\n",
"# the way we set it up here the index tracks which point and the value which\n",
"# cluster the point belongs to\n",
"cluster_labels = np.zeros(n_samples, dtype='int')\n",
"\n",
"# next we loop through our samples and for every point assign it to the cluster\n",
"# to which it has the smallest distance to\n",
"for n in range(n_samples):\n",
" # tracking variables (all of this is basically just an argmin)\n",
" smallest = 1e10\n",
" smallest_row_index = 1e10\n",
" for k in range(n_clusters):\n",
" if distances[n, k] < smallest:\n",
" smallest = distances[n, k]\n",
" smallest_row_index = k\n",
"\n",
" cluster_labels[n] = smallest_row_index"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "9fae7fc9",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"fig = plt.figure()\n",
"ax = fig.add_subplot()\n",
"unique_cluster_labels = np.unique(cluster_labels)\n",
"for i in unique_cluster_labels:\n",
" ax.scatter(data[cluster_labels == i, 0],\n",
" data[cluster_labels == i, 1],\n",
" label = i,\n",
" alpha = 0.2)\n",
" ax.scatter(centroids[:, 0], centroids[:, 1], c='black')\n",
"\n",
"ax.set_title(\"First Grouping of Points to Centroids\")\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "90d2a873",
"metadata": {
"editable": true
},
"source": [
"So what do we have so far? We have 'picked' $k$ centroids at random from our\n",
"data points. There are other ways of more intelligently choosing their\n",
"initializations, however for our purposes randomly is fine. Then we have\n",
"initialized an array 'distances' which holds the information of the distance,\n",
"*or dissimilarity*, of every point to of our centroids. Finally, we have\n",
"initialized an array 'cluster_labels' which according to our distances array\n",
"holds the information of to which centroid every point is assigned. This was the\n",
"first pass of our algorithm. Essentially, all we need to do now is repeat the\n",
"distance and assignment steps above until we have reached a desired convergence\n",
"or a maximum amount of iterations."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "378c29fc",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"\n",
"max_iterations = 100\n",
"tolerance = 1e-8\n",
"\n",
"for iteration in range(max_iterations):\n",
" prev_centroids = centroids.copy()\n",
" for k in range(n_clusters):\n",
" # this array will be used to update our centroid positions\n",
" vector_mean = np.zeros(dimensions)\n",
" mean_divisor = 0\n",
" for n in range(n_samples):\n",
" if cluster_labels[n] == k:\n",
" vector_mean += data[n, :]\n",
" mean_divisor += 1\n",
"\n",
" # update according to the k means\n",
" centroids[k, :] = vector_mean / mean_divisor\n",
"\n",
" # we find the dissimilarity\n",
" for k in range(n_clusters):\n",
" for n in range(n_samples):\n",
" dist = 0\n",
" for d in range(dimensions):\n",
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
" distances[n, k] = dist\n",
"\n",
" # assign each point\n",
" for n in range(n_samples):\n",
" smallest = 1e10\n",
" smallest_row_index = 1e10\n",
" for k in range(n_clusters):\n",
" if distances[n, k] < smallest:\n",
" smallest = distances[n, k]\n",
" smallest_row_index = k\n",
"\n",
" cluster_labels[n] = smallest_row_index\n",
"\n",
" # convergence criteria\n",
" centroid_difference = np.sum(np.abs(centroids - prev_centroids))\n",
" if centroid_difference < tolerance:\n",
" print(f'Converged at iteration {iteration}')\n",
" break\n",
"\n",
" elif iteration == max_iterations:\n",
" print(f'Did not converge in {max_iterations} iterations')"
]
},
{
"cell_type": "markdown",
"id": "545a6742",
"metadata": {
"editable": true
},
"source": [
"We now have a simple , un-optimized $k$-means\n",
"clustering implementation. Lets plot the final result"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "d9d3973b",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"fig = plt.figure()\n",
"ax = fig.add_subplot()\n",
"unique_cluster_labels = np.unique(cluster_labels)\n",
"for i in unique_cluster_labels:\n",
" ax.scatter(data[cluster_labels == i, 0],\n",
" data[cluster_labels == i, 1],\n",
" label = i,\n",
" alpha = 0.2)\n",
" ax.scatter(centroids[:, 0], centroids[:, 1], c='black')\n",
"\n",
"ax.set_title(\"Final Result of K-means Clustering\")\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "ee6a145f",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def naive_kmeans(data, n_clusters=4, max_iterations=100, tolerance=1e-8):\n",
" start_time = time.time()\n",
"\n",
" n_samples, dimensions = data.shape\n",
" n_clusters = 4\n",
" #np.random.seed(2021)\n",
" centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]\n",
" distances = np.zeros((n_samples, n_clusters))\n",
"\n",
" for k in range(n_clusters):\n",
" for n in range(n_samples):\n",
" dist = 0\n",
" for d in range(dimensions):\n",
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
" distances[n, k] = dist\n",
"\n",
" cluster_labels = np.zeros(n_samples, dtype='int')\n",
"\n",
" for n in range(n_samples):\n",
" smallest = 1e10\n",
" smallest_row_index = 1e10\n",
" for k in range(n_clusters):\n",
" if distances[n, k] < smallest:\n",
" smallest = distances[n, k]\n",
" smallest_row_index = k\n",
"\n",
" cluster_labels[n] = smallest_row_index\n",
"\n",
" for iteration in range(max_iterations):\n",
" prev_centroids = centroids.copy()\n",
" for k in range(n_clusters):\n",
" vector_mean = np.zeros(dimensions)\n",
" mean_divisor = 0\n",
" for n in range(n_samples):\n",
" if cluster_labels[n] == k:\n",
" vector_mean += data[n, :]\n",
" mean_divisor += 1\n",
"\n",
" centroids[k, :] = vector_mean / mean_divisor\n",
"\n",
" for k in range(n_clusters):\n",
" for n in range(n_samples):\n",
" dist = 0\n",
" for d in range(dimensions):\n",
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
" distances[n, k] = dist\n",
"\n",
" for n in range(n_samples):\n",
" smallest = 1e10\n",
" smallest_row_index = 1e10\n",
" for k in range(n_clusters):\n",
" if distances[n, k] < smallest:\n",
" smallest = distances[n, k]\n",
" smallest_row_index = k\n",
"\n",
" cluster_labels[n] = smallest_row_index\n",
"\n",
" centroid_difference = np.sum(np.abs(centroids - prev_centroids))\n",
" if centroid_difference < tolerance:\n",
" print(f'Converged at iteration {iteration}')\n",
" print(f'Runtime: {time.time() - start_time} seconds')\n",
"\n",
" return cluster_labels, centroids\n",
"\n",
" print(f'Did not converge in {max_iterations} iterations')\n",
" print(f'Runtime: {time.time() - start_time} seconds')\n",
"\n",
" return cluster_labels, centroids"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
+156 -147
View File
@@ -5,7 +5,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>13. Building a Feed Forward Neural Network &#8212; Applied Data Analysis and Machine Learning</title>
<title>14. Building a Feed Forward Neural Network &#8212; Applied Data Analysis and Machine Learning</title>
<link href="_static/css/theme.css" rel="stylesheet" />
<link href="_static/css/index.c5995385ac14fb8791e8eb36b4908be2.css" rel="stylesheet" />
@@ -53,8 +53,8 @@
<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="14. Solving Differential Equations with Deep Learning" href="chapter11.html" />
<link rel="prev" title="12. Neural networks" href="chapter9.html" />
<link rel="next" title="15. Solving Differential Equations with Deep Learning" href="chapter11.html" />
<link rel="prev" title="13. Neural networks" href="chapter9.html" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="docsearch:language" content="en" />
@@ -199,6 +199,11 @@
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="clustering.html">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
@@ -208,17 +213,27 @@
<ul class="current nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter9.html">
12. Neural networks
13. Neural networks
</a>
</li>
<li class="toctree-l1 current active">
<a class="current reference internal" href="#">
13. Building a Feed Forward Neural Network
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter11.html">
14. Solving Differential Equations with Deep Learning
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
@@ -294,151 +309,151 @@
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#defining-the-cost-function">
13.1. Defining the cost function
14.1. Defining the cost function
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#example-binary-classification-problem">
13.1.1. Example: binary classification problem
14.1.1. Example: binary classification problem
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-softmax-function">
13.1.2. The Softmax function
14.1.2. The Softmax function
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#developing-a-code-for-doing-neural-networks-with-back-propagation">
13.2. Developing a code for doing neural networks with back propagation
14.2. Developing a code for doing neural networks with back propagation
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#collect-and-pre-process-data">
13.2.1. Collect and pre-process data
14.2.1. Collect and pre-process data
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#train-and-test-datasets">
13.2.2. Train and test datasets
14.2.2. Train and test datasets
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#define-model-and-architecture">
13.2.3. Define model and architecture
14.2.3. Define model and architecture
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#layers">
13.2.4. Layers
14.2.4. Layers
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#feed-forward-pass">
13.2.5. Feed-forward pass
14.2.5. Feed-forward pass
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#choose-cost-function-and-optimizer">
13.2.6. Choose cost function and optimizer
14.2.6. Choose cost function and optimizer
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#optimizing-the-cost-function">
13.2.7. Optimizing the cost function
14.2.7. Optimizing the cost function
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#regularization">
13.2.8. Regularization
14.2.8. Regularization
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#matrix-multiplication">
13.2.9. Matrix multiplication
14.2.9. Matrix multiplication
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#improving-performance">
13.3. Improving performance
14.3. Improving performance
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#evaluate-model-performance-on-test-data">
13.4. Evaluate model performance on test data
14.4. Evaluate model performance on test data
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#adjust-hyperparameters">
13.5. Adjust hyperparameters
14.5. Adjust hyperparameters
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#visualization">
13.6. Visualization
14.6. Visualization
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#scikit-learn-implementation">
13.7. scikit-learn implementation
14.7. scikit-learn implementation
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#id1">
13.8. Visualization
14.8. Visualization
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#building-neural-networks-in-tensorflow-and-keras">
13.9. Building neural networks in Tensorflow and Keras
14.9. Building neural networks in Tensorflow and Keras
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-breast-cancer-data-now-with-keras">
13.10. The Breast Cancer Data, now with Keras
14.10. The Breast Cancer Data, now with Keras
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#fine-tuning-neural-network-hyperparameters">
13.11. Fine-tuning neural network hyperparameters
14.11. Fine-tuning neural network hyperparameters
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#which-activation-function-should-i-use">
13.12. Which activation function should I use?
14.12. Which activation function should I use?
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-relu-function-family">
13.13. The RELU function family
14.13. The RELU function family
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#batch-normalization">
13.14. Batch Normalization
14.14. Batch Normalization
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#dropout">
13.15. Dropout
14.15. Dropout
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#gradient-clipping">
13.16. Gradient Clipping
14.16. Gradient Clipping
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#a-top-down-perspective-on-neural-networks">
13.17. A top-down perspective on Neural networks
14.17. A top-down perspective on Neural networks
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#limitations-of-supervised-learning-with-deep-networks">
13.18. Limitations of supervised learning with deep networks
14.18. Limitations of supervised learning with deep networks
</a>
</li>
</ul>
@@ -452,8 +467,9 @@
<div>
<div class="tex2jax_ignore mathjax_ignore section" id="building-a-feed-forward-neural-network">
<h1><span class="section-number">13. </span>Building a Feed Forward Neural Network<a class="headerlink" href="#building-a-feed-forward-neural-network" title="Permalink to this headline"></a></h1>
<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
doconce format html chapter10.do.txt --no_mako --><div class="tex2jax_ignore mathjax_ignore section" id="building-a-feed-forward-neural-network">
<h1><span class="section-number">14. </span>Building a Feed Forward Neural Network<a class="headerlink" href="#building-a-feed-forward-neural-network" title="Permalink to this headline"></a></h1>
<p>We are now gong to develop an example based on the MNIST data
base. This is a classification problem and we need to use our
cross-entropy function we discussed in connection with logistic
@@ -481,7 +497,7 @@ P(y = 1 \mid \hat{x}, \hat{\theta}) = 1 - P(y = 0 \mid \hat{x}, \hat{\theta}) ,
<p>where <span class="math notranslate nohighlight">\(y \in \{0, 1\}\)</span> and <span class="math notranslate nohighlight">\(\hat{\theta}\)</span> represents the weights and biases
of our network.</p>
<div class="section" id="defining-the-cost-function">
<h2><span class="section-number">13.1. </span>Defining the cost function<a class="headerlink" href="#defining-the-cost-function" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.1. </span>Defining the cost function<a class="headerlink" href="#defining-the-cost-function" title="Permalink to this headline"></a></h2>
<p>Our cost function is given as (see the Logistic regression lectures)</p>
<div class="math notranslate nohighlight">
\[
@@ -519,7 +535,7 @@ P(\mathcal{D} \mid \hat{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1
<p>See the logistic regression lectures for a full definition of the cost function.</p>
<p>The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!</p>
<div class="section" id="example-binary-classification-problem">
<h3><span class="section-number">13.1.1. </span>Example: binary classification problem<a class="headerlink" href="#example-binary-classification-problem" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.1.1. </span>Example: binary classification problem<a class="headerlink" href="#example-binary-classification-problem" title="Permalink to this headline"></a></h3>
<p>As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters <span class="math notranslate nohighlight">\(\beta\)</span> as</p>
<div class="math notranslate nohighlight">
\[
@@ -561,7 +577,7 @@ Our cost function at the final layer <span class="math notranslate nohighlight">
<p>In case we use another activation function than the logistic one, we need to evaluate other derivatives.</p>
</div>
<div class="section" id="the-softmax-function">
<h3><span class="section-number">13.1.2. </span>The Softmax function<a class="headerlink" href="#the-softmax-function" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.1.2. </span>The Softmax function<a class="headerlink" href="#the-softmax-function" title="Permalink to this headline"></a></h3>
<p>In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation <span class="math notranslate nohighlight">\(z_i^l\)</span>, that is we need</p>
<div class="math notranslate nohighlight">
\[
@@ -582,7 +598,7 @@ f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}.
</div>
</div>
<div class="section" id="developing-a-code-for-doing-neural-networks-with-back-propagation">
<h2><span class="section-number">13.2. </span>Developing a code for doing neural networks with back propagation<a class="headerlink" href="#developing-a-code-for-doing-neural-networks-with-back-propagation" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.2. </span>Developing a code for doing neural networks with back propagation<a class="headerlink" href="#developing-a-code-for-doing-neural-networks-with-back-propagation" title="Permalink to this headline"></a></h2>
<p>One can identify a set of key steps when using neural networks to solve supervised learning problems:</p>
<ol class="simple">
<li><p>Collect and pre-process data</p></li>
@@ -593,7 +609,7 @@ f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}.
<li><p>Adjust hyperparameters (if necessary, network architecture)</p></li>
</ol>
<div class="section" id="collect-and-pre-process-data">
<h3><span class="section-number">13.2.1. </span>Collect and pre-process data<a class="headerlink" href="#collect-and-pre-process-data" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.1. </span>Collect and pre-process data<a class="headerlink" href="#collect-and-pre-process-data" title="Permalink to this headline"></a></h3>
<p>Here we will be using the MNIST dataset, which is readily available through the <strong>scikit-learn</strong>
package. You may also find it for example <a class="reference external" href="http://yann.lecun.com/exdb/mnist/">here</a>.<br />
The <em>MNIST</em> (Modified National Institute of Standards and Technology) database is a large database
@@ -683,12 +699,12 @@ labels = (n_inputs) = (1797,)
X = (n_inputs, n_features) = (1797, 64)
</pre></div>
</div>
<img alt="_images/chapter10_33_1.png" src="_images/chapter10_33_1.png" />
<img alt="_images/chapter10_39_1.png" src="_images/chapter10_39_1.png" />
</div>
</div>
</div>
<div class="section" id="train-and-test-datasets">
<h3><span class="section-number">13.2.2. </span>Train and test datasets<a class="headerlink" href="#train-and-test-datasets" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.2. </span>Train and test datasets<a class="headerlink" href="#train-and-test-datasets" title="Permalink to this headline"></a></h3>
<p>Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.</p>
<p>We will reserve <span class="math notranslate nohighlight">\(80 \%\)</span> of our dataset for training and <span class="math notranslate nohighlight">\(20 \%\)</span> for testing.</p>
<p>It is important that the train and test datasets are drawn randomly from our dataset, to ensure
@@ -737,7 +753,7 @@ Number of test images: 360
</div>
</div>
<div class="section" id="define-model-and-architecture">
<h3><span class="section-number">13.2.3. </span>Define model and architecture<a class="headerlink" href="#define-model-and-architecture" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.3. </span>Define model and architecture<a class="headerlink" href="#define-model-and-architecture" title="Permalink to this headline"></a></h3>
<p>Our simple feed-forward neural network will consist of an <em>input</em> layer, a single <em>hidden</em> layer and an <em>output</em> layer. The activation <span class="math notranslate nohighlight">\(y\)</span> of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have</p>
<div class="math notranslate nohighlight">
\[ z = \sum_{i=1}^n w_i a_i ,\]</div>
@@ -767,7 +783,7 @@ We will be using the sigmoid function <span class="math notranslate nohighlight"
<p>which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.</p>
</div>
<div class="section" id="layers">
<h3><span class="section-number">13.2.4. </span>Layers<a class="headerlink" href="#layers" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.4. </span>Layers<a class="headerlink" href="#layers" title="Permalink to this headline"></a></h3>
<ul class="simple">
<li><p>Input</p></li>
</ul>
@@ -824,7 +840,7 @@ of values. Without it, any input with the value 0 will be mapped to zero (before
</div>
</div>
<div class="section" id="feed-forward-pass">
<h3><span class="section-number">13.2.5. </span>Feed-forward pass<a class="headerlink" href="#feed-forward-pass" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.5. </span>Feed-forward pass<a class="headerlink" href="#feed-forward-pass" title="Permalink to this headline"></a></h3>
<p>Denote <span class="math notranslate nohighlight">\(F\)</span> the number of features, <span class="math notranslate nohighlight">\(H\)</span> the number of hidden neurons and <span class="math notranslate nohighlight">\(C\)</span> the number of categories.<br />
For each input image we calculate a weighted sum of input features (pixel values) to each neuron <span class="math notranslate nohighlight">\(j\)</span> in the hidden layer <span class="math notranslate nohighlight">\(l\)</span>:</p>
<div class="math notranslate nohighlight">
@@ -917,7 +933,7 @@ correct label for image 0: 6
</div>
</div>
<div class="section" id="choose-cost-function-and-optimizer">
<h3><span class="section-number">13.2.6. </span>Choose cost function and optimizer<a class="headerlink" href="#choose-cost-function-and-optimizer" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.6. </span>Choose cost function and optimizer<a class="headerlink" href="#choose-cost-function-and-optimizer" title="Permalink to this headline"></a></h3>
<p>To measure how well our neural network is doing we need to introduce a cost function.<br />
We will call the function that gives the error of a single sample output the <em>loss</em> function, and the function
that gives the total error of our network across all samples the <em>cost</em> function.
@@ -936,7 +952,7 @@ probability of the correct category <span class="math notranslate nohighlight">\
you got the correct label. The probability of category <span class="math notranslate nohighlight">\(c\)</span> is given by the softmax function. The vector <span class="math notranslate nohighlight">\(\hat{\theta}\)</span> represents the parameters of our network, i.e. all the weights and biases.</p>
</div>
<div class="section" id="optimizing-the-cost-function">
<h3><span class="section-number">13.2.7. </span>Optimizing the cost function<a class="headerlink" href="#optimizing-the-cost-function" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.7. </span>Optimizing the cost function<a class="headerlink" href="#optimizing-the-cost-function" title="Permalink to this headline"></a></h3>
<p>The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is <em>gradient descent</em> and its generalizations. The idea behind gradient descent
is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a <em>local</em> minimum of the cost function.<br />
Each parameter <span class="math notranslate nohighlight">\(\theta\)</span> is iteratively adjusted according to the rule</p>
@@ -962,7 +978,7 @@ We denote each minibatch <span class="math notranslate nohighlight">\(B_k\)</spa
<p>The various optmization methods, with codes and algorithms, are discussed in our lectures on <a class="reference external" href="https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html">Gradient descent approaches</a>.</p>
</div>
<div class="section" id="regularization">
<h3><span class="section-number">13.2.8. </span>Regularization<a class="headerlink" href="#regularization" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.8. </span>Regularization<a class="headerlink" href="#regularization" title="Permalink to this headline"></a></h3>
<p>It is common to add an extra term to the cost function, proportional
to the size of the weights. This is equivalent to constraining the
size of the weights, so that they do not grow out of control.
@@ -985,7 +1001,7 @@ above. This is a clever use of the chain rule that allows us to
calculate the gradient efficently.</p>
</div>
<div class="section" id="matrix-multiplication">
<h3><span class="section-number">13.2.9. </span>Matrix multiplication<a class="headerlink" href="#matrix-multiplication" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">14.2.9. </span>Matrix multiplication<a class="headerlink" href="#matrix-multiplication" title="Permalink to this headline"></a></h3>
<p>To more efficently train our network these equations are implemented using matrix operations.<br />
The error in the output layer is calculated simply as, with <span class="math notranslate nohighlight">\(\hat{t}\)</span> being our targets,</p>
<div class="math notranslate nohighlight">
@@ -1086,7 +1102,7 @@ the <em>Hadamard product</em>, meaning element-wise multiplication.</p>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Old accuracy on training data: 0.1440501043841336
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1098,7 +1114,7 @@ the <em>Hadamard product</em>, meaning element-wise multiplication.</p>
</div>
</div>
<div class="section" id="improving-performance">
<h2><span class="section-number">13.3. </span>Improving performance<a class="headerlink" href="#improving-performance" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.3. </span>Improving performance<a class="headerlink" href="#improving-performance" title="Permalink to this headline"></a></h2>
<p>As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image.<br />
In order to obtain a network that does something useful, we will have to do a bit more work.</p>
<p>The choice of <em>hyperparameters</em> such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a <em>grid-search</em> is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates <span class="math notranslate nohighlight">\(\eta = 10^{-6}, 10^{-5},...,10^{-1}\)</span> with different regularization parameters <span class="math notranslate nohighlight">\(\lambda = 10^{-6},...,10^{-0}\)</span>.</p>
@@ -1215,7 +1231,7 @@ being realizations of this object with different hyperparameters. An implementat
</div>
</div>
<div class="section" id="evaluate-model-performance-on-test-data">
<h2><span class="section-number">13.4. </span>Evaluate model performance on test data<a class="headerlink" href="#evaluate-model-performance-on-test-data" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.4. </span>Evaluate model performance on test data<a class="headerlink" href="#evaluate-model-performance-on-test-data" title="Permalink to this headline"></a></h2>
<p>To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data.<br />
We measure the performance of the network using the <em>accuracy</em> score.<br />
The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of <span class="math notranslate nohighlight">\(1\)</span>.</p>
@@ -1251,7 +1267,7 @@ The accuracy is as you would expect just the number of images correctly labeled
</div>
</div>
<div class="section" id="adjust-hyperparameters">
<h2><span class="section-number">13.5. </span>Adjust hyperparameters<a class="headerlink" href="#adjust-hyperparameters" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.5. </span>Adjust hyperparameters<a class="headerlink" href="#adjust-hyperparameters" title="Permalink to this headline"></a></h2>
<p>We now perform a grid search to find the optimal hyperparameters for the network.<br />
Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around <span class="math notranslate nohighlight">\(98\%\)</span> (<span class="math notranslate nohighlight">\(2\%\)</span> error rate).</p>
<div class="cell docutils container">
@@ -1420,7 +1436,7 @@ Lambda = 10.0
Accuracy score on test set: 0.21944444444444444
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1429,7 +1445,7 @@ Lambda = 1e-05
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1438,7 +1454,7 @@ Lambda = 0.0001
Accuracy score on test set: 0.10555555555555556
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1447,7 +1463,7 @@ Lambda = 0.001
Accuracy score on test set: 0.08888888888888889
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1456,7 +1472,7 @@ Lambda = 0.01
Accuracy score on test set: 0.11388888888888889
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1465,7 +1481,7 @@ Lambda = 0.1
Accuracy score on test set: 0.08611111111111111
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1474,7 +1490,7 @@ Lambda = 1.0
Accuracy score on test set: 0.125
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1483,11 +1499,11 @@ Lambda = 10.0
Accuracy score on test set: 0.09166666666666666
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1496,11 +1512,11 @@ Lambda = 1e-05
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1509,11 +1525,11 @@ Lambda = 0.0001
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1522,11 +1538,11 @@ Lambda = 0.001
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1535,11 +1551,11 @@ Lambda = 0.01
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1548,7 +1564,7 @@ Lambda = 0.1
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
@@ -1557,11 +1573,11 @@ Lambda = 1.0
Accuracy score on test set: 0.125
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1570,11 +1586,11 @@ Lambda = 10.0
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1583,11 +1599,11 @@ Lambda = 1e-05
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1596,11 +1612,11 @@ Lambda = 0.0001
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1609,11 +1625,11 @@ Lambda = 0.001
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1622,11 +1638,11 @@ Lambda = 0.01
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1635,11 +1651,11 @@ Lambda = 0.1
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1648,11 +1664,11 @@ Lambda = 1.0
Accuracy score on test set: 0.07777777777777778
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:43: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:43: RuntimeWarning: overflow encountered in exp
exp_term = np.exp(self.z_o)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/1630775253.py:44: RuntimeWarning: invalid value encountered in true_divide
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
</pre></div>
</div>
@@ -1665,7 +1681,7 @@ Accuracy score on test set: 0.07777777777777778
</div>
</div>
<div class="section" id="visualization">
<h2><span class="section-number">13.6. </span>Visualization<a class="headerlink" href="#visualization" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.6. </span>Visualization<a class="headerlink" href="#visualization" title="Permalink to this headline"></a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># visual representation of grid search</span>
@@ -1705,25 +1721,25 @@ Accuracy score on test set: 0.07777777777777778
</div>
</div>
<div class="cell_output docutils container">
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/953065564.py:4: RuntimeWarning: overflow encountered in exp
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/953065564.py:4: RuntimeWarning: overflow encountered in exp
return 1/(1 + np.exp(-x))
</pre></div>
</div>
<img alt="_images/chapter10_49_1.png" src="_images/chapter10_49_1.png" />
<img alt="_images/chapter10_49_2.png" src="_images/chapter10_49_2.png" />
<img alt="_images/chapter10_59_1.png" src="_images/chapter10_59_1.png" />
<img alt="_images/chapter10_59_2.png" src="_images/chapter10_59_2.png" />
</div>
</div>
</div>
<div class="section" id="scikit-learn-implementation">
<h2><span class="section-number">13.7. </span>scikit-learn implementation<a class="headerlink" href="#scikit-learn-implementation" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.7. </span>scikit-learn implementation<a class="headerlink" href="#scikit-learn-implementation" title="Permalink to this headline"></a></h2>
<p><strong>scikit-learn</strong> focuses more
on traditional machine learning methods, such as regression,
clustering, decision trees, etc. As such, it has only two types of
@@ -2058,13 +2074,13 @@ Accuracy score on test set: 0.2
Learning rate = 10.0
Lambda = 0.001
Accuracy score on test set: 0.10555555555555556
Learning rate = 10.0
Lambda = 0.01
Accuracy score on test set: 0.06388888888888888
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Learning rate = 10.0
Lambda = 0.01
Accuracy score on test set: 0.06388888888888888
Learning rate = 10.0
Lambda = 0.1
Accuracy score on test set: 0.08888888888888889
</pre></div>
@@ -2082,7 +2098,7 @@ Accuracy score on test set: 0.09166666666666666
</div>
</div>
<div class="section" id="id1">
<h2><span class="section-number">13.8. </span>Visualization<a class="headerlink" href="#id1" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.8. </span>Visualization<a class="headerlink" href="#id1" title="Permalink to this headline"></a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># optional</span>
@@ -2123,13 +2139,13 @@ Accuracy score on test set: 0.09166666666666666
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/chapter10_53_0.png" src="_images/chapter10_53_0.png" />
<img alt="_images/chapter10_53_1.png" src="_images/chapter10_53_1.png" />
<img alt="_images/chapter10_63_0.png" src="_images/chapter10_63_0.png" />
<img alt="_images/chapter10_63_1.png" src="_images/chapter10_63_1.png" />
</div>
</div>
</div>
<div class="section" id="building-neural-networks-in-tensorflow-and-keras">
<h2><span class="section-number">13.9. </span>Building neural networks in Tensorflow and Keras<a class="headerlink" href="#building-neural-networks-in-tensorflow-and-keras" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.9. </span>Building neural networks in Tensorflow and Keras<a class="headerlink" href="#building-neural-networks-in-tensorflow-and-keras" title="Permalink to this headline"></a></h2>
<p>Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn
and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy
and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer.</p>
@@ -2154,23 +2170,8 @@ will give an introduction to the lower level Python Application
Program Interfaces (APIs), and see how we use them to build our graph.
Then we will build (effectively) the same graph in Keras, to see just
how simple solving a machine learning problem can be.</p>
<p>To install tensorflow on Unix/Linux systems, use pip as</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="n">pip3</span> <span class="n">install</span> <span class="n">tensorflow</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output traceback highlight-ipythontb notranslate"><div class="highlight"><pre><span></span><span class="gt"> File</span><span class="nn"> &quot;/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/2357089093.py&quot;</span><span class="gt">, line </span><span class="mi">1</span>
<span class="n">pip3</span> <span class="n">install</span> <span class="n">tensorflow</span>
<span class="o">^</span>
<span class="ne">SyntaxError</span>: invalid syntax
</pre></div>
</div>
</div>
</div>
<p>and/or if you use <strong>anaconda</strong>, just write (or install from the graphical user interface)
<p>To install tensorflow on Unix/Linux systems, use pip as <strong>pip3 install tensorflow</strong>
and/or if you use <strong>anaconda</strong>, just write (or install from the graphical user interface)
(current release of CPU-only TensorFlow)</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
@@ -2179,6 +2180,14 @@ how simple solving a machine learning problem can be.</p>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output traceback highlight-ipythontb notranslate"><div class="highlight"><pre><span></span><span class="gt"> File</span><span class="nn"> &quot;/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/2259440937.py&quot;</span><span class="gt">, line </span><span class="mi">1</span>
<span class="n">conda</span> <span class="n">create</span> <span class="o">-</span><span class="n">n</span> <span class="n">tf</span> <span class="n">tensorflow</span>
<span class="o">^</span>
<span class="ne">SyntaxError</span>: invalid syntax
</pre></div>
</div>
</div>
</div>
<p>To install the current release of GPU TensorFlow</p>
<div class="cell docutils container">
@@ -2357,7 +2366,7 @@ If you have Anaconda installed you may run the following command</p>
</div>
</div>
<div class="section" id="the-breast-cancer-data-now-with-keras">
<h2><span class="section-number">13.10. </span>The Breast Cancer Data, now with Keras<a class="headerlink" href="#the-breast-cancer-data-now-with-keras" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.10. </span>The Breast Cancer Data, now with Keras<a class="headerlink" href="#the-breast-cancer-data-now-with-keras" title="Permalink to this headline"></a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">tensorflow</span> <span class="k">as</span> <span class="nn">tf</span>
@@ -2531,7 +2540,7 @@ If you have Anaconda installed you may run the following command</p>
</div>
</div>
<div class="section" id="fine-tuning-neural-network-hyperparameters">
<h2><span class="section-number">13.11. </span>Fine-tuning neural network hyperparameters<a class="headerlink" href="#fine-tuning-neural-network-hyperparameters" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.11. </span>Fine-tuning neural network hyperparameters<a class="headerlink" href="#fine-tuning-neural-network-hyperparameters" title="Permalink to this headline"></a></h2>
<p>The flexibility of neural networks is also one of their main
drawbacks: there are many hyperparameters to tweak. Not only can you
use any imaginable network topology (how neurons/nodes are interconnected),
@@ -2562,7 +2571,7 @@ of training data. However, you will rarely have to train such networks from scra
common to reuse parts of a pretrained state-of-the-art network that performs a similar task.</p>
</div>
<div class="section" id="which-activation-function-should-i-use">
<h2><span class="section-number">13.12. </span>Which activation function should I use?<a class="headerlink" href="#which-activation-function-should-i-use" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.12. </span>Which activation function should I use?<a class="headerlink" href="#which-activation-function-should-i-use" title="Permalink to this headline"></a></h2>
<p>The Back propagation algorithm we derived above works by going from
the output layer to the input layer, propagating the error gradient on
the way. Once the algorithm has computed the gradient of the cost
@@ -2627,7 +2636,7 @@ it does not saturate for positive values (and also because it is quite
fast to compute).</p>
</div>
<div class="section" id="the-relu-function-family">
<h2><span class="section-number">13.13. </span>The RELU function family<a class="headerlink" href="#the-relu-function-family" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.13. </span>The RELU function family<a class="headerlink" href="#the-relu-function-family" title="Permalink to this headline"></a></h2>
<p>The ReLU activation function suffers from a problem known as the dying
ReLUs: during training, some neurons effectively die, meaning they
stop outputting anything other than 0.</p>
@@ -2664,7 +2673,7 @@ bootstrap to evaluate other activation functions.</p>
</ul>
</div>
<div class="section" id="batch-normalization">
<h2><span class="section-number">13.14. </span>Batch Normalization<a class="headerlink" href="#batch-normalization" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.14. </span>Batch Normalization<a class="headerlink" href="#batch-normalization" title="Permalink to this headline"></a></h2>
<p>Batch Normalization
aims to address the vanishing/exploding gradients problems, and more generally the problem that the
distribution of each layers inputs changes during training, as the parameters of the previous layers change.</p>
@@ -2677,7 +2686,7 @@ standard deviation. It does so by evaluating the mean and standard deviation of
mini-batch, from this the name batch normalization.</p>
</div>
<div class="section" id="dropout">
<h2><span class="section-number">13.15. </span>Dropout<a class="headerlink" href="#dropout" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.15. </span>Dropout<a class="headerlink" href="#dropout" title="Permalink to this headline"></a></h2>
<p>It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but
excluding the output neurons) has a probability <span class="math notranslate nohighlight">\(p\)</span> of being temporarily dropped out, meaning it will be
entirely ignored during this training step, but it may be active during the next step.</p>
@@ -2686,7 +2695,7 @@ hyperparameter <span class="math notranslate nohighlight">\(p\)</span> is called
It is viewed as one of the most popular regularization techniques.</p>
</div>
<div class="section" id="gradient-clipping">
<h2><span class="section-number">13.16. </span>Gradient Clipping<a class="headerlink" href="#gradient-clipping" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.16. </span>Gradient Clipping<a class="headerlink" href="#gradient-clipping" title="Permalink to this headline"></a></h2>
<p>A popular technique to lessen the exploding gradients problem is to simply clip the gradients during
backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural
networks).</p>
@@ -2695,7 +2704,7 @@ networks).</p>
Normalization is preferred.</p>
</div>
<div class="section" id="a-top-down-perspective-on-neural-networks">
<h2><span class="section-number">13.17. </span>A top-down perspective on Neural networks<a class="headerlink" href="#a-top-down-perspective-on-neural-networks" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.17. </span>A top-down perspective on Neural networks<a class="headerlink" href="#a-top-down-perspective-on-neural-networks" title="Permalink to this headline"></a></h2>
<p>The first thing we would like to do is divide the data into two or three
parts. A training set, a validation or dev (development) set, and a
test set. The test set is the data on which we want to make
@@ -2729,7 +2738,7 @@ can serve as another important diagnostic when using DNNs for
supervised learning.</p>
</div>
<div class="section" id="limitations-of-supervised-learning-with-deep-networks">
<h2><span class="section-number">13.18. </span>Limitations of supervised learning with deep networks<a class="headerlink" href="#limitations-of-supervised-learning-with-deep-networks" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">14.18. </span>Limitations of supervised learning with deep networks<a class="headerlink" href="#limitations-of-supervised-learning-with-deep-networks" title="Permalink to this headline"></a></h2>
<p>Like all statistical methods, supervised learning using neural
networks has important limitations. This is especially important when
one seeks to apply these methods, especially to physics problems. Like
@@ -2782,7 +2791,7 @@ features).</p>
<i class="prevnext-label fas fa-angle-left"></i>
<div class="prevnext-info">
<p class="prevnext-label">previous</p>
<p class="prevnext-title"><span class="section-number">12. </span>Neural networks</p>
<p class="prevnext-title"><span class="section-number">13. </span>Neural networks</p>
</div>
</a>
</div>
@@ -2790,7 +2799,7 @@ features).</p>
<a class="right-next" href="chapter11.html" title="next page">
<div class="prevnext-info">
<p class="prevnext-label">next</p>
<p class="prevnext-title"><span class="section-number">14. </span>Solving Differential Equations with Deep Learning</p>
<p class="prevnext-title"><span class="section-number">15. </span>Solving Differential Equations with Deep Learning</p>
</div>
<i class="prevnext-label fas fa-angle-right"></i>
</a>
+319 -135
View File
@@ -5,7 +5,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>14. Solving Differential Equations with Deep Learning &#8212; Applied Data Analysis and Machine Learning</title>
<title>15. Solving Differential Equations with Deep Learning &#8212; Applied Data Analysis and Machine Learning</title>
<link href="_static/css/theme.css" rel="stylesheet" />
<link href="_static/css/index.c5995385ac14fb8791e8eb36b4908be2.css" rel="stylesheet" />
@@ -53,7 +53,8 @@
<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="prev" title="13. Building a Feed Forward Neural Network" href="chapter10.html" />
<link rel="next" title="16. Convolutional Neural Networks" href="chapter12.html" />
<link rel="prev" title="14. Building a Feed Forward Neural Network" href="chapter10.html" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="docsearch:language" content="en" />
@@ -198,6 +199,11 @@
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="clustering.html">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
@@ -207,17 +213,27 @@
<ul class="current nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter9.html">
12. Neural networks
13. Neural networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter10.html">
13. Building a Feed Forward Neural Network
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1 current active">
<a class="current reference internal" href="#">
14. Solving Differential Equations with Deep Learning
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
@@ -293,90 +309,90 @@
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#example-exponential-decay">
14.1. Example: Exponential decay
15.1. Example: Exponential decay
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#reformulating-the-problem">
14.2. Reformulating the problem
15.2. Reformulating the problem
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#gradient-descent">
14.3. Gradient descent
15.3. Gradient descent
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-code-for-solving-the-ode">
14.4. The code for solving the ODE
15.4. The code for solving the ODE
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer">
14.5. The network with one input layer, specified number of hidden layers, and one output layer
15.5. The network with one input layer, specified number of hidden layers, and one output layer
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#example-population-growth">
14.5.1. Example: Population growth
15.5.1. Example: Population growth
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#using-forward-euler-to-solve-the-ode">
14.6. Using forward Euler to solve the ODE
15.6. Using forward Euler to solve the ODE
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#solving-the-one-dimensional-poisson-equation">
14.7. Solving the one dimensional Poisson equation
15.7. Solving the one dimensional Poisson equation
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#comparing-with-a-numerical-scheme">
14.7.1. Comparing with a numerical scheme
15.7.1. Comparing with a numerical scheme
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#partial-differential-equations">
14.8. Partial Differential Equations
15.8. Partial Differential Equations
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#type-of-problem">
14.8.1. Type of problem
15.8.1. Type of problem
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#network-requirements">
14.8.2. Network requirements
15.8.2. Network requirements
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#example-the-diffusion-equation">
14.9. Example: The diffusion equation
15.9. Example: The diffusion equation
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#setting-up-the-network-using-autograd-the-full-program">
14.9.1. Setting up the network using Autograd; The full program
15.9.1. Setting up the network using Autograd; The full program
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#solving-the-wave-equation-with-neural-networks">
14.10. Solving the wave equation with Neural Networks
15.10. Solving the wave equation with Neural Networks
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#resources-on-differential-equations-and-deep-learning">
14.11. Resources on differential equations and deep learning
15.11. Resources on differential equations and deep learning
</a>
</li>
</ul>
@@ -390,8 +406,9 @@
<div>
<div class="tex2jax_ignore mathjax_ignore section" id="solving-differential-equations-with-deep-learning">
<h1><span class="section-number">14. </span>Solving Differential Equations with Deep Learning<a class="headerlink" href="#solving-differential-equations-with-deep-learning" title="Permalink to this headline"></a></h1>
<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
doconce format html chapter11.do.txt --><div class="tex2jax_ignore mathjax_ignore section" id="solving-differential-equations-with-deep-learning">
<h1><span class="section-number">15. </span>Solving Differential Equations with Deep Learning<a class="headerlink" href="#solving-differential-equations-with-deep-learning" title="Permalink to this headline"></a></h1>
<p>The Universal Approximation Theorem states that a neural network can
approximate any function at a single hidden layer along with one input
and output layer to any given precision.</p>
@@ -457,7 +474,7 @@ It might happen so that finding an analytical expression of the gradient of <spa
<p>Luckily, there exists libraries that makes the job for us through automatic differentiation.
Automatic differentiation is a method of finding the derivatives numerically with very high precision.</p>
<div class="section" id="example-exponential-decay">
<h2><span class="section-number">14.1. </span>Example: Exponential decay<a class="headerlink" href="#example-exponential-decay" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.1. </span>Example: Exponential decay<a class="headerlink" href="#example-exponential-decay" title="Permalink to this headline"></a></h2>
<p>An exponential decay of a quantity <span class="math notranslate nohighlight">\(g(x)\)</span> is described by the equation</p>
<!-- Equation labels as ordinary links -->
<div id="solve_expdec"></div>
@@ -512,7 +529,7 @@ g_t(x, P) = g_0 + x \cdot N(x, P)
\]</div>
</div>
<div class="section" id="reformulating-the-problem">
<h2><span class="section-number">14.2. </span>Reformulating the problem<a class="headerlink" href="#reformulating-the-problem" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.2. </span>Reformulating the problem<a class="headerlink" href="#reformulating-the-problem" title="Permalink to this headline"></a></h2>
<p>We wish that our neural network manages to minimize a given cost function.</p>
<p>A reformulation of out equation, (<a class="reference external" href="#solveode">6</a>), must therefore be done,
such that it describes the problem a neural network can solve for.</p>
@@ -657,7 +674,7 @@ C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i
<p>Here, gradient descent with a constant step size has been chosen.</p>
</div>
<div class="section" id="gradient-descent">
<h2><span class="section-number">14.3. </span>Gradient descent<a class="headerlink" href="#gradient-descent" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.3. </span>Gradient descent<a class="headerlink" href="#gradient-descent" title="Permalink to this headline"></a></h2>
<p>The idea of the gradient descent algorithm is to update parameters in
a direction where the cost function decreases goes to a minimum.</p>
<p>In general, the update of some parameters <span class="math notranslate nohighlight">\(\boldsymbol{\omega}\)</span> given a cost
@@ -686,7 +703,7 @@ P_{\text{output},\text{new}} &amp;= P_{\text{output}} - \lambda \nabla_{P_{\text
\end{split}\]</div>
</div>
<div class="section" id="the-code-for-solving-the-ode">
<h2><span class="section-number">14.4. </span>The code for solving the ODE<a class="headerlink" href="#the-code-for-solving-the-ode" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.4. </span>The code for solving the ODE<a class="headerlink" href="#the-code-for-solving-the-ode" title="Permalink to this headline"></a></h2>
<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
@@ -846,12 +863,12 @@ P_{\text{output},\text{new}} &amp;= P_{\text{output}} - \lambda \nabla_{P_{\text
Max absolute difference: 0.0437499
</pre></div>
</div>
<img alt="_images/chapter11_47_2.png" src="_images/chapter11_47_2.png" />
<img alt="_images/chapter11_50_2.png" src="_images/chapter11_50_2.png" />
</div>
</div>
</div>
<div class="section" id="the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer">
<h2><span class="section-number">14.5. </span>The network with one input layer, specified number of hidden layers, and one output layer<a class="headerlink" href="#the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.5. </span>The network with one input layer, specified number of hidden layers, and one output layer<a class="headerlink" href="#the-network-with-one-input-layer-specified-number-of-hidden-layers-and-one-output-layer" title="Permalink to this headline"></a></h2>
<p>It is also possible to extend the construction of our network into a more general one, allowing the network to contain more than one hidden layers.</p>
<p>The number of neurons within each hidden layer are given as a list of integers in the program below.</p>
<div class="cell docutils container">
@@ -1025,106 +1042,14 @@ Max absolute difference: 0.0437499
return array(a, dtype, copy=False, order=order)
</pre></div>
</div>
<div class="output traceback highlight-ipythontb notranslate"><div class="highlight"><pre><span></span>---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42376/2971492148.py in &lt;module&gt;
144 lmb = 0.001
145
--&gt; 146 P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
147
148 res = g_trial_deep(x,P)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42376/2971492148.py in solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb)
119 # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases
120 # in the hidden layers and output layers evaluated at x.
--&gt; 121 cost_deep_grad = cost_function_deep_grad(P, x)
122
123 for l in range(N_hidden+1):
~/anaconda3/lib/python3.8/site-packages/autograd/wrap_util.py in nary_f(*args, **kwargs)
18 else:
19 x = tuple(args[i] for i in argnum)
---&gt; 20 return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
21 return nary_f
22 return nary_operator
~/anaconda3/lib/python3.8/site-packages/autograd/differential_operators.py in grad(fun, x)
23 arguments as `fun`, but returns the gradient instead. The function `fun`
24 should be scalar-valued. The gradient has the same type as the argument.&quot;&quot;&quot;
---&gt; 25 vjp, ans = _make_vjp(fun, x)
26 if not vspace(ans).size == 1:
27 raise TypeError(&quot;Grad only applies to real scalar-output functions. &quot;
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in make_vjp(fun, x)
8 def make_vjp(fun, x):
9 start_node = VJPNode.new_root()
---&gt; 10 end_value, end_node = trace(start_node, fun, x)
11 if end_node is None:
12 def vjp(g): return vspace(x).zeros()
~/anaconda3/lib/python3.8/site-packages/autograd/tracer.py in trace(start_node, fun, x)
8 with trace_stack.new_trace() as t:
9 start_box = new_box(x, t, start_node)
---&gt; 10 end_box = fun(start_box)
11 if isbox(end_box) and end_box._trace == start_box._trace:
12 return end_box._value, end_box._node
~/anaconda3/lib/python3.8/site-packages/autograd/wrap_util.py in unary_f(x)
13 else:
14 subargs = subvals(args, zip(argnum, x))
---&gt; 15 return fun(*subargs, **kwargs)
16 if isinstance(argnum, int):
17 x = args[argnum]
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42376/2971492148.py in cost_function_deep(P, x)
67
68 # Evaluate the trial function with the current parameters P
---&gt; 69 g_t = g_trial_deep(x,P)
70
71 # Find the derivative w.r.t x of the neural network
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42376/2971492148.py in g_trial_deep(x, params, g0)
57 # The trial solution using the deep neural network:
58 def g_trial_deep(x,params, g0 = 10):
---&gt; 59 return g0 + x*deep_neural_network(params, x)
60
61 # The right side of the ODE:
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42376/2971492148.py in deep_neural_network(deep_params, x)
37
38 z_hidden = np.matmul(w_hidden, x_prev)
---&gt; 39 x_hidden = sigmoid(z_hidden)
40
41 # Update x_prev such that next layer can use the output from this layer
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42376/2971492148.py in sigmoid(z)
5
6 def sigmoid(z):
----&gt; 7 return 1/(1 + np.exp(-z))
8
9 # The neural network with one input layer and one output layer,
~/anaconda3/lib/python3.8/site-packages/autograd/tracer.py in f_wrapped(*args, **kwargs)
40 if f_wrapped in notrace_primitives[node_constructor]:
41 return f_wrapped(*argvals, **kwargs)
---&gt; 42 parents = tuple(box._node for _ , box in boxed_args)
43 argnums = tuple(argnum for argnum, _ in boxed_args)
44 ans = f_wrapped(*argvals, **kwargs)
~/anaconda3/lib/python3.8/site-packages/autograd/tracer.py in &lt;genexpr&gt;(.0)
40 if f_wrapped in notrace_primitives[node_constructor]:
41 return f_wrapped(*argvals, **kwargs)
---&gt; 42 parents = tuple(box._node for _ , box in boxed_args)
43 argnums = tuple(argnum for argnum, _ in boxed_args)
44 ans = f_wrapped(*argvals, **kwargs)
KeyboardInterrupt:
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Final cost: 0.119936
</pre></div>
</div>
<img alt="_images/chapter11_52_3.png" src="_images/chapter11_52_3.png" />
</div>
</div>
<div class="section" id="example-population-growth">
<h3><span class="section-number">14.5.1. </span>Example: Population growth<a class="headerlink" href="#example-population-growth" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">15.5.1. </span>Example: Population growth<a class="headerlink" href="#example-population-growth" title="Permalink to this headline"></a></h3>
<p>A logistic model of population growth assumes that a population converges toward an equilibrium.
The population growth can be modeled by</p>
<!-- Equation labels as ordinary links -->
@@ -1335,11 +1260,25 @@ g(t) = \frac{Ag_0}{g_0 + (A - g_0)\exp(-\alpha A t)}
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Initial cost: 0.221805
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/Users/MortenImac/anaconda3/lib/python3.8/site-packages/numpy/core/_asarray.py:83: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify &#39;dtype=object&#39; when creating the ndarray
return array(a, dtype, copy=False, order=order)
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Final cost: 0.000417932
The max absolute difference between the solutions is: 0.00424909
</pre></div>
</div>
<img alt="_images/chapter11_58_3.png" src="_images/chapter11_58_3.png" />
</div>
</div>
</div>
</div>
<div class="section" id="using-forward-euler-to-solve-the-ode">
<h2><span class="section-number">14.6. </span>Using forward Euler to solve the ODE<a class="headerlink" href="#using-forward-euler-to-solve-the-ode" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.6. </span>Using forward Euler to solve the ODE<a class="headerlink" href="#using-forward-euler-to-solve-the-ode" title="Permalink to this headline"></a></h2>
<p>A straightforward way of solving an ODE numerically, is to use Eulers method.</p>
<p>Eulers method uses Taylor series to approximate the value at a function <span class="math notranslate nohighlight">\(f\)</span> at a step <span class="math notranslate nohighlight">\(\Delta x\)</span> from <span class="math notranslate nohighlight">\(x\)</span>:</p>
<div class="math notranslate nohighlight">
@@ -1452,10 +1391,27 @@ extending the program that uses the network using Autograd:</p>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Initial cost: 0.221805
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/Users/MortenImac/anaconda3/lib/python3.8/site-packages/numpy/core/_asarray.py:83: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify &#39;dtype=object&#39; when creating the ndarray
return array(a, dtype, copy=False, order=order)
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Final cost: 0.000417932
The max absolute difference between the solutions is: 0.00424909
Max absolute difference between Euler method and analytical: 0.011225
Max absolute difference between deep neural network and analytical: 0.00424909
</pre></div>
</div>
<img alt="_images/chapter11_66_3.png" src="_images/chapter11_66_3.png" />
<img alt="_images/chapter11_66_4.png" src="_images/chapter11_66_4.png" />
</div>
</div>
</div>
<div class="section" id="solving-the-one-dimensional-poisson-equation">
<h2><span class="section-number">14.7. </span>Solving the one dimensional Poisson equation<a class="headerlink" href="#solving-the-one-dimensional-poisson-equation" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.7. </span>Solving the one dimensional Poisson equation<a class="headerlink" href="#solving-the-one-dimensional-poisson-equation" title="Permalink to this headline"></a></h2>
<p>The Poisson equation for <span class="math notranslate nohighlight">\(g(x)\)</span> in one dimension is</p>
<!-- Equation labels as ordinary links -->
<div id="poisson"></div>
@@ -1657,9 +1613,23 @@ g(x) = x(1 - x)\exp(x)
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/Users/MortenImac/anaconda3/lib/python3.8/site-packages/numpy/core/_asarray.py:83: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify &#39;dtype=object&#39; when creating the ndarray
return array(a, dtype, copy=False, order=order)
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Initial cost: 457.256
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Final cost: 0.00310113
The max absolute difference between the solutions is: 0.000464088
</pre></div>
</div>
<img alt="_images/chapter11_79_3.png" src="_images/chapter11_79_3.png" />
</div>
</div>
<div class="section" id="comparing-with-a-numerical-scheme">
<h3><span class="section-number">14.7.1. </span>Comparing with a numerical scheme<a class="headerlink" href="#comparing-with-a-numerical-scheme" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">15.7.1. </span>Comparing with a numerical scheme<a class="headerlink" href="#comparing-with-a-numerical-scheme" title="Permalink to this headline"></a></h3>
<p>The Poisson equation is possible to solve using Taylor series to approximate the second derivative.</p>
<p>Using Taylor series, the second derivative can be expressed as</p>
<div class="math notranslate nohighlight">
@@ -1933,11 +1903,27 @@ f(x_{N_x - 2})
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Initial cost: 457.256
</pre></div>
</div>
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/Users/MortenImac/anaconda3/lib/python3.8/site-packages/numpy/core/_asarray.py:83: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify &#39;dtype=object&#39; when creating the ndarray
return array(a, dtype, copy=False, order=order)
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Final cost: 0.00310113
The max absolute difference between the analytical solution and DNN Autograd: 0.000464088
The max absolute difference between the analytical solution and numerical scheme: 0.00266858
</pre></div>
</div>
<img alt="_images/chapter11_91_3.png" src="_images/chapter11_91_3.png" />
<img alt="_images/chapter11_91_4.png" src="_images/chapter11_91_4.png" />
</div>
</div>
</div>
</div>
<div class="section" id="partial-differential-equations">
<h2><span class="section-number">14.8. </span>Partial Differential Equations<a class="headerlink" href="#partial-differential-equations" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.8. </span>Partial Differential Equations<a class="headerlink" href="#partial-differential-equations" title="Permalink to this headline"></a></h2>
<p>A partial differential equation (PDE) has a solution here the function
is defined by multiple variables. The equation may involve all kinds
of combinations of which variables the function is differentiated with
@@ -1953,7 +1939,7 @@ respect to.</p>
\]</div>
<p>where <span class="math notranslate nohighlight">\(f\)</span> is an expression involving all kinds of possible mixed derivatives of <span class="math notranslate nohighlight">\(g(x_1,\dots,x_N)\)</span> up to an order <span class="math notranslate nohighlight">\(n\)</span>. In order for the solution to be unique, some additional conditions must also be given.</p>
<div class="section" id="type-of-problem">
<h3><span class="section-number">14.8.1. </span>Type of problem<a class="headerlink" href="#type-of-problem" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">15.8.1. </span>Type of problem<a class="headerlink" href="#type-of-problem" title="Permalink to this headline"></a></h3>
<p>The problem our network must solve for, is similar to the ODE case.
We must have a trial solution <span class="math notranslate nohighlight">\(g_t\)</span> at hand.</p>
<p>For instance, the trial solution could be expressed as</p>
@@ -1968,7 +1954,7 @@ The neural network <span class="math notranslate nohighlight">\(N(x_1,\dots,x_N,
<p>The role of the function <span class="math notranslate nohighlight">\(h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))\)</span>, is to ensure that the output of <span class="math notranslate nohighlight">\(N(x_1,\dots,x_N,P)\)</span> is zero when <span class="math notranslate nohighlight">\(g_t(x_1,\dots,x_N)\)</span> is evaluated at the values of <span class="math notranslate nohighlight">\(x_1,\dots,x_N\)</span> where the given conditions must be satisfied. The function <span class="math notranslate nohighlight">\(h_1(x_1,\dots,x_N)\)</span> should alone make <span class="math notranslate nohighlight">\(g_t(x_1,\dots,x_N)\)</span> satisfy the conditions.</p>
</div>
<div class="section" id="network-requirements">
<h3><span class="section-number">14.8.2. </span>Network requirements<a class="headerlink" href="#network-requirements" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">15.8.2. </span>Network requirements<a class="headerlink" href="#network-requirements" title="Permalink to this headline"></a></h3>
<p>The network tries then the minimize the cost function following the
same ideas as described for the ODE case, but now with more than one
variables to consider. The concept still remains the same; find a set
@@ -1994,7 +1980,7 @@ C\left(X, P \right) = \sum_{i=1}^M f\left( \left( \boldsymbol{x}_i, \frac{\parti
</div>
</div>
<div class="section" id="example-the-diffusion-equation">
<h2><span class="section-number">14.9. </span>Example: The diffusion equation<a class="headerlink" href="#example-the-diffusion-equation" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.9. </span>Example: The diffusion equation<a class="headerlink" href="#example-the-diffusion-equation" title="Permalink to this headline"></a></h2>
<p>In one spatial dimension, the equation reads</p>
<div class="math notranslate nohighlight">
\[
@@ -2162,7 +2148,7 @@ mixed derivatives of <span class="math notranslate nohighlight">\(g(x,t)\)</span
</div>
</div>
<div class="section" id="setting-up-the-network-using-autograd-the-full-program">
<h3><span class="section-number">14.9.1. </span>Setting up the network using Autograd; The full program<a class="headerlink" href="#setting-up-the-network-using-autograd-the-full-program" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">15.9.1. </span>Setting up the network using Autograd; The full program<a class="headerlink" href="#setting-up-the-network-using-autograd-the-full-program" title="Permalink to this headline"></a></h3>
<p>Having set up the network, along with the trial solution and cost function, we can now see how the deep neural network performs by comparing the results to the analytical solution.</p>
<p>The analytical solution of our problem is</p>
<div class="math notranslate nohighlight">
@@ -2402,11 +2388,200 @@ Using TensorFlow results in a much better execution time. Try it!</p>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/Users/MortenImac/anaconda3/lib/python3.8/site-packages/numpy/core/_asarray.py:83: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify &#39;dtype=object&#39; when creating the ndarray
return array(a, dtype, copy=False, order=order)
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Initial cost: 41.05505310046362
</pre></div>
</div>
<div class="output traceback highlight-ipythontb notranslate"><div class="highlight"><pre><span></span>---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47448/73752910.py in &lt;module&gt;
141 lmb = 0.01
142
--&gt; 143 P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)
144
145 ## Store the results
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47448/73752910.py in solve_pde_deep_neural_network(x, t, num_neurons, num_iter, lmb)
118 # Let the update be done num_iter times
119 for i in range(num_iter):
--&gt; 120 cost_grad = cost_function_grad(P, x , t)
121
122 for l in range(N_hidden+1):
~/anaconda3/lib/python3.8/site-packages/autograd/wrap_util.py in nary_f(*args, **kwargs)
18 else:
19 x = tuple(args[i] for i in argnum)
---&gt; 20 return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
21 return nary_f
22 return nary_operator
~/anaconda3/lib/python3.8/site-packages/autograd/differential_operators.py in grad(fun, x)
23 arguments as `fun`, but returns the gradient instead. The function `fun`
24 should be scalar-valued. The gradient has the same type as the argument.&quot;&quot;&quot;
---&gt; 25 vjp, ans = _make_vjp(fun, x)
26 if not vspace(ans).size == 1:
27 raise TypeError(&quot;Grad only applies to real scalar-output functions. &quot;
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in make_vjp(fun, x)
8 def make_vjp(fun, x):
9 start_node = VJPNode.new_root()
---&gt; 10 end_value, end_node = trace(start_node, fun, x)
11 if end_node is None:
12 def vjp(g): return vspace(x).zeros()
~/anaconda3/lib/python3.8/site-packages/autograd/tracer.py in trace(start_node, fun, x)
8 with trace_stack.new_trace() as t:
9 start_box = new_box(x, t, start_node)
---&gt; 10 end_box = fun(start_box)
11 if isbox(end_box) and end_box._trace == start_box._trace:
12 return end_box._value, end_box._node
~/anaconda3/lib/python3.8/site-packages/autograd/wrap_util.py in unary_f(x)
13 else:
14 subargs = subvals(args, zip(argnum, x))
---&gt; 15 return fun(*subargs, **kwargs)
16 if isinstance(argnum, int):
17 x = args[argnum]
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47448/73752910.py in cost_function(P, x, t)
78 g_t = g_trial(point,P)
79 g_t_jacobian = g_t_jacobian_func(point,P)
---&gt; 80 g_t_hessian = g_t_hessian_func(point,P)
81
82 g_t_dt = g_t_jacobian[1]
~/anaconda3/lib/python3.8/site-packages/autograd/wrap_util.py in nary_f(*args, **kwargs)
18 else:
19 x = tuple(args[i] for i in argnum)
---&gt; 20 return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
21 return nary_f
22 return nary_operator
~/anaconda3/lib/python3.8/site-packages/autograd/differential_operators.py in hessian(fun, x)
76 def hessian(fun, x):
77 &quot;Returns a function that computes the exact Hessian.&quot;
---&gt; 78 return jacobian(jacobian(fun))(x)
79
80 @unary_to_nary
~/anaconda3/lib/python3.8/site-packages/autograd/wrap_util.py in nary_f(*args, **kwargs)
18 else:
19 x = tuple(args[i] for i in argnum)
---&gt; 20 return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
21 return nary_f
22 return nary_operator
~/anaconda3/lib/python3.8/site-packages/autograd/differential_operators.py in jacobian(fun, x)
59 jacobian_shape = ans_vspace.shape + vspace(x).shape
60 grads = map(vjp, ans_vspace.standard_basis())
---&gt; 61 return np.reshape(np.stack(grads), jacobian_shape)
62
63 @unary_to_nary
~/anaconda3/lib/python3.8/site-packages/autograd/numpy/numpy_wrapper.py in stack(arrays, axis)
86 # primitives defined in this file
87
---&gt; 88 arrays = [array(arr) for arr in arrays]
89 if not arrays:
90 raise ValueError(&#39;need at least one array to stack&#39;)
~/anaconda3/lib/python3.8/site-packages/autograd/numpy/numpy_wrapper.py in &lt;listcomp&gt;(.0)
86 # primitives defined in this file
87
---&gt; 88 arrays = [array(arr) for arr in arrays]
89 if not arrays:
90 raise ValueError(&#39;need at least one array to stack&#39;)
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in vjp(g)
12 def vjp(g): return vspace(x).zeros()
13 else:
---&gt; 14 def vjp(g): return backward_pass(g, end_node)
15 return vjp, end_value
16
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in backward_pass(g, end_node)
19 for node in toposort(end_node):
20 outgrad = outgrads.pop(node)
---&gt; 21 ingrads = node.vjp(outgrad[0])
22 for parent, ingrad in zip(node.parents, ingrads):
23 outgrads[parent] = add_outgrads(outgrads.get(parent), ingrad)
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in &lt;lambda&gt;(g)
65 &quot;VJP of {} wrt argnum 0 not defined&quot;.format(fun.__name__))
66 vjp = vjpfun(ans, *args, **kwargs)
---&gt; 67 return lambda g: (vjp(g),)
68 elif L == 2:
69 argnum_0, argnum_1 = argnums
~/anaconda3/lib/python3.8/site-packages/autograd/numpy/numpy_vjps.py in &lt;lambda&gt;(g)
421 A_ndim = anp.ndim(A)
422 B_meta = anp.metadata(B)
--&gt; 423 return lambda g: matmul_adjoint_1(A, g, A_ndim, B_meta)
424
425 defvjp(anp.matmul, matmul_vjp_0, matmul_vjp_1)
~/anaconda3/lib/python3.8/site-packages/autograd/numpy/numpy_vjps.py in matmul_adjoint_1(A, G, A_ndim, B_meta)
408 else: # We need to swap the last two axes of A
409 A = anp.swapaxes(A, A_ndim - 2, A_ndim - 1)
--&gt; 410 result = anp.matmul(A, G)
411 if B_is_vec:
412 result = anp.squeeze(result, anp.ndim(G) - 1)
~/anaconda3/lib/python3.8/site-packages/autograd/tracer.py in f_wrapped(*args, **kwargs)
43 argnums = tuple(argnum for argnum, _ in boxed_args)
44 ans = f_wrapped(*argvals, **kwargs)
---&gt; 45 node = node_constructor(ans, f_wrapped, argvals, kwargs, argnums, parents)
46 return new_box(ans, trace, node)
47 else:
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in __init__(self, value, fun, args, kwargs, parent_argnums, parents)
34 raise NotImplementedError(&quot;VJP of {} wrt argnums {} not defined&quot;
35 .format(fun_name, parent_argnums))
---&gt; 36 self.vjp = vjpmaker(parent_argnums, value, args, kwargs)
37
38 def initialize_root(self):
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in vjp_argnums(argnums, ans, args, kwargs)
75 &quot;VJP of {} wrt argnums 0, 1 not defined&quot;.format(fun.__name__))
76 vjp_0 = vjp_0_fun(ans, *args, **kwargs)
---&gt; 77 vjp_1 = vjp_1_fun(ans, *args, **kwargs)
78 return lambda g: (vjp_0(g), vjp_1(g))
79 else:
~/anaconda3/lib/python3.8/site-packages/autograd/numpy/numpy_vjps.py in matmul_vjp_1(ans, A, B)
420 def matmul_vjp_1(ans, A, B):
421 A_ndim = anp.ndim(A)
--&gt; 422 B_meta = anp.metadata(B)
423 return lambda g: matmul_adjoint_1(A, g, A_ndim, B_meta)
424
~/anaconda3/lib/python3.8/site-packages/autograd/tracer.py in f_wrapped(*args, **kwargs)
59 def f_wrapped(*args, **kwargs):
60 argvals = map(getval, args)
---&gt; 61 return f_raw(*argvals, **kwargs)
62 f_wrapped._is_primitive = True
63 return f_wrapped
~/anaconda3/lib/python3.8/site-packages/autograd/numpy/numpy_wrapper.py in metadata(A)
146 @notrace_primitive
147 def metadata(A):
--&gt; 148 return _np.shape(A), _np.ndim(A), _np.result_type(A), _np.iscomplexobj(A)
149
150 @notrace_primitive
KeyboardInterrupt:
</pre></div>
</div>
</div>
</div>
</div>
</div>
<div class="section" id="solving-the-wave-equation-with-neural-networks">
<h2><span class="section-number">14.10. </span>Solving the wave equation with Neural Networks<a class="headerlink" href="#solving-the-wave-equation-with-neural-networks" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.10. </span>Solving the wave equation with Neural Networks<a class="headerlink" href="#solving-the-wave-equation-with-neural-networks" title="Permalink to this headline"></a></h2>
<p>The wave equation is</p>
<div class="math notranslate nohighlight">
\[
@@ -2693,7 +2868,7 @@ g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t)
</div>
</div>
<div class="section" id="resources-on-differential-equations-and-deep-learning">
<h2><span class="section-number">14.11. </span>Resources on differential equations and deep learning<a class="headerlink" href="#resources-on-differential-equations-and-deep-learning" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">15.11. </span>Resources on differential equations and deep learning<a class="headerlink" href="#resources-on-differential-equations-and-deep-learning" title="Permalink to this headline"></a></h2>
<ol class="simple">
<li><p><a class="reference external" href="https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf">Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al</a></p></li>
<li><p><a class="reference external" href="https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c">Neural networks for solving differential equations by A. Honchar</a></p></li>
@@ -2737,10 +2912,19 @@ g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t)
<i class="prevnext-label fas fa-angle-left"></i>
<div class="prevnext-info">
<p class="prevnext-label">previous</p>
<p class="prevnext-title"><span class="section-number">13. </span>Building a Feed Forward Neural Network</p>
<p class="prevnext-title"><span class="section-number">14. </span>Building a Feed Forward Neural Network</p>
</div>
</a>
</div>
<div id="next">
<a class="right-next" href="chapter12.html" title="next page">
<div class="prevnext-info">
<p class="prevnext-label">next</p>
<p class="prevnext-title"><span class="section-number">16. </span>Convolutional Neural Networks</p>
</div>
<i class="prevnext-label fas fa-angle-right"></i>
</a>
</div>
</div>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+53 -38
View File
@@ -5,7 +5,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>12. Neural networks &#8212; Applied Data Analysis and Machine Learning</title>
<title>13. Neural networks &#8212; Applied Data Analysis and Machine Learning</title>
<link href="_static/css/theme.css" rel="stylesheet" />
<link href="_static/css/index.c5995385ac14fb8791e8eb36b4908be2.css" rel="stylesheet" />
@@ -53,8 +53,8 @@
<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="13. Building a Feed Forward Neural Network" href="chapter10.html" />
<link rel="prev" title="11. Basic ideas of the Principal Component Analysis (PCA)" href="chapter8.html" />
<link rel="next" title="14. Building a Feed Forward Neural Network" href="chapter10.html" />
<link rel="prev" title="12. Clustering and Unsupervised Learning" href="clustering.html" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="docsearch:language" content="en" />
@@ -199,6 +199,11 @@
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="clustering.html">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
@@ -208,17 +213,27 @@
<ul class="current nav bd-sidenav">
<li class="toctree-l1 current active">
<a class="current reference internal" href="#">
12. Neural networks
13. Neural networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter10.html">
13. Building a Feed Forward Neural Network
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter11.html">
14. Solving Differential Equations with Deep Learning
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
@@ -294,76 +309,76 @@
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#feed-forward-neural-networks">
12.1. Feed-forward neural networks
13.1. Feed-forward neural networks
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#convolutional-neural-network">
12.2. Convolutional Neural Network
13.2. Convolutional Neural Network
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#recurrent-neural-networks">
12.3. Recurrent neural networks
13.3. Recurrent neural networks
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#other-types-of-networks">
12.4. Other types of networks
13.4. Other types of networks
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#multilayer-perceptrons">
12.5. Multilayer perceptrons
13.5. Multilayer perceptrons
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#matrix-vector-notation-and-activation">
12.5.1. Matrix-vector notation and activation
13.5.1. Matrix-vector notation and activation
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#activation-functions">
12.5.2. Activation functions
13.5.2. Activation functions
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#the-multilayer-perceptron-mlp">
12.6. The multilayer perceptron (MLP)
13.6. The multilayer perceptron (MLP)
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#from-one-to-many-layers-the-universal-approximation-theorem">
12.6.1. From one to many layers, the universal approximation theorem
13.6.1. From one to many layers, the universal approximation theorem
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#deriving-the-back-propagation-code-for-a-multilayer-perceptron-model">
12.7. Deriving the back propagation code for a multilayer perceptron model
13.7. Deriving the back propagation code for a multilayer perceptron model
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#derivatives-and-the-chain-rule">
12.7.1. Derivatives and the chain rule
13.7.1. Derivatives and the chain rule
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#bringing-it-together-first-back-propagation-equation">
12.7.2. Bringing it together, first back propagation equation
13.7.2. Bringing it together, first back propagation equation
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#final-back-propagating-equation">
12.7.3. Final back propagating equation
13.7.3. Final back propagating equation
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#setting-up-the-back-propagation-algorithm">
12.7.4. Setting up the Back propagation algorithm
13.7.4. Setting up the Back propagation algorithm
</a>
</li>
</ul>
@@ -380,7 +395,7 @@
<div>
<div class="tex2jax_ignore mathjax_ignore section" id="neural-networks">
<h1><span class="section-number">12. </span>Neural networks<a class="headerlink" href="#neural-networks" title="Permalink to this headline"></a></h1>
<h1><span class="section-number">13. </span>Neural networks<a class="headerlink" href="#neural-networks" title="Permalink to this headline"></a></h1>
<p>Artificial neural networks are computational systems that can learn to
perform tasks by considering examples, generally without being
programmed with any task-specific rules. It is supposed to mimic a
@@ -452,7 +467,7 @@ can be viewed as natural, more powerful extensions of supervised
learning methods such as linear and logistic regression and soft-max
methods we discussed earlier.</p>
<div class="section" id="feed-forward-neural-networks">
<h2><span class="section-number">12.1. </span>Feed-forward neural networks<a class="headerlink" href="#feed-forward-neural-networks" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">13.1. </span>Feed-forward neural networks<a class="headerlink" href="#feed-forward-neural-networks" title="Permalink to this headline"></a></h2>
<p>The feed-forward neural network (FFNN) was the first and simplest type
of ANNs that were devised. In this network, the information moves in
only one direction: forward through the layers.</p>
@@ -464,7 +479,7 @@ to <em>all</em> nodes in the subsequent layer, making this a so-called
<em>fully-connected</em> FFNN.</p>
</div>
<div class="section" id="convolutional-neural-network">
<h2><span class="section-number">12.2. </span>Convolutional Neural Network<a class="headerlink" href="#convolutional-neural-network" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">13.2. </span>Convolutional Neural Network<a class="headerlink" href="#convolutional-neural-network" title="Permalink to this headline"></a></h2>
<p>A different variant of FFNNs are <em>convolutional neural networks</em>
(CNNs), which have a connectivity pattern inspired by the animal
visual cortex. Individual neurons in the visual cortex only respond to
@@ -484,7 +499,7 @@ produces the outputs. They have wide applications in image and video
recognition.</p>
</div>
<div class="section" id="recurrent-neural-networks">
<h2><span class="section-number">12.3. </span>Recurrent neural networks<a class="headerlink" href="#recurrent-neural-networks" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">13.3. </span>Recurrent neural networks<a class="headerlink" href="#recurrent-neural-networks" title="Permalink to this headline"></a></h2>
<p>So far we have only mentioned ANNs where information flows in one
direction: forward. <em>Recurrent neural networks</em> on the other hand,
have connections between nodes that form directed <em>cycles</em>. This
@@ -497,7 +512,7 @@ example of such information is sentences, making recurrent NNs
especially well-suited for handwriting and speech recognition.</p>
</div>
<div class="section" id="other-types-of-networks">
<h2><span class="section-number">12.4. </span>Other types of networks<a class="headerlink" href="#other-types-of-networks" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">13.4. </span>Other types of networks<a class="headerlink" href="#other-types-of-networks" title="Permalink to this headline"></a></h2>
<p>There are many other kinds of ANNs that have been developed. One type
that is specifically designed for interpolation in multidimensional
space is the radial basis function (RBF) network. RBFs are typically
@@ -510,7 +525,7 @@ fully-connected FFNN. They are however usually treated as a separate
type of NN due the unusual activation functions.</p>
</div>
<div class="section" id="multilayer-perceptrons">
<h2><span class="section-number">12.5. </span>Multilayer perceptrons<a class="headerlink" href="#multilayer-perceptrons" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">13.5. </span>Multilayer perceptrons<a class="headerlink" href="#multilayer-perceptrons" title="Permalink to this headline"></a></h2>
<p>One uses often so-called fully-connected feed-forward neural networks
with three or more layers (an input layer, one or more hidden layers
and an output layer) consisting of neurons that have non-linear
@@ -680,7 +695,7 @@ the equation for the activations of hidden layer 2 (assuming three nodes for sim
\end{equation}
\end{split}\]</div>
<div class="section" id="matrix-vector-notation-and-activation">
<h3><span class="section-number">12.5.1. </span>Matrix-vector notation and activation<a class="headerlink" href="#matrix-vector-notation-and-activation" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">13.5.1. </span>Matrix-vector notation and activation<a class="headerlink" href="#matrix-vector-notation-and-activation" title="Permalink to this headline"></a></h3>
<p>The activation of node <span class="math notranslate nohighlight">\(i\)</span> in layer 2 is</p>
<!-- Equation labels as ordinary links -->
<div id="_auto7"></div>
@@ -699,7 +714,7 @@ used as input to the activation functions. For each operation
<span class="math notranslate nohighlight">\(\mathrm{W}_l \hat{y}_{l-1}\)</span> we move forward one layer.</p>
</div>
<div class="section" id="activation-functions">
<h3><span class="section-number">12.5.2. </span>Activation functions<a class="headerlink" href="#activation-functions" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">13.5.2. </span>Activation functions<a class="headerlink" href="#activation-functions" title="Permalink to this headline"></a></h3>
<p>A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s). As described
in, the following restrictions are imposed on an activation function
@@ -819,7 +834,7 @@ become the most popular for <em>deep neural networks</em></p>
</div>
</div>
<div class="section" id="the-multilayer-perceptron-mlp">
<h2><span class="section-number">12.6. </span>The multilayer perceptron (MLP)<a class="headerlink" href="#the-multilayer-perceptron-mlp" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">13.6. </span>The multilayer perceptron (MLP)<a class="headerlink" href="#the-multilayer-perceptron-mlp" title="Permalink to this headline"></a></h2>
<p>The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of</p>
<ol class="simple">
<li><p>A neural network with one or more layers of nodes between the input and the output nodes.</p></li>
@@ -844,7 +859,7 @@ are learned from data. This results in an important difference between
neural networks and deep learning approaches on one side and methods
like logistic regression or linear regression and their modifications on the other side.</p>
<div class="section" id="from-one-to-many-layers-the-universal-approximation-theorem">
<h3><span class="section-number">12.6.1. </span>From one to many layers, the universal approximation theorem<a class="headerlink" href="#from-one-to-many-layers-the-universal-approximation-theorem" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">13.6.1. </span>From one to many layers, the universal approximation theorem<a class="headerlink" href="#from-one-to-many-layers-the-universal-approximation-theorem" title="Permalink to this headline"></a></h3>
<p>A neural network with only one layer, what we called the simple
perceptron, is best suited if we have a standard binary model with
clear (linear) boundaries between the outcomes. As such it could
@@ -865,7 +880,7 @@ the potential of being universal approximators.</p>
</div>
</div>
<div class="section" id="deriving-the-back-propagation-code-for-a-multilayer-perceptron-model">
<h2><span class="section-number">12.7. </span>Deriving the back propagation code for a multilayer perceptron model<a class="headerlink" href="#deriving-the-back-propagation-code-for-a-multilayer-perceptron-model" title="Permalink to this headline"></a></h2>
<h2><span class="section-number">13.7. </span>Deriving the back propagation code for a multilayer perceptron model<a class="headerlink" href="#deriving-the-back-propagation-code-for-a-multilayer-perceptron-model" title="Permalink to this headline"></a></h2>
<p>As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.
The unknowwn quantities are our weights <span class="math notranslate nohighlight">\(w_{ij}\)</span> and we need to find an algorithm for changing them so that our errors are as small as possible.
This leads us to the famous <a class="reference external" href="https://www.nature.com/articles/323533a0">back propagation algorithm</a>.</p>
@@ -912,7 +927,7 @@ and their nodes. It means we have</p>
a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}.
\]</div>
<div class="section" id="derivatives-and-the-chain-rule">
<h3><span class="section-number">12.7.1. </span>Derivatives and the chain rule<a class="headerlink" href="#derivatives-and-the-chain-rule" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">13.7.1. </span>Derivatives and the chain rule<a class="headerlink" href="#derivatives-and-the-chain-rule" title="Permalink to this headline"></a></h3>
<p>From the definition of the activation <span class="math notranslate nohighlight">\(z_j^l\)</span> we have</p>
<div class="math notranslate nohighlight">
\[
@@ -946,7 +961,7 @@ a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}.
\]</div>
</div>
<div class="section" id="bringing-it-together-first-back-propagation-equation">
<h3><span class="section-number">12.7.2. </span>Bringing it together, first back propagation equation<a class="headerlink" href="#bringing-it-together-first-back-propagation-equation" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">13.7.2. </span>Bringing it together, first back propagation equation<a class="headerlink" href="#bringing-it-together-first-back-propagation-equation" title="Permalink to this headline"></a></h3>
<p>We have thus</p>
<div class="math notranslate nohighlight">
\[
@@ -1045,7 +1060,7 @@ to do so we need to represent the error in the layer before the final
one <span class="math notranslate nohighlight">\(L-1\)</span> in terms of the errors in the final output layer.</p>
</div>
<div class="section" id="final-back-propagating-equation">
<h3><span class="section-number">12.7.3. </span>Final back propagating equation<a class="headerlink" href="#final-back-propagating-equation" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">13.7.3. </span>Final back propagating equation<a class="headerlink" href="#final-back-propagating-equation" title="Permalink to this headline"></a></h3>
<p>We have that (replacing <span class="math notranslate nohighlight">\(L\)</span> with a general layer <span class="math notranslate nohighlight">\(l\)</span>)</p>
<div class="math notranslate nohighlight">
\[
@@ -1070,7 +1085,7 @@ z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},
<p>We are now ready to set up the algorithm for back propagation and learning the weights and biases.</p>
</div>
<div class="section" id="setting-up-the-back-propagation-algorithm">
<h3><span class="section-number">12.7.4. </span>Setting up the Back propagation algorithm<a class="headerlink" href="#setting-up-the-back-propagation-algorithm" title="Permalink to this headline"></a></h3>
<h3><span class="section-number">13.7.4. </span>Setting up the Back propagation algorithm<a class="headerlink" href="#setting-up-the-back-propagation-algorithm" title="Permalink to this headline"></a></h3>
<p>The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.</p>
<p>First, we set up the input data <span class="math notranslate nohighlight">\(\hat{x}\)</span> and the activations
<span class="math notranslate nohighlight">\(\hat{z}_1\)</span> of the input layer and compute the activation function and
@@ -1134,11 +1149,11 @@ Here it is convenient to use stochastic gradient descent (see the examples below
<div class='prev-next-bottom'>
<div id="prev">
<a class="left-prev" href="chapter8.html" title="previous page">
<a class="left-prev" href="clustering.html" title="previous page">
<i class="prevnext-label fas fa-angle-left"></i>
<div class="prevnext-info">
<p class="prevnext-label">previous</p>
<p class="prevnext-title"><span class="section-number">11. </span>Basic ideas of the Principal Component Analysis (PCA)</p>
<p class="prevnext-title"><span class="section-number">12. </span>Clustering and Unsupervised Learning</p>
</div>
</a>
</div>
@@ -1146,7 +1161,7 @@ Here it is convenient to use stochastic gradient descent (see the examples below
<a class="right-next" href="chapter10.html" title="next page">
<div class="prevnext-info">
<p class="prevnext-label">next</p>
<p class="prevnext-title"><span class="section-number">13. </span>Building a Feed Forward Neural Network</p>
<p class="prevnext-title"><span class="section-number">14. </span>Building a Feed Forward Neural Network</p>
</div>
<i class="prevnext-label fas fa-angle-right"></i>
</a>
@@ -199,6 +199,11 @@
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="clustering.html">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
@@ -208,17 +213,27 @@
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter9.html">
12. Neural networks
13. Neural networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter10.html">
13. Building a Feed Forward Neural Network
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter11.html">
14. Solving Differential Equations with Deep Learning
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
@@ -330,8 +345,8 @@
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#stochastic-gradient-descent">
7.7. Stochastic Gradient Descent
<a class="reference internal nav-link" href="#stochastic-gradient-descent-sgd">
7.7. Stochastic Gradient Descent (SGD)
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
@@ -368,6 +383,23 @@
7.10. Automatic differentiation
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#using-autograd-with-ols">
7.11. Using Autograd with OLS
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#including-stochastic-gradient-descent-with-autograd">
7.11.1. Including Stochastic Gradient Descent with Autograd
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#and-logistic-regression">
7.11.2. And Logistic Regression
</a>
</li>
</ul>
</li>
</ul>
</nav>
@@ -379,7 +411,8 @@
<div>
<div class="tex2jax_ignore mathjax_ignore section" id="optimization-the-central-part-of-any-machine-learning-algortithm">
<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
doconce format html chapteroptimization.do.txt --><div class="tex2jax_ignore mathjax_ignore section" id="optimization-the-central-part-of-any-machine-learning-algortithm">
<h1><span class="section-number">7. </span>Optimization, the central part of any Machine Learning algortithm<a class="headerlink" href="#optimization-the-central-part-of-any-machine-learning-algortithm" title="Permalink to this headline"></a></h1>
<p>Almost every problem in machine learning and data science starts with
a dataset <span class="math notranslate nohighlight">\(X\)</span>, a model <span class="math notranslate nohighlight">\(g(\beta)\)</span>, which is a function of the
@@ -750,14 +783,14 @@ which equals</p>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42573/483257001.py:18: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().
<div class="output stderr highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47735/483257001.py:18: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().
ax = fig.gca(projection=&quot;3d&quot;)
</pre></div>
</div>
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>&lt;mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7fad10f9a280&gt;
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>&lt;mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7fd098df3280&gt;
</pre></div>
</div>
<img alt="_images/chapteroptimization_56_2.png" src="_images/chapteroptimization_56_2.png" />
<img alt="_images/chapteroptimization_61_2.png" src="_images/chapteroptimization_61_2.png" />
</div>
</div>
<p>And then as countor plot</p>
@@ -770,7 +803,7 @@ which equals</p>
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/chapteroptimization_58_0.png" src="_images/chapteroptimization_58_0.png" />
<img alt="_images/chapteroptimization_63_0.png" src="_images/chapteroptimization_63_0.png" />
</div>
</div>
<p>Find guesses</p>
@@ -812,10 +845,10 @@ which equals</p>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[&lt;matplotlib.lines.Line2D at 0x7fad20f69be0&gt;]
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[&lt;matplotlib.lines.Line2D at 0x7fd0a9063be0&gt;]
</pre></div>
</div>
<img alt="_images/chapteroptimization_64_1.png" src="_images/chapteroptimization_64_1.png" />
<img alt="_images/chapteroptimization_69_1.png" src="_images/chapteroptimization_69_1.png" />
</div>
</div>
</div>
@@ -1069,16 +1102,14 @@ when <span class="math notranslate nohighlight">\(||\nabla_\beta C(\beta_k) || \
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[0.32903042 4.1484256 ]
[[4.04621521]
[3.00415763]]
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[0.28001319 4.21265216]
[[3.96987657]
[3.02493054]]
[[3.96987657]
[3.02493054]]
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[[4.04621521]
[3.00415763]]
</pre></div>
</div>
<img alt="_images/chapteroptimization_118_2.png" src="_images/chapteroptimization_118_2.png" />
<img alt="_images/chapteroptimization_123_1.png" src="_images/chapteroptimization_123_1.png" />
</div>
</div>
<p>Alternatively, we can use <strong>Scikit-Learn</strong> as done here</p>
@@ -1104,9 +1135,9 @@ when <span class="math notranslate nohighlight">\(||\nabla_\beta C(\beta_k) || \
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[[3.97230501]
[3.14741468]]
[3.94735055] [3.17084902]
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[[4.00275135]
[2.99724883]]
[3.97065296] [3.07656896]
</pre></div>
</div>
</div>
@@ -1177,13 +1208,13 @@ C_{\text{ridge}}(\beta) = \frac{1}{n}||X\beta -\mathbf{y}||^2 + \lambda ||\beta|
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[[3.92343595]
[3.15258907]]
[[3.815563 ]
[3.23522201]]
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[[4.1533795 ]
[2.92819235]]
[[4.06858699]
[2.99829953]]
</pre></div>
</div>
<img alt="_images/chapteroptimization_127_1.png" src="_images/chapteroptimization_127_1.png" />
<img alt="_images/chapteroptimization_132_1.png" src="_images/chapteroptimization_132_1.png" />
</div>
</div>
</div>
@@ -1198,8 +1229,27 @@ C_{\text{ridge}}(\beta) = \frac{1}{n}||X\beta -\mathbf{y}||^2 + \lambda ||\beta|
<li><p>GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.</p></li>
</ul>
</div>
<div class="section" id="stochastic-gradient-descent">
<h2><span class="section-number">7.7. </span>Stochastic Gradient Descent<a class="headerlink" href="#stochastic-gradient-descent" title="Permalink to this headline"></a></h2>
<div class="section" id="stochastic-gradient-descent-sgd">
<h2><span class="section-number">7.7. </span>Stochastic Gradient Descent (SGD)<a class="headerlink" href="#stochastic-gradient-descent-sgd" title="Permalink to this headline"></a></h2>
<p>In stochastic gradient descent, the extreme case is the case where we
have only one batch, that is we include the whole data set.</p>
<p>This process is called Stochastic Gradient
Descent (SGD) (or also sometimes on-line gradient descent). This is
relatively less common to see because in practice due to vectorized
code optimizations it can be computationally much more efficient to
evaluate the gradient for 100 examples, than the gradient for one
example 100 times. Even though SGD technically refers to using a
single example at a time to evaluate the gradient, you will hear
people use the term SGD even when referring to mini-batch gradient
descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD
for “Batch gradient descent” are rare to see), where it is usually
assumed that mini-batches are used. The size of the mini-batch is a
hyperparameter but it is not very common to cross-validate or bootstrap it. It is
usually based on memory constraints (if any), or set to some value,
e.g. 32, 64 or 128. We use powers of 2 in practice because many
vectorized operation implementations work faster when their inputs are
sized in powers of 2.</p>
<p>In our notes with SGD we mean stochastic gradient descent with mini-batches.</p>
<p>Stochastic gradient descent (SGD) and variants thereof address some of
the shortcomings of the Gradient descent method discussed above.</p>
<p>The underlying idea of SGD comes from the observation that the cost
@@ -1256,7 +1306,7 @@ the number of minibatches, as exemplified in the code below.</p>
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">100</span> <span class="c1">#100 datapoints </span>
<span class="n">M</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1">#size of each minibatch</span>
<span class="n">M</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1">#size of each mini-batche</span>
<span class="n">m</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">n</span><span class="o">/</span><span class="n">M</span><span class="p">)</span> <span class="c1">#number of minibatches</span>
<span class="n">n_epochs</span> <span class="o">=</span> <span class="mi">10</span> <span class="c1">#number of epochs</span>
@@ -1332,38 +1382,39 @@ function.</p>
</div>
</div>
</div>
<p>We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters <span class="math notranslate nohighlight">\(t_0\)</span> and <span class="math notranslate nohighlight">\(t_1\)</span>.</p>
<div class="section" id="program-for-stochastic-gradient">
<h3><span class="section-number">7.7.1. </span>Program for stochastic gradient<a class="headerlink" href="#program-for-stochastic-gradient" title="Permalink to this headline"></a></h3>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Importing various packages</span>
<span class="c1"># Importing various packages</span>
<span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">exp</span><span class="p">,</span> <span class="n">sqrt</span>
<span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">random</span><span class="p">,</span> <span class="n">seed</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</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">from</span> <span class="nn">sklearn.linear_model</span> <span class="kn">import</span> <span class="n">SGDRegressor</span>
<span class="n">m</span> <span class="o">=</span> <span class="mi">100</span>
<span class="n">x</span> <span class="o">=</span> <span class="mi">2</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="n">m</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span> <span class="mi">4</span><span class="o">+</span><span class="mi">3</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="n">m</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">100</span>
<span class="n">x</span> <span class="o">=</span> <span class="mi">2</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</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">y</span> <span class="o">=</span> <span class="mi">4</span><span class="o">+</span><span class="mi">3</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</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">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">ones</span><span class="p">((</span><span class="n">m</span><span class="p">,</span><span class="mi">1</span><span class="p">)),</span> <span class="n">x</span><span class="p">]</span>
<span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">ones</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="p">]</span>
<span class="n">XT_X</span> <span class="o">=</span> <span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">X</span>
<span class="n">theta_linreg</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">inv</span><span class="p">(</span><span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">X</span><span class="p">)</span> <span class="o">@</span> <span class="p">(</span><span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">y</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Own inversion&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta_linreg</span><span class="p">)</span>
<span class="n">sgdreg</span> <span class="o">=</span> <span class="n">SGDRegressor</span><span class="p">(</span><span class="n">max_iter</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span> <span class="n">penalty</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">eta0</span><span class="o">=</span><span class="mf">0.1</span><span class="p">)</span>
<span class="n">sgdreg</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="o">.</span><span class="n">ravel</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;sgdreg from scikit&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">sgdreg</span><span class="o">.</span><span class="n">intercept_</span><span class="p">,</span> <span class="n">sgdreg</span><span class="o">.</span><span class="n">coef_</span><span class="p">)</span>
<span class="c1"># Hessian matrix</span>
<span class="n">H</span> <span class="o">=</span> <span class="p">(</span><span class="mf">2.0</span><span class="o">/</span><span class="n">n</span><span class="p">)</span><span class="o">*</span> <span class="n">XT_X</span>
<span class="n">EigValues</span><span class="p">,</span> <span class="n">EigVectors</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">eig</span><span class="p">(</span><span class="n">H</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Eigenvalues of Hessian Matrix:</span><span class="si">{</span><span class="n">EigValues</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="n">eta</span> <span class="o">=</span> <span class="mf">0.1</span>
<span class="n">eta</span> <span class="o">=</span> <span class="mf">1.0</span><span class="o">/</span><span class="n">np</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">EigValues</span><span class="p">)</span>
<span class="n">Niterations</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="k">for</span> <span class="nb">iter</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">Niterations</span><span class="p">):</span>
<span class="n">gradients</span> <span class="o">=</span> <span class="mf">2.0</span><span class="o">/</span><span class="n">m</span><span class="o">*</span><span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="p">((</span><span class="n">X</span> <span class="o">@</span> <span class="n">theta</span><span class="p">)</span><span class="o">-</span><span class="n">y</span><span class="p">)</span>
<span class="n">gradients</span> <span class="o">=</span> <span class="mf">2.0</span><span class="o">/</span><span class="n">n</span><span class="o">*</span><span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="p">((</span><span class="n">X</span> <span class="o">@</span> <span class="n">theta</span><span class="p">)</span><span class="o">-</span><span class="n">y</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">-=</span> <span class="n">eta</span><span class="o">*</span><span class="n">gradients</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;theta from own gd&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
@@ -1373,8 +1424,9 @@ function.</p>
<span class="n">ypredict</span> <span class="o">=</span> <span class="n">Xnew</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
<span class="n">ypredict2</span> <span class="o">=</span> <span class="n">Xnew</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">theta_linreg</span><span class="p">)</span>
<span class="n">n_epochs</span> <span class="o">=</span> <span class="mi">50</span>
<span class="n">M</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1">#size of each minibatch</span>
<span class="n">m</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">n</span><span class="o">/</span><span class="n">M</span><span class="p">)</span> <span class="c1">#number of minibatches</span>
<span class="n">t0</span><span class="p">,</span> <span class="n">t1</span> <span class="o">=</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">50</span>
<span class="k">def</span> <span class="nf">learning_schedule</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
<span class="k">return</span> <span class="n">t0</span><span class="o">/</span><span class="p">(</span><span class="n">t</span><span class="o">+</span><span class="n">t1</span><span class="p">)</span>
@@ -1382,16 +1434,20 @@ function.</p>
<span class="n">theta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="k">for</span> <span class="n">epoch</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_epochs</span><span class="p">):</span>
<span class="c1"># Can you figure out a better way of setting up the contributions to each batch?</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="n">m</span><span class="p">):</span>
<span class="n">random_index</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="n">xi</span> <span class="o">=</span> <span class="n">X</span><span class="p">[</span><span class="n">random_index</span><span class="p">:</span><span class="n">random_index</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span>
<span class="n">yi</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="n">random_index</span><span class="p">:</span><span class="n">random_index</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span>
<span class="n">gradients</span> <span class="o">=</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">xi</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="p">((</span><span class="n">xi</span> <span class="o">@</span> <span class="n">theta</span><span class="p">)</span><span class="o">-</span><span class="n">yi</span><span class="p">)</span>
<span class="n">random_index</span> <span class="o">=</span> <span class="n">M</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="n">xi</span> <span class="o">=</span> <span class="n">X</span><span class="p">[</span><span class="n">random_index</span><span class="p">:</span><span class="n">random_index</span><span class="o">+</span><span class="n">M</span><span class="p">]</span>
<span class="n">yi</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="n">random_index</span><span class="p">:</span><span class="n">random_index</span><span class="o">+</span><span class="n">M</span><span class="p">]</span>
<span class="n">gradients</span> <span class="o">=</span> <span class="p">(</span><span class="mf">2.0</span><span class="o">/</span><span class="n">M</span><span class="p">)</span><span class="o">*</span> <span class="n">xi</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="p">((</span><span class="n">xi</span> <span class="o">@</span> <span class="n">theta</span><span class="p">)</span><span class="o">-</span><span class="n">yi</span><span class="p">)</span>
<span class="n">eta</span> <span class="o">=</span> <span class="n">learning_schedule</span><span class="p">(</span><span class="n">epoch</span><span class="o">*</span><span class="n">m</span><span class="o">+</span><span class="n">i</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">=</span> <span class="n">theta</span> <span class="o">-</span> <span class="n">eta</span><span class="o">*</span><span class="n">gradients</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;theta from own sdg&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta</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">xnew</span><span class="p">,</span> <span class="n">ypredict</span><span class="p">,</span> <span class="s2">&quot;r-&quot;</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">xnew</span><span class="p">,</span> <span class="n">ypredict2</span><span class="p">,</span> <span class="s2">&quot;b-&quot;</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">x</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>
@@ -1405,23 +1461,24 @@ function.</p>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Own inversion
[[4.15629539]
[2.7293182 ]]
sgdreg from scikit
[4.0728785] [2.66410989]
[[3.99775949]
[2.94659383]]
Eigenvalues of Hessian Matrix:[0.36102113 4.18276924]
theta from own gd
[[4.15629539]
[2.7293182 ]]
[[3.99775949]
[2.94659383]]
theta from own sdg
[[3.96489434]
[2.98399675]]
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>theta from own sdg
[[4.15454301]
[2.72522848]]
</pre></div>
</div>
<img alt="_images/chapteroptimization_141_2.png" src="_images/chapteroptimization_141_2.png" />
<img alt="_images/chapteroptimization_148_1.png" src="_images/chapteroptimization_148_1.png" />
</div>
</div>
<p>In the above code, we have use replacement in setting up the
mini-batches. The discussion
<a class="reference external" href="https://sebastianraschka.com/faq/docs/sgd-methods.html">here</a> may be
useful. More material will be added later.</p>
</div>
</div>
<div class="section" id="momentum-based-gd">
@@ -1538,7 +1595,7 @@ the steep computational price of calculating or approximating
Hessians.</p>
<p>Recently, a number of methods have been introduced that accomplish
this by tracking not only the gradient, but also the second moment of
the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and
the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and
ADAM.</p>
<div class="section" id="rms-prop">
<h3><span class="section-number">7.8.1. </span>RMS prop<a class="headerlink" href="#rms-prop" title="Permalink to this headline"></a></h3>
@@ -1724,7 +1781,7 @@ f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right)
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/chapteroptimization_177_0.png" src="_images/chapteroptimization_177_0.png" />
<img alt="_images/chapteroptimization_188_0.png" src="_images/chapteroptimization_188_0.png" />
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>The max absolute difference is: 1.77636e-15
</pre></div>
</div>
@@ -1907,28 +1964,42 @@ The analytical gradient of f4 at x = 2.7 is: 13.8759
</div>
</div>
</div>
<p>1
8</p>
<p>&lt;
&lt;
&lt;
!
!
C
O
D
E
_
B
L
O
C
K</p>
<p>p
y
c
o
d</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="kn">import</span> <span class="nn">autograd.numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">autograd</span> <span class="kn">import</span> <span class="n">grad</span>
<span class="k">def</span> <span class="nf">f6_for</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="n">val</span> <span class="o">=</span> <span class="mi">0</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">10</span><span class="p">):</span>
<span class="n">val</span> <span class="o">=</span> <span class="n">val</span> <span class="o">+</span> <span class="n">x</span><span class="o">**</span><span class="n">i</span>
<span class="k">return</span> <span class="n">val</span>
<span class="k">def</span> <span class="nf">f6_while</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="n">val</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">:</span>
<span class="n">val</span> <span class="o">=</span> <span class="n">val</span> <span class="o">+</span> <span class="n">x</span><span class="o">**</span><span class="n">i</span>
<span class="n">i</span> <span class="o">=</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">1</span>
<span class="k">return</span> <span class="n">val</span>
<span class="n">f6_for_grad</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">f6_for</span><span class="p">)</span>
<span class="n">f6_while_grad</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">f6_while</span><span class="p">)</span>
<span class="n">x</span> <span class="o">=</span> <span class="mf">0.5</span>
<span class="c1"># Print the computed derivaties of f6_for and f6_while</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;The computed derivative of f6_for at x = </span><span class="si">%g</span><span class="s2"> is: </span><span class="si">%g</span><span class="s2">&quot;</span><span class="o">%</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">f6_for_grad</span><span class="p">(</span><span class="n">x</span><span class="p">)))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;The computed derivative of f6_while at x = </span><span class="si">%g</span><span class="s2"> is: </span><span class="si">%g</span><span class="s2">&quot;</span><span class="o">%</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">f6_while_grad</span><span class="p">(</span><span class="n">x</span><span class="p">)))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>The computed derivative of f6_for at x = 0.5 is: 3.95703
The computed derivative of f6_while at x = 0.5 is: 3.95703
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">autograd.numpy</span> <span class="k">as</span> <span class="nn">np</span>
@@ -1944,7 +2015,7 @@ d</p>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>The analytical derivative of f6 at x = 2.7 is: 37732.5
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>The analytical derivative of f6 at x = 0.5 is: 3.95703
</pre></div>
</div>
</div>
@@ -1989,49 +2060,31 @@ The analytical derivative of f7 at n = 2 is: 1
</div>
</div>
<p>Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.</p>
<p>Autograd supports many features. However, there are some functions that are not supported (yet) by Autograd.</p>
<p>Assigning a value to the variable being differentiated with respect to is an example thereof.</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="c1">#import autograd.numpy as np</span>
<span class="c1">#from autograd import grad</span>
<span class="c1">#def f8(x): # Assume x is an array</span>
<span class="c1"># x[2] = 3</span>
<span class="c1"># return x*2</span>
<span class="c1">#f8_grad = grad(f8)</span>
<span class="c1">#x = 8.4</span>
<span class="c1">#print(&quot;The derivative of f8 is:&quot;,f8_grad(x))</span>
</pre></div>
</div>
</div>
</div>
<p>Here, Autograd tells us that an ArrayBox does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.</p>
<p>Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.</p>
<p>Assigning a value to the variable being differentiated with respect to</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="kn">import</span> <span class="nn">autograd.numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">autograd</span> <span class="kn">import</span> <span class="n">grad</span>
<span class="k">def</span> <span class="nf">f9</span><span class="p">(</span><span class="n">a</span><span class="p">):</span> <span class="c1"># Assume a is an array with 2 elements</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">1.0</span><span class="p">,</span><span class="mf">2.0</span><span class="p">])</span>
<span class="k">return</span> <span class="n">a</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">f8</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="c1"># Assume x is an array</span>
<span class="n">x</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="mi">3</span>
<span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="mi">2</span>
<span class="n">f9_grad</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">f9</span><span class="p">)</span>
<span class="n">f8_grad</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">f8</span><span class="p">)</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">1.0</span><span class="p">,</span><span class="mf">0.0</span><span class="p">])</span>
<span class="n">x</span> <span class="o">=</span> <span class="mf">8.4</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;The derivative of f9 is:&quot;</span><span class="p">,</span><span class="n">f9_grad</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;The derivative of f8 is:&quot;</span><span class="p">,</span><span class="n">f8_grad</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output traceback highlight-ipythontb notranslate"><div class="highlight"><pre><span></span>---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42573/546166676.py in &lt;module&gt;
9 x = np.array([1.0,0.0])
TypeError Traceback (most recent call last)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47735/1122558214.py in &lt;module&gt;
9 x = 8.4
10
---&gt; 11 print(&quot;The derivative of f9 is:&quot;,f9_grad(x))
---&gt; 11 print(&quot;The derivative of f8 is:&quot;,f8_grad(x))
~/anaconda3/lib/python3.8/site-packages/autograd/wrap_util.py in nary_f(*args, **kwargs)
18 else:
@@ -2068,14 +2121,32 @@ AttributeError Traceback (most recent call last)
16 if isinstance(argnum, int):
17 x = args[argnum]
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42573/546166676.py in f9(a)
3 def f9(a): # Assume a is an array with 2 elements
4 b = np.array([1.0,2.0])
----&gt; 5 return a.dot(b)
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47735/1122558214.py in f8(x)
2 from autograd import grad
3 def f8(x): # Assume x is an array
----&gt; 4 x[2] = 3
5 return x*2
6
7 f9_grad = grad(f9)
AttributeError: &#39;ArrayBox&#39; object has no attribute &#39;dot&#39;
TypeError: &#39;ArrayBox&#39; object does not support item assignment
</pre></div>
</div>
</div>
</div>
<p>Here, Autograd tells us that an ArrayBox does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.</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="kn">import</span> <span class="nn">autograd.numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">autograd</span> <span class="kn">import</span> <span class="n">grad</span>
<span class="k">def</span> <span class="nf">f9</span><span class="p">(</span><span class="n">a</span><span class="p">):</span> <span class="c1"># Assume a is an array with 2 elements</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">1.0</span><span class="p">,</span><span class="mf">2.0</span><span class="p">])</span>
<span class="k">return</span> <span class="n">a</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="n">f9_grad</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">f9</span><span class="p">)</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">1.0</span><span class="p">,</span><span class="mf">0.0</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;The derivative of f9 is:&quot;</span><span class="p">,</span><span class="n">f9_grad</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
</pre></div>
</div>
</div>
@@ -2114,7 +2185,192 @@ which also computed the dot product can be used:</p>
</div>
</div>
</div>
<p>More examples will be added, in particular how to compare autograd with own codes for the gradients.</p>
</div>
<div class="section" id="using-autograd-with-ols">
<h2><span class="section-number">7.11. </span>Using Autograd with OLS<a class="headerlink" href="#using-autograd-with-ols" title="Permalink to this headline"></a></h2>
<p>We conclude the part on optmization by showing how we can make codes
for linear regression and logistic regression using <strong>autograd</strong>. The
first example shows results with ordinary leats squares.</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="c1"># Using Autograd to calculate gradients for OLS</span>
<span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">random</span><span class="p">,</span> <span class="n">seed</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">autograd.numpy</span> <span class="k">as</span> <span class="nn">np</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">from</span> <span class="nn">autograd</span> <span class="kn">import</span> <span class="n">grad</span>
<span class="k">def</span> <span class="nf">CostOLS</span><span class="p">(</span><span class="n">beta</span><span class="p">):</span>
<span class="k">return</span> <span class="p">(</span><span class="mf">1.0</span><span class="o">/</span><span class="n">n</span><span class="p">)</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y</span><span class="o">-</span><span class="n">X</span> <span class="o">@</span> <span class="n">beta</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">100</span>
<span class="n">x</span> <span class="o">=</span> <span class="mi">2</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</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">y</span> <span class="o">=</span> <span class="mi">4</span><span class="o">+</span><span class="mi">3</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</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">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">ones</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="p">]</span>
<span class="n">XT_X</span> <span class="o">=</span> <span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">X</span>
<span class="n">theta_linreg</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">pinv</span><span class="p">(</span><span class="n">XT_X</span><span class="p">)</span> <span class="o">@</span> <span class="p">(</span><span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">y</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Own inversion&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta_linreg</span><span class="p">)</span>
<span class="c1"># Hessian matrix</span>
<span class="n">H</span> <span class="o">=</span> <span class="p">(</span><span class="mf">2.0</span><span class="o">/</span><span class="n">n</span><span class="p">)</span><span class="o">*</span> <span class="n">XT_X</span>
<span class="n">EigValues</span><span class="p">,</span> <span class="n">EigVectors</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">eig</span><span class="p">(</span><span class="n">H</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Eigenvalues of Hessian Matrix:</span><span class="si">{</span><span class="n">EigValues</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="n">eta</span> <span class="o">=</span> <span class="mf">1.0</span><span class="o">/</span><span class="n">np</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">EigValues</span><span class="p">)</span>
<span class="n">Niterations</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="c1"># define the gradient</span>
<span class="n">training_gradient</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">CostOLS</span><span class="p">)</span>
<span class="k">for</span> <span class="nb">iter</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">Niterations</span><span class="p">):</span>
<span class="n">gradients</span> <span class="o">=</span> <span class="n">training_gradient</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">-=</span> <span class="n">eta</span><span class="o">*</span><span class="n">gradients</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;theta from own gd&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
<span class="n">xnew</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">0</span><span class="p">],[</span><span class="mi">2</span><span class="p">]])</span>
<span class="n">Xnew</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">ones</span><span class="p">((</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">)),</span> <span class="n">xnew</span><span class="p">]</span>
<span class="n">ypredict</span> <span class="o">=</span> <span class="n">Xnew</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
<span class="n">ypredict2</span> <span class="o">=</span> <span class="n">Xnew</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">theta_linreg</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">xnew</span><span class="p">,</span> <span class="n">ypredict</span><span class="p">,</span> <span class="s2">&quot;r-&quot;</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">xnew</span><span class="p">,</span> <span class="n">ypredict2</span><span class="p">,</span> <span class="s2">&quot;b-&quot;</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">x</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">axis</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mf">2.0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="mf">15.0</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="sa">r</span><span class="s1">&#39;$x$&#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="sa">r</span><span class="s1">&#39;$y$&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;Random numbers &#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>
<div class="section" id="including-stochastic-gradient-descent-with-autograd">
<h3><span class="section-number">7.11.1. </span>Including Stochastic Gradient Descent with Autograd<a class="headerlink" href="#including-stochastic-gradient-descent-with-autograd" title="Permalink to this headline"></a></h3>
<p>In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using <strong>autograd</strong>.</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="c1"># Using Autograd to calculate gradients using SGD</span>
<span class="c1"># OLS example</span>
<span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">random</span><span class="p">,</span> <span class="n">seed</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">autograd.numpy</span> <span class="k">as</span> <span class="nn">np</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">from</span> <span class="nn">autograd</span> <span class="kn">import</span> <span class="n">grad</span>
<span class="c1"># Note change from previous example</span>
<span class="k">def</span> <span class="nf">CostOLS</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="n">X</span><span class="p">,</span><span class="n">theta</span><span class="p">):</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y</span><span class="o">-</span><span class="n">X</span> <span class="o">@</span> <span class="n">theta</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">100</span>
<span class="n">x</span> <span class="o">=</span> <span class="mi">2</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</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">y</span> <span class="o">=</span> <span class="mi">4</span><span class="o">+</span><span class="mi">3</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</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">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">ones</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="p">]</span>
<span class="n">XT_X</span> <span class="o">=</span> <span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">X</span>
<span class="n">theta_linreg</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">pinv</span><span class="p">(</span><span class="n">XT_X</span><span class="p">)</span> <span class="o">@</span> <span class="p">(</span><span class="n">X</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">y</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Own inversion&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta_linreg</span><span class="p">)</span>
<span class="c1"># Hessian matrix</span>
<span class="n">H</span> <span class="o">=</span> <span class="p">(</span><span class="mf">2.0</span><span class="o">/</span><span class="n">n</span><span class="p">)</span><span class="o">*</span> <span class="n">XT_X</span>
<span class="n">EigValues</span><span class="p">,</span> <span class="n">EigVectors</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">eig</span><span class="p">(</span><span class="n">H</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Eigenvalues of Hessian Matrix:</span><span class="si">{</span><span class="n">EigValues</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="n">eta</span> <span class="o">=</span> <span class="mf">1.0</span><span class="o">/</span><span class="n">np</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">EigValues</span><span class="p">)</span>
<span class="n">Niterations</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="c1"># Note that we request the derivative wrt third argument (theta, 2 here)</span>
<span class="n">training_gradient</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">CostOLS</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="k">for</span> <span class="nb">iter</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">Niterations</span><span class="p">):</span>
<span class="n">gradients</span> <span class="o">=</span> <span class="p">(</span><span class="mf">1.0</span><span class="o">/</span><span class="n">n</span><span class="p">)</span><span class="o">*</span><span class="n">training_gradient</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="n">X</span><span class="p">,</span> <span class="n">theta</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">-=</span> <span class="n">eta</span><span class="o">*</span><span class="n">gradients</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;theta from own gd&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
<span class="n">xnew</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">0</span><span class="p">],[</span><span class="mi">2</span><span class="p">]])</span>
<span class="n">Xnew</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">ones</span><span class="p">((</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">)),</span> <span class="n">xnew</span><span class="p">]</span>
<span class="n">ypredict</span> <span class="o">=</span> <span class="n">Xnew</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
<span class="n">ypredict2</span> <span class="o">=</span> <span class="n">Xnew</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">theta_linreg</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">xnew</span><span class="p">,</span> <span class="n">ypredict</span><span class="p">,</span> <span class="s2">&quot;r-&quot;</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">xnew</span><span class="p">,</span> <span class="n">ypredict2</span><span class="p">,</span> <span class="s2">&quot;b-&quot;</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">x</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">axis</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mf">2.0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="mf">15.0</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="sa">r</span><span class="s1">&#39;$x$&#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="sa">r</span><span class="s1">&#39;$y$&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;Random numbers &#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="n">n_epochs</span> <span class="o">=</span> <span class="mi">50</span>
<span class="n">M</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1">#size of each minibatch</span>
<span class="n">m</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">n</span><span class="o">/</span><span class="n">M</span><span class="p">)</span> <span class="c1">#number of minibatches</span>
<span class="n">t0</span><span class="p">,</span> <span class="n">t1</span> <span class="o">=</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">50</span>
<span class="k">def</span> <span class="nf">learning_schedule</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
<span class="k">return</span> <span class="n">t0</span><span class="o">/</span><span class="p">(</span><span class="n">t</span><span class="o">+</span><span class="n">t1</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="k">for</span> <span class="n">epoch</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_epochs</span><span class="p">):</span>
<span class="c1"># Can you figure out a better way of setting up the contributions to each batch?</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="n">m</span><span class="p">):</span>
<span class="n">random_index</span> <span class="o">=</span> <span class="n">M</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="n">xi</span> <span class="o">=</span> <span class="n">X</span><span class="p">[</span><span class="n">random_index</span><span class="p">:</span><span class="n">random_index</span><span class="o">+</span><span class="n">M</span><span class="p">]</span>
<span class="n">yi</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="n">random_index</span><span class="p">:</span><span class="n">random_index</span><span class="o">+</span><span class="n">M</span><span class="p">]</span>
<span class="n">gradients</span> <span class="o">=</span> <span class="p">(</span><span class="mf">1.0</span><span class="o">/</span><span class="n">M</span><span class="p">)</span><span class="o">*</span><span class="n">training_gradient</span><span class="p">(</span><span class="n">yi</span><span class="p">,</span> <span class="n">xi</span><span class="p">,</span> <span class="n">theta</span><span class="p">)</span>
<span class="n">eta</span> <span class="o">=</span> <span class="n">learning_schedule</span><span class="p">(</span><span class="n">epoch</span><span class="o">*</span><span class="n">m</span><span class="o">+</span><span class="n">i</span><span class="p">)</span>
<span class="n">theta</span> <span class="o">=</span> <span class="n">theta</span> <span class="o">-</span> <span class="n">eta</span><span class="o">*</span><span class="n">gradients</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;theta from own sdg&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">theta</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="and-logistic-regression">
<h3><span class="section-number">7.11.2. </span>And Logistic Regression<a class="headerlink" href="#and-logistic-regression" title="Permalink to this headline"></a></h3>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">autograd.numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">autograd</span> <span class="kn">import</span> <span class="n">grad</span>
<span class="k">def</span> <span class="nf">sigmoid</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">tanh</span><span class="p">(</span><span class="n">x</span> <span class="o">/</span> <span class="mf">2.</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">logistic_predictions</span><span class="p">(</span><span class="n">weights</span><span class="p">,</span> <span class="n">inputs</span><span class="p">):</span>
<span class="c1"># Outputs probability of a label being true according to logistic model.</span>
<span class="k">return</span> <span class="n">sigmoid</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="n">inputs</span><span class="p">,</span> <span class="n">weights</span><span class="p">))</span>
<span class="k">def</span> <span class="nf">training_loss</span><span class="p">(</span><span class="n">weights</span><span class="p">):</span>
<span class="c1"># Training loss is the negative log-likelihood of the training labels.</span>
<span class="n">preds</span> <span class="o">=</span> <span class="n">logistic_predictions</span><span class="p">(</span><span class="n">weights</span><span class="p">,</span> <span class="n">inputs</span><span class="p">)</span>
<span class="n">label_probabilities</span> <span class="o">=</span> <span class="n">preds</span> <span class="o">*</span> <span class="n">targets</span> <span class="o">+</span> <span class="p">(</span><span class="mi">1</span> <span class="o">-</span> <span class="n">preds</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span> <span class="o">-</span> <span class="n">targets</span><span class="p">)</span>
<span class="k">return</span> <span class="o">-</span><span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">label_probabilities</span><span class="p">))</span>
<span class="c1"># Build a toy dataset.</span>
<span class="n">inputs</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span><span class="mf">0.52</span><span class="p">,</span> <span class="mf">1.12</span><span class="p">,</span> <span class="mf">0.77</span><span class="p">],</span>
<span class="p">[</span><span class="mf">0.88</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.08</span><span class="p">,</span> <span class="mf">0.15</span><span class="p">],</span>
<span class="p">[</span><span class="mf">0.52</span><span class="p">,</span> <span class="mf">0.06</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.30</span><span class="p">],</span>
<span class="p">[</span><span class="mf">0.74</span><span class="p">,</span> <span class="o">-</span><span class="mf">2.49</span><span class="p">,</span> <span class="mf">1.39</span><span class="p">]])</span>
<span class="n">targets</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="kc">True</span><span class="p">,</span> <span class="kc">True</span><span class="p">,</span> <span class="kc">False</span><span class="p">,</span> <span class="kc">True</span><span class="p">])</span>
<span class="c1"># Define a function that returns gradients of training loss using Autograd.</span>
<span class="n">training_gradient_fun</span> <span class="o">=</span> <span class="n">grad</span><span class="p">(</span><span class="n">training_loss</span><span class="p">)</span>
<span class="c1"># Optimize weights using gradient descent.</span>
<span class="n">weights</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Initial loss:&quot;</span><span class="p">,</span> <span class="n">training_loss</span><span class="p">(</span><span class="n">weights</span><span class="p">))</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">100</span><span class="p">):</span>
<span class="n">weights</span> <span class="o">-=</span> <span class="n">training_gradient_fun</span><span class="p">(</span><span class="n">weights</span><span class="p">)</span> <span class="o">*</span> <span class="mf">0.01</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Trained loss:&quot;</span><span class="p">,</span> <span class="n">training_loss</span><span class="p">(</span><span class="n">weights</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,828 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>12. Clustering and Unsupervised Learning &#8212; Applied Data Analysis and Machine Learning</title>
<link href="_static/css/theme.css" rel="stylesheet" />
<link href="_static/css/index.c5995385ac14fb8791e8eb36b4908be2.css" rel="stylesheet" />
<link rel="stylesheet"
href="_static/vendor/fontawesome/5.13.0/css/all.min.css">
<link rel="preload" as="font" type="font/woff2" crossorigin
href="_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
<link rel="preload" as="font" type="font/woff2" crossorigin
href="_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">
<link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-book-theme.css?digest=c3fdc42140077d1ad13ad2f1588a4309" />
<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" />
<link rel="preload" as="script" href="_static/js/index.1c5a1a01449ed65a7b51.js">
<script data-url_root="./" id="documentation_options" 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/togglebutton.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.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 src="_static/sphinx-book-theme.12a9622fbb08dcb3a2a40b2c02b83a57.js"></script>
<script async="async" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>window.MathJax = {"options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script async="async" src="https://unpkg.com/thebe@0.5.1/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="13. Neural networks" href="chapter9.html" />
<link rel="prev" title="11. Basic ideas of the Principal Component Analysis (PCA)" href="chapter8.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-fluid" id="banner"></div>
<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">
<!-- `logo` is deprecated in Sphinx 4.0, so remove this when we stop supporting 3 -->
<img src="_static/logo.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">Applied Data Analysis and Machine Learning</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">
<div class="bd-toc-item active">
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Applied Data Analysis and Machine Learning, FYS-STK3155/4155 at the University of Oslo, Norway
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
About the course
</span>
</p>
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="schedule.html">
Teaching schedule with links to material
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="teachers.html">
Teachers and Grading
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="textbooks.html">
Textbooks
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
Review of Statistics with Resampling Techniques and Linear Algebra
</span>
</p>
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="statistics.html">
1. Elements of Probability Theory and Statistical Data Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="linalg.html">
2. Linear Algebra, Handling of Arrays and more Python Features
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
From Regression to Support Vector Machines
</span>
</p>
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter1.html">
3. Linear Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter2.html">
4. Ridge and Lasso Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter3.html">
5. Resampling Methods
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter4.html">
6. Logistic Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapteroptimization.html">
7. Optimization, the central part of any Machine Learning algortithm
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter5.html">
8. Support Vector Machines, overarching aims
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
Decision Trees, Ensemble Methods and Boosting
</span>
</p>
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter6.html">
9. Decision trees, overarching aims
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter7.html">
10. Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
Dimensionality Reduction
</span>
</p>
<ul class="current nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter8.html">
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1 current active">
<a class="current reference internal" href="#">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
Deep Learning Methods
</span>
</p>
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter9.html">
13. Neural networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter10.html">
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter11.html">
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
</div>
</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="topbar container-xl fixed-top">
<div class="topbar-contents row">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show"></div>
<div class="col pl-md-4 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/clustering.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()" aria-label="Fullscreen mode"
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" aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#codes-and-approaches">
12.1. Codes and Approaches
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
doconce format html clustering.do.txt --><div class="tex2jax_ignore mathjax_ignore section" id="clustering-and-unsupervised-learning">
<h1><span class="section-number">12. </span>Clustering and Unsupervised Learning<a class="headerlink" href="#clustering-and-unsupervised-learning" title="Permalink to this headline"></a></h1>
<p>In general terms cluster analysis, or clustering, is the task of grouping a
data-set into different distinct categories based on some measure of equality of
the data. This measure is often referred to as a <strong>metric</strong> or <strong>similarity
measure</strong> in the literature (note: sometimes we deal with a <strong>dissimilarity
measure</strong> instead). Usually, these metrics are formulated as some kind of
distance function between points in a high-dimensional space.</p>
<p>The simplest, and also the most
common is the <strong>Euclidean distance</strong>.</p>
<p>The simplest of all clustering algorithms is the <strong>k-means algorithm</strong>
, sometimes also referred to as <em>Lloyds algorithm</em>. It is the simplest and also
the most common. From its simplicity it obtains both strengths and weaknesses.
These will be discussed in more detail later. The <span class="math notranslate nohighlight">\(k\)</span>-means algorithm is a
<strong>centroid based</strong> clustering algorithm.</p>
<p>Assume, we are given <span class="math notranslate nohighlight">\(n\)</span> data points and we wish to split the data into <span class="math notranslate nohighlight">\(K &lt; n\)</span>
different categories, or clusters. We label each cluster by an integer</p>
<div class="math notranslate nohighlight">
\[
k\in\{1, \cdots, K \}.
\]</div>
<p>In the basic k-means algorithm each point is assigned to only
one cluster <span class="math notranslate nohighlight">\(k\)</span>, and these assignments are <em>non-injective</em> i.e. many-to-one. We
can think of these mappings as an encoder <span class="math notranslate nohighlight">\(k = C(i)\)</span>, which assigns the <span class="math notranslate nohighlight">\(i\)</span>-th
data-point <span class="math notranslate nohighlight">\(\bf x_i\)</span> to the <span class="math notranslate nohighlight">\(k\)</span>-th cluster.</p>
<p><span class="math notranslate nohighlight">\(k\)</span>-means algorithm in words:</p>
<ol class="simple">
<li><p>We start with guesses / random initializations of our <span class="math notranslate nohighlight">\(k\)</span> cluster centers/centroids</p></li>
<li><p>For each centroid the points that are most similar are identified</p></li>
<li><p>Then we move / replace each centroid with a coordinate average of all the points that were assigned to that centroid.</p></li>
<li><p>Iterate 2-3 until the centroids no longer move (to some tolerance)</p></li>
</ol>
<p>We assume we have <span class="math notranslate nohighlight">\(n\)</span> data-points</p>
<!-- Equation labels as ordinary links -->
<div id="eq:kmeanspoints"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}\label{eq:kmeanspoints} \tag{1}
\boldsymbol{x_i} = \{x_{i, 1}, \cdots, x_{i, p}\}\in\mathbb{R}^p.
\end{equation}
\]</div>
<p>which we wish to group into <span class="math notranslate nohighlight">\(K &lt; n\)</span> clusters. For our dissimilarity measure we
use the <em>squared Euclidean distance</em></p>
<!-- Equation labels as ordinary links -->
<div id="eq:squaredeuclidean"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}\label{eq:squaredeuclidean} \tag{2}
d(\boldsymbol{x_i}, \boldsymbol{x_i'}) = \sum_{j=1}^p(x_{ij} - x_{i'j})^2
= ||\boldsymbol{x_i} - \boldsymbol{x_{i'}}||^2
\end{equation}
\]</div>
<p>We define the so called <em>within-cluster point scatter</em> which gives us a
measure of how close each data point assigned to the same cluster tends to be to
the all the others.</p>
<!-- Equation labels as ordinary links -->
<div id="eq:withincluster"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}\label{eq:withincluster} \tag{3}
W(C) = \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k}
\sum_{C(i')=k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}}) =
\sum_{k=1}^KN_k\sum_{C(i)=k}||\boldsymbol{x_i} - \boldsymbol{\overline{x_k}}||^2
\end{equation}
\]</div>
<p>where <span class="math notranslate nohighlight">\(\boldsymbol{\overline{x_k}}\)</span> is the mean vector associated with the <span class="math notranslate nohighlight">\(k\)</span>-th
cluster, and <span class="math notranslate nohighlight">\(N_k = \sum_{i=1}^nI(C(i) = k)\)</span>, where the <span class="math notranslate nohighlight">\(I()\)</span> notation is
similar to the Kronecker delta (<em>Commonly used in statistics, it just means that
when <span class="math notranslate nohighlight">\(i = k\)</span> we have the encoder <span class="math notranslate nohighlight">\(C(i)\)</span></em>). In other words, the within-cluster
scatter measures the compactness of each cluster with respect to the data points
assigned to each cluster. This is the quantity that the <span class="math notranslate nohighlight">\(k\)</span>-means algorithm aims
to minimize. We refer to this quantity <span class="math notranslate nohighlight">\(W(C)\)</span> as the within cluster scatter
because of its relation to the <em>total scatter</em>.</p>
<p>We have</p>
<!-- Equation labels as ordinary links -->
<div id="eq:totalscatter"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}\label{eq:totalscatter} \tag{4}
T = W(C) + B(C) = \frac{1}{2}\sum_{i=1}^n
\sum_{i'=1}^nd(\boldsymbol{x_i}, \boldsymbol{x_{i'}})
= \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k}
\Big(\sum_{C(i') = k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}})
+ \sum_{C(i')\neq k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}})\Big).
\end{equation}
\]</div>
<p>This is a quantity that is conserved throughout the <span class="math notranslate nohighlight">\(k\)</span>-means algorithm. It can
be thought of as the total amount of information in the data, and it is composed
of the aforementioned within-cluster scatter and the <em>between-cluster scatter</em>
<span class="math notranslate nohighlight">\(B(C)\)</span>. In methods such as principle component analysis the total scatter is not
conserved.</p>
<p>Given a cluster mean <span class="math notranslate nohighlight">\(\boldsymbol{m_k}\)</span> we define the <strong>total cluster variance</strong></p>
<!-- Equation labels as ordinary links -->
<div id="eq:totalclustervariance"></div>
<div class="math notranslate nohighlight">
\[
\begin{equation}\label{eq:totalclustervariance} \tag{5}
\min_{C, \{\boldsymbol{m_k}\}_1^K}\sum_{k=1}^KN_k\sum||\boldsymbol{x_i} - \boldsymbol{m_k}||^2
\end{equation}
\]</div>
<p>Now we have all the pieces necessary to formally revisit the <span class="math notranslate nohighlight">\(k\)</span>-means algorithm.</p>
<p>The <span class="math notranslate nohighlight">\(k\)</span>-means clustering algorithm goes as follows</p>
<ol class="simple">
<li><p>For a given cluster assignment <span class="math notranslate nohighlight">\(C\)</span>, and <span class="math notranslate nohighlight">\(k\)</span> cluster means <span class="math notranslate nohighlight">\(\left\{m_1, \cdots, m_k\right\}\)</span>. We minimize the total cluster variance with respect to the cluster means <span class="math notranslate nohighlight">\(\{m_k\}\)</span> yielding the means of the currently assigned clusters.</p></li>
<li><p>Given a current set of <span class="math notranslate nohighlight">\(k\)</span> means <span class="math notranslate nohighlight">\(\{m_k\}\)</span> the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $<span class="math notranslate nohighlight">\(C(i) = \underset{1\leq k\leq K}{\mathrm{argmin}} ||\boldsymbol{x_i} - \boldsymbol{m_k}||^2\)</span>$</p></li>
<li><p>Steps 1 and 2 are repeated until the assignments do not change.</p></li>
</ol>
<div class="section" id="codes-and-approaches">
<h2><span class="section-number">12.1. </span>Codes and Approaches<a class="headerlink" href="#codes-and-approaches" title="Permalink to this headline"></a></h2>
<ol class="simple">
<li><p>Before we start we specify a number <span class="math notranslate nohighlight">\(k\)</span> which is the number of clusters we want to try to separate our data into.</p></li>
<li><p>We initially choose <span class="math notranslate nohighlight">\(k\)</span> random data points in our data as our initial centroids, <em>or means</em> (this is where the name comes from).</p></li>
<li><p>Assign each data point to their closest centroid, based on the squared Euclidean distance.</p></li>
<li><p>For each of the <span class="math notranslate nohighlight">\(k\)</span> cluster we update the centroid by calculating new mean values for all the data points in the cluster.</p></li>
<li><p>Iteratively minimize the within cluster scatter by performing steps (3, 4) until the new assignments stop changing (can be to some tolerance) or until a maximum number of iterations have passed.</p></li>
</ol>
<p>Let us now program the most basic version of the algorithm using nothing but
Python with numpy arrays. This code is kept intentionally simple to gradually
progress our understanding. There is no vectorization of any kind, and even most
helper functions are not utilized.</p>
<p>We need first a dataset to do our cluster analysis on. In our case
this is a plain <em>vanilla</em> data set using random numbers using a
Gaussian distribution.</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">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">tensorflow</span> <span class="k">as</span> <span class="nn">tf</span>
<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="kn">import</span> <span class="n">image</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">from</span> <span class="nn">sklearn.cluster</span> <span class="kn">import</span> <span class="n">KMeans</span>
<span class="kn">from</span> <span class="nn">IPython.display</span> <span class="kn">import</span> <span class="n">display</span>
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">2021</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>Next we define functions, for ease of use later, to generate Gaussians and to
set up our toy data set.</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="k">def</span> <span class="nf">gaussian_points</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">n_points</span><span class="o">=</span><span class="mi">1000</span><span class="p">,</span> <span class="n">mean_vector</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">]),</span>
<span class="n">sample_variance</span><span class="o">=</span><span class="mi">1</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd"> Very simple custom function to generate gaussian distributed point clusters</span>
<span class="sd"> with variable dimension, number of points, means in each direction</span>
<span class="sd"> (must match dim) and sample variance.</span>
<span class="sd"> Inputs:</span>
<span class="sd"> dim (int)</span>
<span class="sd"> n_points (int)</span>
<span class="sd"> mean_vector (np.array) (where index 0 is x, index 1 is y etc.)</span>
<span class="sd"> sample_variance (float)</span>
<span class="sd"> Returns:</span>
<span class="sd"> data (np.array): with dimensions (dim x n_points)</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="n">mean_matrix</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="n">dim</span><span class="p">)</span> <span class="o">+</span> <span class="n">mean_vector</span>
<span class="n">covariance_matrix</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="n">dim</span><span class="p">)</span> <span class="o">*</span> <span class="n">sample_variance</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">multivariate_normal</span><span class="p">(</span><span class="n">mean_matrix</span><span class="p">,</span> <span class="n">covariance_matrix</span><span class="p">,</span>
<span class="n">n_points</span><span class="p">)</span>
<span class="k">return</span> <span class="n">data</span>
<span class="k">def</span> <span class="nf">generate_simple_clustering_dataset</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">n_points</span><span class="o">=</span><span class="mi">1000</span><span class="p">,</span> <span class="n">plotting</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="n">return_data</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd"> Toy model to illustrate k-means clustering</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="n">data1</span> <span class="o">=</span> <span class="n">gaussian_points</span><span class="p">(</span><span class="n">mean_vector</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">5</span><span class="p">,</span> <span class="mi">5</span><span class="p">]))</span>
<span class="n">data2</span> <span class="o">=</span> <span class="n">gaussian_points</span><span class="p">()</span>
<span class="n">data3</span> <span class="o">=</span> <span class="n">gaussian_points</span><span class="p">(</span><span class="n">mean_vector</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mf">4.5</span><span class="p">]))</span>
<span class="n">data4</span> <span class="o">=</span> <span class="n">gaussian_points</span><span class="p">(</span><span class="n">mean_vector</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">]))</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">concatenate</span><span class="p">((</span><span class="n">data1</span><span class="p">,</span> <span class="n">data2</span><span class="p">,</span> <span class="n">data3</span><span class="p">,</span> <span class="n">data4</span><span class="p">),</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="k">if</span> <span class="n">plotting</span><span class="p">:</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">()</span>
<span class="n">ax</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">data</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">],</span> <span class="n">data</span><span class="p">[:,</span> <span class="mi">1</span><span class="p">],</span> <span class="n">alpha</span><span class="o">=</span><span class="mf">0.2</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;Toy Model Dataset&#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="k">if</span> <span class="n">return_data</span><span class="p">:</span>
<span class="k">return</span> <span class="n">data</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">generate_simple_clustering_dataset</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/clustering_17_0.png" src="_images/clustering_17_0.png" />
</div>
</div>
<p>With the above dataset we start
implementing the <span class="math notranslate nohighlight">\(k\)</span>-means algorithm.</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="n">n_samples</span><span class="p">,</span> <span class="n">dimensions</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">shape</span>
<span class="n">n_clusters</span> <span class="o">=</span> <span class="mi">4</span>
<span class="c1"># we randomly initialize our centroids</span>
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">2021</span><span class="p">)</span>
<span class="n">centroids</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">(</span><span class="n">n_samples</span><span class="p">,</span> <span class="n">n_clusters</span><span class="p">,</span> <span class="n">replace</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span> <span class="p">:]</span>
<span class="n">distances</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="n">n_samples</span><span class="p">,</span> <span class="n">n_clusters</span><span class="p">))</span>
<span class="c1"># first we need to calculate the distance to each centroid from our data</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">dimensions</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">+=</span> <span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">d</span><span class="p">]</span> <span class="o">-</span> <span class="n">centroids</span><span class="p">[</span><span class="n">k</span><span class="p">,</span> <span class="n">d</span><span class="p">])</span><span class="o">**</span><span class="mi">2</span>
<span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">dist</span>
<span class="c1"># we initialize an array to keep track of to which cluster each point belongs</span>
<span class="c1"># the way we set it up here the index tracks which point and the value which</span>
<span class="c1"># cluster the point belongs to</span>
<span class="n">cluster_labels</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="n">n_samples</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="s1">&#39;int&#39;</span><span class="p">)</span>
<span class="c1"># next we loop through our samples and for every point assign it to the cluster</span>
<span class="c1"># to which it has the smallest distance to</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="c1"># tracking variables (all of this is basically just an argmin)</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">if</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">smallest</span><span class="p">:</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="n">k</span>
<span class="n">cluster_labels</span><span class="p">[</span><span class="n">n</span><span class="p">]</span> <span class="o">=</span> <span class="n">smallest_row_index</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></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="n">unique_cluster_labels</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">unique</span><span class="p">(</span><span class="n">cluster_labels</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">unique_cluster_labels</span><span class="p">:</span>
<span class="n">ax</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">cluster_labels</span> <span class="o">==</span> <span class="n">i</span><span class="p">,</span> <span class="mi">0</span><span class="p">],</span>
<span class="n">data</span><span class="p">[</span><span class="n">cluster_labels</span> <span class="o">==</span> <span class="n">i</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span>
<span class="n">label</span> <span class="o">=</span> <span class="n">i</span><span class="p">,</span>
<span class="n">alpha</span> <span class="o">=</span> <span class="mf">0.2</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">centroids</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">],</span> <span class="n">centroids</span><span class="p">[:,</span> <span class="mi">1</span><span class="p">],</span> <span class="n">c</span><span class="o">=</span><span class="s1">&#39;black&#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="s2">&quot;First Grouping of Points to Centroids&quot;</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/clustering_20_0.png" src="_images/clustering_20_0.png" />
</div>
</div>
<p>So what do we have so far? We have picked <span class="math notranslate nohighlight">\(k\)</span> centroids at random from our
data points. There are other ways of more intelligently choosing their
initializations, however for our purposes randomly is fine. Then we have
initialized an array distances which holds the information of the distance,
<em>or dissimilarity</em>, of every point to of our centroids. Finally, we have
initialized an array cluster_labels which according to our distances array
holds the information of to which centroid every point is assigned. This was the
first pass of our algorithm. Essentially, all we need to do now is repeat the
distance and assignment steps above until we have reached a desired convergence
or a maximum amount of iterations.</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="n">max_iterations</span> <span class="o">=</span> <span class="mi">100</span>
<span class="n">tolerance</span> <span class="o">=</span> <span class="mf">1e-8</span>
<span class="k">for</span> <span class="n">iteration</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">max_iterations</span><span class="p">):</span>
<span class="n">prev_centroids</span> <span class="o">=</span> <span class="n">centroids</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="c1"># this array will be used to update our centroid positions</span>
<span class="n">vector_mean</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="n">dimensions</span><span class="p">)</span>
<span class="n">mean_divisor</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="k">if</span> <span class="n">cluster_labels</span><span class="p">[</span><span class="n">n</span><span class="p">]</span> <span class="o">==</span> <span class="n">k</span><span class="p">:</span>
<span class="n">vector_mean</span> <span class="o">+=</span> <span class="n">data</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="p">:]</span>
<span class="n">mean_divisor</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="c1"># update according to the k means</span>
<span class="n">centroids</span><span class="p">[</span><span class="n">k</span><span class="p">,</span> <span class="p">:]</span> <span class="o">=</span> <span class="n">vector_mean</span> <span class="o">/</span> <span class="n">mean_divisor</span>
<span class="c1"># we find the dissimilarity</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">dimensions</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">+=</span> <span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">d</span><span class="p">]</span> <span class="o">-</span> <span class="n">centroids</span><span class="p">[</span><span class="n">k</span><span class="p">,</span> <span class="n">d</span><span class="p">])</span><span class="o">**</span><span class="mi">2</span>
<span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">dist</span>
<span class="c1"># assign each point</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">if</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">smallest</span><span class="p">:</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="n">k</span>
<span class="n">cluster_labels</span><span class="p">[</span><span class="n">n</span><span class="p">]</span> <span class="o">=</span> <span class="n">smallest_row_index</span>
<span class="c1"># convergence criteria</span>
<span class="n">centroid_difference</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">centroids</span> <span class="o">-</span> <span class="n">prev_centroids</span><span class="p">))</span>
<span class="k">if</span> <span class="n">centroid_difference</span> <span class="o">&lt;</span> <span class="n">tolerance</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Converged at iteration </span><span class="si">{</span><span class="n">iteration</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="k">break</span>
<span class="k">elif</span> <span class="n">iteration</span> <span class="o">==</span> <span class="n">max_iterations</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Did not converge in </span><span class="si">{</span><span class="n">max_iterations</span><span class="si">}</span><span class="s1"> iterations&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Converged at iteration 5
</pre></div>
</div>
</div>
</div>
<p>We now have a simple , un-optimized <span class="math notranslate nohighlight">\(k\)</span>-means
clustering implementation. Lets plot the final result</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="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="n">unique_cluster_labels</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">unique</span><span class="p">(</span><span class="n">cluster_labels</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">unique_cluster_labels</span><span class="p">:</span>
<span class="n">ax</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">cluster_labels</span> <span class="o">==</span> <span class="n">i</span><span class="p">,</span> <span class="mi">0</span><span class="p">],</span>
<span class="n">data</span><span class="p">[</span><span class="n">cluster_labels</span> <span class="o">==</span> <span class="n">i</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span>
<span class="n">label</span> <span class="o">=</span> <span class="n">i</span><span class="p">,</span>
<span class="n">alpha</span> <span class="o">=</span> <span class="mf">0.2</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">centroids</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">],</span> <span class="n">centroids</span><span class="p">[:,</span> <span class="mi">1</span><span class="p">],</span> <span class="n">c</span><span class="o">=</span><span class="s1">&#39;black&#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="s2">&quot;Final Result of K-means Clustering&quot;</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/clustering_24_0.png" src="_images/clustering_24_0.png" />
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">naive_kmeans</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">n_clusters</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">max_iterations</span><span class="o">=</span><span class="mi">100</span><span class="p">,</span> <span class="n">tolerance</span><span class="o">=</span><span class="mf">1e-8</span><span class="p">):</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="n">n_samples</span><span class="p">,</span> <span class="n">dimensions</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">shape</span>
<span class="n">n_clusters</span> <span class="o">=</span> <span class="mi">4</span>
<span class="c1">#np.random.seed(2021)</span>
<span class="n">centroids</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">(</span><span class="n">n_samples</span><span class="p">,</span> <span class="n">n_clusters</span><span class="p">,</span> <span class="n">replace</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span> <span class="p">:]</span>
<span class="n">distances</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="n">n_samples</span><span class="p">,</span> <span class="n">n_clusters</span><span class="p">))</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">dimensions</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">+=</span> <span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">d</span><span class="p">]</span> <span class="o">-</span> <span class="n">centroids</span><span class="p">[</span><span class="n">k</span><span class="p">,</span> <span class="n">d</span><span class="p">])</span><span class="o">**</span><span class="mi">2</span>
<span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">dist</span>
<span class="n">cluster_labels</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="n">n_samples</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="s1">&#39;int&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">if</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">smallest</span><span class="p">:</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="n">k</span>
<span class="n">cluster_labels</span><span class="p">[</span><span class="n">n</span><span class="p">]</span> <span class="o">=</span> <span class="n">smallest_row_index</span>
<span class="k">for</span> <span class="n">iteration</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">max_iterations</span><span class="p">):</span>
<span class="n">prev_centroids</span> <span class="o">=</span> <span class="n">centroids</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="n">vector_mean</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="n">dimensions</span><span class="p">)</span>
<span class="n">mean_divisor</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="k">if</span> <span class="n">cluster_labels</span><span class="p">[</span><span class="n">n</span><span class="p">]</span> <span class="o">==</span> <span class="n">k</span><span class="p">:</span>
<span class="n">vector_mean</span> <span class="o">+=</span> <span class="n">data</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="p">:]</span>
<span class="n">mean_divisor</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="n">centroids</span><span class="p">[</span><span class="n">k</span><span class="p">,</span> <span class="p">:]</span> <span class="o">=</span> <span class="n">vector_mean</span> <span class="o">/</span> <span class="n">mean_divisor</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">dimensions</span><span class="p">):</span>
<span class="n">dist</span> <span class="o">+=</span> <span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">d</span><span class="p">]</span> <span class="o">-</span> <span class="n">centroids</span><span class="p">[</span><span class="n">k</span><span class="p">,</span> <span class="n">d</span><span class="p">])</span><span class="o">**</span><span class="mi">2</span>
<span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">dist</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_samples</span><span class="p">):</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="mf">1e10</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_clusters</span><span class="p">):</span>
<span class="k">if</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span> <span class="o">&lt;</span> <span class="n">smallest</span><span class="p">:</span>
<span class="n">smallest</span> <span class="o">=</span> <span class="n">distances</span><span class="p">[</span><span class="n">n</span><span class="p">,</span> <span class="n">k</span><span class="p">]</span>
<span class="n">smallest_row_index</span> <span class="o">=</span> <span class="n">k</span>
<span class="n">cluster_labels</span><span class="p">[</span><span class="n">n</span><span class="p">]</span> <span class="o">=</span> <span class="n">smallest_row_index</span>
<span class="n">centroid_difference</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">centroids</span> <span class="o">-</span> <span class="n">prev_centroids</span><span class="p">))</span>
<span class="k">if</span> <span class="n">centroid_difference</span> <span class="o">&lt;</span> <span class="n">tolerance</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Converged at iteration </span><span class="si">{</span><span class="n">iteration</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Runtime: </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span><span class="si">}</span><span class="s1"> seconds&#39;</span><span class="p">)</span>
<span class="k">return</span> <span class="n">cluster_labels</span><span class="p">,</span> <span class="n">centroids</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Did not converge in </span><span class="si">{</span><span class="n">max_iterations</span><span class="si">}</span><span class="s1"> iterations&#39;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Runtime: </span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span><span class="si">}</span><span class="s1"> seconds&#39;</span><span class="p">)</span>
<span class="k">return</span> <span class="n">cluster_labels</span><span class="p">,</span> <span class="n">centroids</span>
</pre></div>
</div>
</div>
</div>
</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 class='prev-next-bottom'>
<div id="prev">
<a class="left-prev" href="chapter8.html" title="previous page">
<i class="prevnext-label fas fa-angle-left"></i>
<div class="prevnext-info">
<p class="prevnext-label">previous</p>
<p class="prevnext-title"><span class="section-number">11. </span>Basic ideas of the Principal Component Analysis (PCA)</p>
</div>
</a>
</div>
<div id="next">
<a class="right-next" href="chapter9.html" title="next page">
<div class="prevnext-info">
<p class="prevnext-label">next</p>
<p class="prevnext-title"><span class="section-number">13. </span>Neural networks</p>
</div>
<i class="prevnext-label fas fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<p>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2021.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="_static/js/index.1c5a1a01449ed65a7b51.js"></script>
</body>
</html>
+18 -3
View File
@@ -188,6 +188,11 @@
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="clustering.html">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
@@ -197,17 +202,27 @@
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter9.html">
12. Neural networks
13. Neural networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter10.html">
13. Building a Feed Forward Neural Network
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter11.html">
14. Solving Differential Equations with Deep Learning
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
+18 -3
View File
@@ -196,6 +196,11 @@
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="clustering.html">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
@@ -205,17 +210,27 @@
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter9.html">
12. Neural networks
13. Neural networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter10.html">
13. Building a Feed Forward Neural Network
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter11.html">
14. Solving Differential Equations with Deep Learning
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
Binary file not shown.
+18 -3
View File
@@ -194,6 +194,11 @@
11. Basic ideas of the Principal Component Analysis (PCA)
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="clustering.html">
12. Clustering and Unsupervised Learning
</a>
</li>
</ul>
<p class="caption" role="heading">
<span class="caption-text">
@@ -203,17 +208,27 @@
<ul class="nav bd-sidenav">
<li class="toctree-l1">
<a class="reference internal" href="chapter9.html">
12. Neural networks
13. Neural networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter10.html">
13. Building a Feed Forward Neural Network
14. Building a Feed Forward Neural Network
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter11.html">
14. Solving Differential Equations with Deep Learning
15. Solving Differential Equations with Deep Learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter12.html">
16. Convolutional Neural Networks
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="chapter13.html">
17. Recurrent neural networks: Overarching view
</a>
</li>
</ul>
File diff suppressed because one or more lines are too long