buidl
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 78 KiB |
@@ -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
|
||||
}
|
||||
@@ -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 — Applied Data Analysis and Machine Learning</title>
|
||||
<title>14. Building a Feed Forward Neural Network — 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"> "/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_42331/2357089093.py"</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"> "/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47411/2259440937.py"</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 layer’s 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>
|
||||
|
||||
@@ -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 — Applied Data Analysis and Machine Learning</title>
|
||||
<title>15. Solving Differential Equations with Deep Learning — 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}} &= 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}} &= 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 <module>
|
||||
144 lmb = 0.001
|
||||
145
|
||||
--> 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.
|
||||
--> 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)
|
||||
---> 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."""
|
||||
---> 25 vjp, ans = _make_vjp(fun, x)
|
||||
26 if not vspace(ans).size == 1:
|
||||
27 raise TypeError("Grad only applies to real scalar-output functions. "
|
||||
|
||||
~/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()
|
||||
---> 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)
|
||||
---> 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))
|
||||
---> 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
|
||||
---> 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):
|
||||
---> 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)
|
||||
---> 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):
|
||||
----> 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)
|
||||
---> 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 <genexpr>(.0)
|
||||
40 if f_wrapped in notrace_primitives[node_constructor]:
|
||||
41 return f_wrapped(*argvals, **kwargs)
|
||||
---> 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 'dtype=object' 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 Euler’s method.</p>
|
||||
<p>Euler’s 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 'dtype=object' 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 'dtype=object' 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 'dtype=object' 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 'dtype=object' 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 <module>
|
||||
141 lmb = 0.01
|
||||
142
|
||||
--> 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):
|
||||
--> 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)
|
||||
---> 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."""
|
||||
---> 25 vjp, ans = _make_vjp(fun, x)
|
||||
26 if not vspace(ans).size == 1:
|
||||
27 raise TypeError("Grad only applies to real scalar-output functions. "
|
||||
|
||||
~/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()
|
||||
---> 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)
|
||||
---> 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))
|
||||
---> 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)
|
||||
---> 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)
|
||||
---> 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 "Returns a function that computes the exact Hessian."
|
||||
---> 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)
|
||||
---> 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())
|
||||
---> 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
|
||||
---> 88 arrays = [array(arr) for arr in arrays]
|
||||
89 if not arrays:
|
||||
90 raise ValueError('need at least one array to stack')
|
||||
|
||||
~/anaconda3/lib/python3.8/site-packages/autograd/numpy/numpy_wrapper.py in <listcomp>(.0)
|
||||
86 # primitives defined in this file
|
||||
87
|
||||
---> 88 arrays = [array(arr) for arr in arrays]
|
||||
89 if not arrays:
|
||||
90 raise ValueError('need at least one array to stack')
|
||||
|
||||
~/anaconda3/lib/python3.8/site-packages/autograd/core.py in vjp(g)
|
||||
12 def vjp(g): return vspace(x).zeros()
|
||||
13 else:
|
||||
---> 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)
|
||||
---> 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 <lambda>(g)
|
||||
65 "VJP of {} wrt argnum 0 not defined".format(fun.__name__))
|
||||
66 vjp = vjpfun(ans, *args, **kwargs)
|
||||
---> 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 <lambda>(g)
|
||||
421 A_ndim = anp.ndim(A)
|
||||
422 B_meta = anp.metadata(B)
|
||||
--> 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)
|
||||
--> 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)
|
||||
---> 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("VJP of {} wrt argnums {} not defined"
|
||||
35 .format(fun_name, parent_argnums))
|
||||
---> 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 "VJP of {} wrt argnums 0, 1 not defined".format(fun.__name__))
|
||||
76 vjp_0 = vjp_0_fun(ans, *args, **kwargs)
|
||||
---> 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)
|
||||
--> 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)
|
||||
---> 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):
|
||||
--> 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>
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>12. Neural networks — Applied Data Analysis and Machine Learning</title>
|
||||
<title>13. Neural networks — 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="3d")
|
||||
</pre></div>
|
||||
</div>
|
||||
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span><mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7fad10f9a280>
|
||||
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span><mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7fd098df3280>
|
||||
</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>[<matplotlib.lines.Line2D at 0x7fad20f69be0>]
|
||||
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[<matplotlib.lines.Line2D at 0x7fd0a9063be0>]
|
||||
</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">"Own inversion"</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">"sgdreg from scikit"</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">"Eigenvalues of Hessian Matrix:</span><span class="si">{</span><span class="n">EigValues</span><span class="si">}</span><span class="s2">"</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">"theta from own gd"</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">"theta from own sdg"</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">"r-"</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">"b-"</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">'ro'</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><
|
||||
<
|
||||
<
|
||||
!
|
||||
!
|
||||
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"><</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">"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">"</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">"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">"</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("The derivative of f8 is:",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">"The derivative of f9 is:"</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">"The derivative of f8 is:"</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 <module>
|
||||
9 x = np.array([1.0,0.0])
|
||||
TypeError Traceback (most recent call last)
|
||||
/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47735/1122558214.py in <module>
|
||||
9 x = 8.4
|
||||
10
|
||||
---> 11 print("The derivative of f9 is:",f9_grad(x))
|
||||
---> 11 print("The derivative of f8 is:",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])
|
||||
----> 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
|
||||
----> 4 x[2] = 3
|
||||
5 return x*2
|
||||
6
|
||||
7 f9_grad = grad(f9)
|
||||
|
||||
AttributeError: 'ArrayBox' object has no attribute 'dot'
|
||||
TypeError: 'ArrayBox' 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">"The derivative of f9 is:"</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">"Own inversion"</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">"Eigenvalues of Hessian Matrix:</span><span class="si">{</span><span class="n">EigValues</span><span class="si">}</span><span class="s2">"</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">"theta from own gd"</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">"r-"</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">"b-"</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">'ro'</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">'$x$'</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">'$y$'</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">'Random numbers '</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">"Own inversion"</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">"Eigenvalues of Hessian Matrix:</span><span class="si">{</span><span class="n">EigValues</span><span class="si">}</span><span class="s2">"</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">"theta from own gd"</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">"r-"</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">"b-"</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">'ro'</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">'$x$'</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">'$y$'</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">'Random numbers '</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">"theta from own sdg"</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">"Initial loss:"</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">"Trained loss:"</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 — 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 < 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 < 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">"""</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"> """</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">"""</span>
|
||||
<span class="sd"> Toy model to illustrate k-means clustering</span>
|
||||
<span class="sd"> """</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">'Toy Model Dataset'</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">'int'</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"><</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">'black'</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">"First Grouping of Points to Centroids"</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"><</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"><</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">'Converged at iteration </span><span class="si">{</span><span class="n">iteration</span><span class="si">}</span><span class="s1">'</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">'Did not converge in </span><span class="si">{</span><span class="n">max_iterations</span><span class="si">}</span><span class="s1"> iterations'</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">'black'</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">"Final Result of K-means Clustering"</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">'int'</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"><</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"><</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"><</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">'Converged at iteration </span><span class="si">{</span><span class="n">iteration</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'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'</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">'Did not converge in </span><span class="si">{</span><span class="n">max_iterations</span><span class="si">}</span><span class="s1"> iterations'</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'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'</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/>
|
||||
|
||||
© Copyright 2021.<br/>
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="_static/js/index.1c5a1a01449ed65a7b51.js"></script>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
|
||||
# doconce format html chapter10.do.txt --no_mako -->
|
||||
|
||||
# # Building a Feed Forward Neural Network
|
||||
#
|
||||
# We are now gong to develop an example based on the MNIST data
|
||||
@@ -33,9 +36,7 @@
|
||||
|
||||
# where $y \in \{0, 1\}$ and $\hat{\theta}$ represents the weights and biases
|
||||
# of our network.
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
# ## Defining the cost function
|
||||
#
|
||||
# Our cost function is given as (see the Logistic regression lectures)
|
||||
@@ -54,10 +55,8 @@
|
||||
#
|
||||
# $y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and
|
||||
#
|
||||
#
|
||||
# $y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$
|
||||
#
|
||||
#
|
||||
# i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$)..
|
||||
#
|
||||
# If $\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th
|
||||
@@ -86,8 +85,7 @@
|
||||
# See the logistic regression lectures for a full definition of the cost function.
|
||||
#
|
||||
# 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!
|
||||
#
|
||||
#
|
||||
|
||||
# ### Example: binary classification problem
|
||||
#
|
||||
# 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 $\beta$ as
|
||||
@@ -136,10 +134,8 @@
|
||||
# \frac{\partial \mathcal{C}(\hat{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.
|
||||
# $$
|
||||
|
||||
# In case we use another activation function than the logistic one, we need to evaluate other derivatives.
|
||||
#
|
||||
#
|
||||
#
|
||||
# In case we use another activation function than the logistic one, we need to evaluate other derivatives.
|
||||
|
||||
# ### The Softmax function
|
||||
#
|
||||
# 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 $z_i^l$, that is we need
|
||||
@@ -161,12 +157,10 @@
|
||||
# \frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right),
|
||||
# $$
|
||||
|
||||
# which in case of the simply binary model reduces to having $i=j$.
|
||||
#
|
||||
#
|
||||
# which in case of the simply binary model reduces to having $i=j$.
|
||||
|
||||
# ## Developing a code for doing neural networks with back propagation
|
||||
#
|
||||
#
|
||||
# One can identify a set of key steps when using neural networks to solve supervised learning problems:
|
||||
#
|
||||
# 1. Collect and pre-process data
|
||||
@@ -180,7 +174,7 @@
|
||||
# 5. Evaluate model performance on test data
|
||||
#
|
||||
# 6. Adjust hyperparameters (if necessary, network architecture)
|
||||
#
|
||||
|
||||
# ### Collect and pre-process data
|
||||
#
|
||||
# Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**
|
||||
@@ -350,7 +344,7 @@ print("Number of test images: " + str(len(X_test)))
|
||||
# $$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
# ### Layers
|
||||
#
|
||||
# * Input
|
||||
@@ -383,7 +377,6 @@ print("Number of test images: " + str(len(X_test)))
|
||||
# Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500
|
||||
# weights to the output layer.
|
||||
#
|
||||
#
|
||||
# Typically weights are initialized with small values distributed around zero, drawn from a uniform
|
||||
# or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless.
|
||||
#
|
||||
@@ -434,7 +427,6 @@ output_bias = np.zeros(n_categories) + 0.01
|
||||
# $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}}
|
||||
# {\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$
|
||||
#
|
||||
#
|
||||
# Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden
|
||||
# layer have the dimensions
|
||||
# $W_{hidden} = (n_{features}, n_{hidden})$,
|
||||
@@ -512,10 +504,8 @@ print("correct label for image 0: " + str(Y_train[0]))
|
||||
#
|
||||
# $$ y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$
|
||||
#
|
||||
#
|
||||
# $$ y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$
|
||||
#
|
||||
#
|
||||
# i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset.
|
||||
#
|
||||
# Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector.
|
||||
@@ -524,10 +514,8 @@ print("correct label for image 0: " + str(Y_train[0]))
|
||||
# In the one-hot representation only one of the terms in the loss function is non-zero, namely the
|
||||
# probability of the correct category $c'$
|
||||
# (i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong
|
||||
# you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\hat{\theta}$ represents the parameters of our network, i.e. all the weights and biases.
|
||||
#
|
||||
#
|
||||
#
|
||||
# you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\hat{\theta}$ represents the parameters of our network, i.e. all the weights and biases.
|
||||
|
||||
# ### Optimizing the cost function
|
||||
#
|
||||
# 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 *gradient descent* and its generalizations. The idea behind gradient descent
|
||||
@@ -557,8 +545,7 @@ print("correct label for image 0: " + str(Y_train[0]))
|
||||
# 2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
|
||||
#
|
||||
# The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).
|
||||
#
|
||||
#
|
||||
|
||||
# ### Regularization
|
||||
#
|
||||
# It is common to add an extra term to the cost function, proportional
|
||||
@@ -576,7 +563,6 @@ print("correct label for image 0: " + str(Y_train[0]))
|
||||
#
|
||||
# i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter.
|
||||
#
|
||||
#
|
||||
# In order to train the model, we need to calculate the derivative of
|
||||
# the cost function with respect to every bias and weight in the
|
||||
# network. In total our network has $(64 + 1)\times 50=3250$ weights in
|
||||
@@ -584,9 +570,8 @@ print("correct label for image 0: " + str(Y_train[0]))
|
||||
# layer ($+1$ for the bias), and the gradient must be calculated for
|
||||
# every parameter. We use the *backpropagation* algorithm discussed
|
||||
# above. This is a clever use of the chain rule that allows us to
|
||||
# calculate the gradient efficently.
|
||||
#
|
||||
#
|
||||
# calculate the gradient efficently.
|
||||
|
||||
# ### Matrix multiplication
|
||||
#
|
||||
# To more efficently train our network these equations are implemented using matrix operations.
|
||||
@@ -705,7 +690,6 @@ print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y
|
||||
# If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers.
|
||||
# Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/).
|
||||
#
|
||||
#
|
||||
# It is very natural to think of the network as an object, with specific instances of the network
|
||||
# being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below.
|
||||
|
||||
@@ -1000,7 +984,6 @@ plt.show()
|
||||
# clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or
|
||||
# NumPy arrays.
|
||||
#
|
||||
#
|
||||
# Tensorflow is an open source library machine learning library
|
||||
# developed by the Google Brain team for internal use. It was released
|
||||
# under the Apache 2.0 open source license in November 9, 2015.
|
||||
@@ -1023,18 +1006,11 @@ plt.show()
|
||||
# Then we will build (effectively) the same graph in Keras, to see just
|
||||
# how simple solving a machine learning problem can be.
|
||||
#
|
||||
# To install tensorflow on Unix/Linux systems, use pip as
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
pip3 install tensorflow
|
||||
|
||||
|
||||
# To install tensorflow on Unix/Linux systems, use pip as **pip3 install tensorflow**
|
||||
# and/or if you use **anaconda**, just write (or install from the graphical user interface)
|
||||
# (current release of CPU-only TensorFlow)
|
||||
|
||||
# In[ ]:
|
||||
# In[12]:
|
||||
|
||||
|
||||
conda create -n tf tensorflow
|
||||
@@ -1043,7 +1019,7 @@ conda activate tf
|
||||
|
||||
# To install the current release of GPU TensorFlow
|
||||
|
||||
# In[ ]:
|
||||
# In[13]:
|
||||
|
||||
|
||||
conda create -n tf-gpu tensorflow-gpu
|
||||
@@ -1054,7 +1030,7 @@ conda activate tf-gpu
|
||||
# that supports Tensorflow, CTNK and Theano as backends.
|
||||
# If you have Anaconda installed you may run the following command
|
||||
|
||||
# In[ ]:
|
||||
# In[14]:
|
||||
|
||||
|
||||
conda install keras
|
||||
@@ -1064,10 +1040,9 @@ conda install keras
|
||||
#
|
||||
# We will to a large extent use **keras** in this course.
|
||||
#
|
||||
#
|
||||
# Let us look again at the MINST data set.
|
||||
|
||||
# In[ ]:
|
||||
# In[15]:
|
||||
|
||||
|
||||
# import necessary packages
|
||||
@@ -1115,7 +1090,7 @@ for i, image in enumerate(digits.images[random_indices]):
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[ ]:
|
||||
# In[16]:
|
||||
|
||||
|
||||
from tensorflow.keras.layers import Input
|
||||
@@ -1137,7 +1112,7 @@ X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=t
|
||||
test_size=test_size)
|
||||
|
||||
|
||||
# In[ ]:
|
||||
# In[17]:
|
||||
|
||||
|
||||
|
||||
@@ -1160,7 +1135,7 @@ def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories
|
||||
return model
|
||||
|
||||
|
||||
# In[ ]:
|
||||
# In[18]:
|
||||
|
||||
|
||||
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
|
||||
@@ -1180,7 +1155,7 @@ for i, eta in enumerate(eta_vals):
|
||||
print()
|
||||
|
||||
|
||||
# In[ ]:
|
||||
# In[19]:
|
||||
|
||||
|
||||
# optional
|
||||
@@ -1218,7 +1193,7 @@ plt.show()
|
||||
|
||||
# ## The Breast Cancer Data, now with Keras
|
||||
|
||||
# In[ ]:
|
||||
# In[20]:
|
||||
|
||||
|
||||
|
||||
@@ -1405,7 +1380,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# training a neural network on a large dataset takes a lot of time, you
|
||||
# will only be able to explore a tiny part of the hyperparameter space.
|
||||
#
|
||||
#
|
||||
# * You can use randomized search.
|
||||
#
|
||||
# * Or use tools like [Oscar](http://oscar.calldesk.ai/), which implements more complex algorithms to help you find a good set of hyperparameters quickly.
|
||||
@@ -1422,11 +1396,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# and they need a huge amount
|
||||
# of training data. However, you will rarely have to train such networks from scratch: it is much more
|
||||
# common to reuse parts of a pretrained state-of-the-art network that performs a similar task.
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
# ## Which activation function should I use?
|
||||
#
|
||||
# The Back propagation algorithm we derived above works by going from
|
||||
@@ -1435,7 +1405,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# function with regards to each parameter in the network, it uses these
|
||||
# gradients to update each parameter with a Gradient Descent (GD) step.
|
||||
#
|
||||
#
|
||||
# Unfortunately for us, the gradients often get smaller and smaller as the
|
||||
# algorithm progresses down to the first hidden layers. As a result, the
|
||||
# GD update leaves the lower layer connection weights
|
||||
@@ -1451,9 +1420,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# neural networks suffer from unstable gradients, different layers may
|
||||
# learn at widely different speeds
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
# Although this unfortunate behavior has been empirically observed for
|
||||
# quite a while (it was one of the reasons why deep neural networks were
|
||||
# mostly abandoned for a long time), it is only around 2010 that
|
||||
@@ -1476,8 +1442,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# (the hyperbolic tangent function has a mean of 0 and behaves slightly
|
||||
# better than the logistic function in deep networks).
|
||||
#
|
||||
#
|
||||
#
|
||||
# Looking at the logistic activation function, when inputs become large
|
||||
# (negative or positive), the function saturates at 0 or 1, with a
|
||||
# derivative extremely close to 0. Thus when backpropagation kicks in,
|
||||
@@ -1496,8 +1460,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# its inputs, and we also need the gradients to have equal variance
|
||||
# before and after flowing through a layer in the reverse direction.
|
||||
#
|
||||
#
|
||||
#
|
||||
# One of the insights in the 2010 paper by Glorot and Bengio was that
|
||||
# the vanishing/exploding gradients problems were in part due to a poor
|
||||
# choice of activation function. Until then most people had assumed that
|
||||
@@ -1507,8 +1469,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# networks, in particular the ReLU activation function, mostly because
|
||||
# it does not saturate for positive values (and also because it is quite
|
||||
# fast to compute).
|
||||
#
|
||||
#
|
||||
|
||||
# ## The RELU function family
|
||||
#
|
||||
# The ReLU activation function suffers from a problem known as the dying
|
||||
@@ -1543,8 +1504,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# spare time and computing power, you can use cross-validation or
|
||||
# bootstrap to evaluate other activation functions.
|
||||
#
|
||||
#
|
||||
#
|
||||
# In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).
|
||||
#
|
||||
# It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.
|
||||
@@ -1554,7 +1513,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# * For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).
|
||||
#
|
||||
# * For regression tasks, you can simply use no activation function at all.
|
||||
#
|
||||
|
||||
# ## Batch Normalization
|
||||
#
|
||||
# Batch Normalization
|
||||
@@ -1568,7 +1527,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and
|
||||
# standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current
|
||||
# mini-batch, from this the name batch normalization.
|
||||
#
|
||||
|
||||
# ## Dropout
|
||||
#
|
||||
# It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but
|
||||
@@ -1578,7 +1537,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# The
|
||||
# hyperparameter $p$ is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore.
|
||||
# It is viewed as one of the most popular regularization techniques.
|
||||
#
|
||||
|
||||
# ## Gradient Clipping
|
||||
#
|
||||
# A popular technique to lessen the exploding gradients problem is to simply clip the gradients during
|
||||
@@ -1589,11 +1548,9 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
#
|
||||
# In general however, Batch
|
||||
# Normalization is preferred.
|
||||
#
|
||||
#
|
||||
|
||||
# ## A top-down perspective on Neural networks
|
||||
#
|
||||
#
|
||||
# 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
|
||||
@@ -1604,7 +1561,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# do not use any of the test data to train the algorithm. This is a
|
||||
# cardinal sin in ML. Then:
|
||||
#
|
||||
#
|
||||
# * Estimate optimal error rate
|
||||
#
|
||||
# * Minimize underfitting (bias) on training data set.
|
||||
@@ -1629,8 +1585,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
# on these two validation sets quantifies the train-test mismatch. This
|
||||
# can serve as another important diagnostic when using DNNs for
|
||||
# supervised learning.
|
||||
#
|
||||
#
|
||||
|
||||
# ## Limitations of supervised learning with deep networks
|
||||
#
|
||||
# Like all statistical methods, supervised learning using neural
|
||||
@@ -1643,8 +1598,6 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
#
|
||||
# Here we list some of the important limitations of supervised neural network based models.
|
||||
#
|
||||
#
|
||||
#
|
||||
# * **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
|
||||
#
|
||||
# * **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
|
||||
|
||||
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 28 KiB |
@@ -1,13 +1,15 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
|
||||
# doconce format html chapter11.do.txt -->
|
||||
|
||||
# # Solving Differential Equations with Deep Learning
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
#
|
||||
# An ordinary differential equation (ODE) is an equation involving functions having one variable.
|
||||
#
|
||||
# In general, an ordinary differential equation looks like
|
||||
@@ -29,8 +31,6 @@
|
||||
# Along with ([1](#ode)), some additional conditions of the function $g(x)$ are typically given
|
||||
# for the solution to be unique.
|
||||
#
|
||||
#
|
||||
#
|
||||
# Let the trial solution $g_t(x)$ be
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
@@ -54,11 +54,8 @@
|
||||
#
|
||||
# But what about the network $N(x,P)$?
|
||||
#
|
||||
#
|
||||
# As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation.
|
||||
#
|
||||
#
|
||||
#
|
||||
# For the minimization to be defined, we need to have a cost function at hand to minimize.
|
||||
#
|
||||
# It is given that $f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)$ should be equal to zero in ([1](#ode)).
|
||||
@@ -85,15 +82,12 @@
|
||||
# The neural net should then find the parameters $P$ that minimizes the cost function in
|
||||
# ([3](#cost)) for a set of $N$ training samples $x_i$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# To perform the minimization using gradient descent, the gradient of $C\left(\boldsymbol{x}, P\right)$ is needed.
|
||||
# It might happen so that finding an analytical expression of the gradient of $C(\boldsymbol{x}, P)$ from ([3](#cost)) gets too messy, depending on which cost function one desires to use.
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
#
|
||||
|
||||
# ### Example: Exponential decay
|
||||
#
|
||||
# An exponential decay of a quantity $g(x)$ is described by the equation
|
||||
@@ -123,8 +117,6 @@
|
||||
|
||||
# Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of ([4](#solve_expdec)).
|
||||
#
|
||||
#
|
||||
#
|
||||
# The program will use a neural network to solve
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
@@ -140,7 +132,6 @@
|
||||
#
|
||||
# In this example, $\gamma = 2$ and $g_0 = 10$.
|
||||
#
|
||||
#
|
||||
# To begin with, a trial solution $g_t(t)$ must be chosen. A general trial solution for ordinary differential equations could be
|
||||
|
||||
# $$
|
||||
@@ -149,8 +140,6 @@
|
||||
|
||||
# with $h_1(x)$ ensuring that $g_t(x)$ satisfies some conditions and $h_2(x,N(x, P))$ an expression involving $x$ and the output from the neural network $N(x,P)$ with $P $ being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer.
|
||||
#
|
||||
#
|
||||
#
|
||||
# In this network, there are no weights and bias at the input layer, so $P = \{ P_{\text{hidden}}, P_{\text{output}} \}$.
|
||||
# If there are $N_{\text{hidden} }$ neurons in the hidden layer, then $P_{\text{hidden}}$ is a $N_{\text{hidden} } \times (1 + N_{\text{input}})$ matrix, given that there are $N_{\text{input}}$ neurons in the input layer.
|
||||
#
|
||||
@@ -198,7 +187,6 @@
|
||||
|
||||
# is fulfilled as *best as possible*.
|
||||
#
|
||||
#
|
||||
# The left hand side and right hand side of ([8](#nnmin)) must be computed separately, and then the neural network must choose weights and biases, contained in $P$, such that the sides are equal as best as possible.
|
||||
# This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.
|
||||
# In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to $P$ of the neural network.
|
||||
@@ -219,8 +207,6 @@
|
||||
|
||||
# for an input value $x$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# If the neural network evaluates $g_t(x, P)$ at more values for $x$, say $N$ values $x_i$ for $i = 1, \dots, N$, then the *total* error to minimize becomes
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
@@ -244,14 +230,12 @@
|
||||
# \min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\boldsymbol{x}, \{P_{\text{hidden} }, P_{\text{output} }\})
|
||||
# $$
|
||||
#
|
||||
#
|
||||
# For simplicity, it is assumed that the input is an array $\boldsymbol{x} = (x_1, \dots, x_N)$ with $N$ elements. It is at these points the neural network should find $P$ such that it fulfills ([9](#min)).
|
||||
#
|
||||
# First, the neural network must feed forward the inputs.
|
||||
# This means that $\boldsymbol{x}s$ must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further.
|
||||
# The input layer will consist of $N_{\text{input} }$ neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be $N_{\text{hidden} }$.
|
||||
#
|
||||
#
|
||||
# For the $i$-th in the hidden layer with weight $w_i^{\text{hidden} }$ and bias $b_i^{\text{hidden} }$, the weighting from the $j$-th neuron at the input layer is:
|
||||
|
||||
# $$
|
||||
@@ -311,8 +295,6 @@
|
||||
# and biases $b_i^{\text{output}}$. In this case,
|
||||
# it is assumes that the number of neurons in the output layer is one.
|
||||
#
|
||||
#
|
||||
#
|
||||
# The procedure of weighting the output neuron $j$ in the hidden layer to the $i$-th neuron in the output layer is similar as for the hidden layer described previously.
|
||||
|
||||
# $$
|
||||
@@ -343,7 +325,6 @@
|
||||
|
||||
# In this case we seek a continuous range of values since we are approximating a function. This means that after computing $\boldsymbol{z}_{1}^{\text{output}}$ the neural network has finished its feed forward step, and $\boldsymbol{z}_{1}^{\text{output}}$ is the final output of the network.
|
||||
#
|
||||
#
|
||||
# The next step is to decide how the parameters should be changed such that they minimize the cost function.
|
||||
#
|
||||
# The chosen cost function for this problem is
|
||||
@@ -355,7 +336,7 @@
|
||||
# In order to minimize the cost function, an optimization method must be chosen.
|
||||
#
|
||||
# Here, gradient descent with a constant step size has been chosen.
|
||||
#
|
||||
|
||||
# ### Gradient descent
|
||||
#
|
||||
# The idea of the gradient descent algorithm is to update parameters in
|
||||
@@ -734,8 +715,6 @@ if __name__ == '__main__':
|
||||
# using a library like TensorFlow is recommended.
|
||||
# Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method.
|
||||
#
|
||||
#
|
||||
#
|
||||
# Here, we will model a population $g(t)$ in an environment having carrying capacity $A$.
|
||||
# The population follows the model
|
||||
|
||||
@@ -752,7 +731,6 @@ if __name__ == '__main__':
|
||||
#
|
||||
# In this example, we let $\alpha = 2$, $A = 1$, and $g_0 = 1.2$.
|
||||
#
|
||||
#
|
||||
# We will get a slightly different trial solution, as the boundary conditions are different
|
||||
# compared to the case for exponential decay.
|
||||
#
|
||||
@@ -770,11 +748,9 @@ if __name__ == '__main__':
|
||||
# g(t) = \frac{Ag_0}{g_0 + (A - g_0)\exp(-\alpha A t)}
|
||||
# $$
|
||||
#
|
||||
#
|
||||
#
|
||||
# The network will be the similar as for the exponential decay example, but with some small modifications for our problem.
|
||||
|
||||
# In[ ]:
|
||||
# In[3]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
@@ -996,7 +972,7 @@ if __name__ == '__main__':
|
||||
# Equation ([12](#odenum)) could be implemented in the following way,
|
||||
# extending the program that uses the network using Autograd:
|
||||
|
||||
# In[ ]:
|
||||
# In[4]:
|
||||
|
||||
|
||||
# Assume that all function definitions from the example program using Autograd
|
||||
@@ -1094,7 +1070,6 @@ if __name__ == '__main__':
|
||||
# The results from the networks can then be compared to the analytical solution.
|
||||
# In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks.
|
||||
#
|
||||
#
|
||||
# Here, the function $g(x)$ to solve for follows the equation
|
||||
|
||||
# $$
|
||||
@@ -1126,7 +1101,7 @@ if __name__ == '__main__':
|
||||
# g(x) = x(1 - x)\exp(x)
|
||||
# $$
|
||||
|
||||
# In[ ]:
|
||||
# In[5]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
@@ -1372,10 +1347,9 @@ if __name__ == '__main__':
|
||||
|
||||
# which makes it possible to solve for the vector $\boldsymbol{g}$.
|
||||
#
|
||||
#
|
||||
# We can then compare the result from this numerical scheme with the output from our network using Autograd:
|
||||
|
||||
# In[ ]:
|
||||
# In[6]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
@@ -1589,7 +1563,7 @@ if __name__ == '__main__':
|
||||
# $$
|
||||
|
||||
# where $f$ is an expression involving all kinds of possible mixed derivatives of $g(x_1,\dots,x_N)$ up to an order $n$. In order for the solution to be unique, some additional conditions must also be given.
|
||||
#
|
||||
|
||||
# ### Type of problem
|
||||
#
|
||||
# The problem our network must solve for, is similar to the ODE case.
|
||||
@@ -1607,9 +1581,7 @@ if __name__ == '__main__':
|
||||
# The neural network $N(x_1,\dots,x_N,P)$ has weights and biases described by $P$ and $h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))$ is an expression using the output from the neural network in some way.
|
||||
#
|
||||
# The role of the function $h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))$, is to ensure that the output of $N(x_1,\dots,x_N,P)$ is zero when $g_t(x_1,\dots,x_N)$ is evaluated at the values of $x_1,\dots,x_N$ where the given conditions must be satisfied. The function $h_1(x_1,\dots,x_N)$ should alone make $g_t(x_1,\dots,x_N)$ satisfy the conditions.
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
# ### Network requirements
|
||||
#
|
||||
# The network tries then the minimize the cost function following the
|
||||
@@ -1658,8 +1630,6 @@ if __name__ == '__main__':
|
||||
|
||||
# with $u(x)$ being some given function.
|
||||
#
|
||||
#
|
||||
#
|
||||
# For this case, we want to find $g(x,t)$ such that
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
@@ -1687,9 +1657,6 @@ if __name__ == '__main__':
|
||||
# The deep neural network will follow the same structure as discussed in the examples solving the ODEs.
|
||||
# First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions.
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
# The only change to do here, is to extend our network such that
|
||||
# functions of multiple parameters are correctly handled. In this case
|
||||
# we have two variables in our function to solve for, that is time $t$
|
||||
@@ -1698,7 +1665,7 @@ if __name__ == '__main__':
|
||||
# network at each possible pair $(x,t)$, given an array for the desired
|
||||
# $x$-values and $t$-values to approximate the solution at.
|
||||
|
||||
# In[ ]:
|
||||
# In[7]:
|
||||
|
||||
|
||||
def sigmoid(z):
|
||||
@@ -1767,8 +1734,6 @@ def deep_neural_network(deep_params, x):
|
||||
# $$
|
||||
# since $(0) = u(1) = 0$ and $u(x) = \sin(\pi x)$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# The Jacobian is used because the program must find the derivative of
|
||||
# the trial solution with respect to $x$ and $t$.
|
||||
#
|
||||
@@ -1787,7 +1752,7 @@ def deep_neural_network(deep_params, x):
|
||||
# matrix, which is the matrix containing all the possible second order
|
||||
# mixed derivatives of $g(x,t)$.
|
||||
|
||||
# In[ ]:
|
||||
# In[8]:
|
||||
|
||||
|
||||
# Set up the trial function:
|
||||
@@ -1842,11 +1807,10 @@ def cost_function(P, x, t):
|
||||
# Be aware, though, that it is fairly slow for the parameters used.
|
||||
# A better result is possible, but requires more iterations, and thus longer time to complete.
|
||||
#
|
||||
#
|
||||
# Indeed, the program below is not optimal in its implementation, but rather serves as an example on how to implement and use a neural network to solve a PDE.
|
||||
# Using TensorFlow results in a much better execution time. Try it!
|
||||
|
||||
# In[ ]:
|
||||
# In[9]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
@@ -2097,7 +2061,6 @@ if __name__ == '__main__':
|
||||
|
||||
# where $\frac{\partial g(x,t)}{\partial t} \Big |_{t = 0}$ means the derivative of $g(x,t)$ with respect to $t$ is evaluated at $t = 0$, and $u(x)$ and $v(x)$ being given functions.
|
||||
#
|
||||
#
|
||||
# The wave equation to solve for, is
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
@@ -2126,8 +2089,6 @@ if __name__ == '__main__':
|
||||
|
||||
# In this example, let $c = 1$ and $u(x) = \sin(\pi x)$ and $v(x) = -\pi\sin(\pi x)$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# Setting up the network is done in similar matter as for the example of solving the diffusion equation.
|
||||
# The only things we have to change, is the trial solution such that it satisfies the conditions from ([20](#condwave)) and the cost function.
|
||||
#
|
||||
@@ -2145,14 +2106,13 @@ if __name__ == '__main__':
|
||||
#
|
||||
# Note that this trial solution satisfies the conditions only if $u(0) = v(0) = u(1) = v(1) = 0$, which is the case in this example.
|
||||
#
|
||||
#
|
||||
# The analytical solution for our specific problem, is
|
||||
#
|
||||
# $$
|
||||
# g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t)
|
||||
# $$
|
||||
|
||||
# In[ ]:
|
||||
# In[10]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
|
||||
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 27 KiB |
@@ -0,0 +1,921 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
|
||||
# doconce format html chapter12.do.txt -->
|
||||
|
||||
# # Convolutional Neural Networks
|
||||
#
|
||||
# Convolutional neural networks (CNNs) were developed during the last
|
||||
# decade of the previous century, with a focus on character recognition
|
||||
# tasks. Nowadays, CNNs are a central element in the spectacular success
|
||||
# of deep learning methods. The success in for example image
|
||||
# classifications have made them a central tool for most machine
|
||||
# learning practitioners.
|
||||
#
|
||||
# CNNs are very similar to ordinary Neural Networks.
|
||||
# They are made up of neurons that have learnable weights and
|
||||
# biases. Each neuron receives some inputs, performs a dot product and
|
||||
# optionally follows it with a non-linearity. The whole network still
|
||||
# expresses a single differentiable score function: from the raw image
|
||||
# pixels on one end to class scores at the other. And they still have a
|
||||
# loss function (for example Softmax) on the last (fully-connected) layer
|
||||
# and all the tips/tricks we developed for learning regular Neural
|
||||
# Networks still apply (back propagation, gradient descent etc etc).
|
||||
#
|
||||
# **CNN architectures make the explicit assumption that
|
||||
# the inputs are images, which allows us to encode certain properties
|
||||
# into the architecture. These then make the forward function more
|
||||
# efficient to implement and vastly reduce the amount of parameters in
|
||||
# the network.**
|
||||
#
|
||||
# Here we provide only a superficial overview, for the more interested, we recommend highly the course
|
||||
# [IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)
|
||||
# and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).
|
||||
#
|
||||
# Another good read is the article here <https://arxiv.org/pdf/1603.07285.pdf>.
|
||||
|
||||
# ## Neural Networks vs CNNs
|
||||
#
|
||||
# Neural networks are defined as **affine transformations**, that is
|
||||
# a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an
|
||||
# output (to which a bias vector is usually added before passing the result
|
||||
# through a nonlinear activation function). This is applicable to any type of input, be it an
|
||||
# image, a sound clip or an unordered collection of features: whatever their
|
||||
# dimensionality, their representation can always be flattened into a vector
|
||||
# before the transformation.
|
||||
#
|
||||
# However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic
|
||||
# structure. More formally, they share these important properties:
|
||||
# * They are stored as multi-dimensional arrays (think of the pixels of a figure) .
|
||||
#
|
||||
# * They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).
|
||||
#
|
||||
# * One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).
|
||||
#
|
||||
# These properties are not exploited when an affine transformation is applied; in
|
||||
# fact, all the axes are treated in the same way and the topological information
|
||||
# is not taken into account. Still, taking advantage of the implicit structure of
|
||||
# the data may prove very handy in solving some tasks, like computer vision and
|
||||
# speech recognition, and in these cases it would be best to preserve it. This is
|
||||
# where discrete convolutions come into play.
|
||||
#
|
||||
# A discrete convolution is a linear transformation that preserves this notion of
|
||||
# ordering. It is sparse (only a few input units contribute to a given output
|
||||
# unit) and reuses parameters (the same weights are applied to multiple locations
|
||||
# in the input).
|
||||
#
|
||||
# As an example, consider
|
||||
# an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a
|
||||
# single fully-connected neuron in a first hidden layer of a regular
|
||||
# Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still
|
||||
# seems manageable, but clearly this fully-connected structure does not
|
||||
# scale to larger images. For example, an image of more respectable
|
||||
# size, say $200\times 200\times 3$, would lead to neurons that have
|
||||
# $200\times 200\times 3 = 120,000$ weights.
|
||||
#
|
||||
# We could have
|
||||
# several such neurons, and the parameters would add up quickly! Clearly,
|
||||
# this full connectivity is wasteful and the huge number of parameters
|
||||
# would quickly lead to possible overfitting.
|
||||
#
|
||||
# <!-- dom:FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network. -->
|
||||
# <!-- begin figure -->
|
||||
#
|
||||
# <img src="figslides/nn.jpeg" width="500"><p style="font-size: 0.9em"><i>Figure 1: A regular 3-layer Neural Network.</i></p>
|
||||
# <!-- end figure -->
|
||||
#
|
||||
# Convolutional Neural Networks take advantage of the fact that the
|
||||
# input consists of images and they constrain the architecture in a more
|
||||
# sensible way.
|
||||
#
|
||||
# In particular, unlike a regular Neural Network, the
|
||||
# layers of a CNN have neurons arranged in 3 dimensions: width,
|
||||
# height, depth. (Note that the word depth here refers to the third
|
||||
# dimension of an activation volume, not to the depth of a full Neural
|
||||
# Network, which can refer to the total number of layers in a network.)
|
||||
#
|
||||
# To understand it better, the above example of an image
|
||||
# with an input volume of
|
||||
# activations has dimensions $32\times 32\times 3$ (width, height,
|
||||
# depth respectively).
|
||||
#
|
||||
# The neurons in a layer will
|
||||
# only be connected to a small region of the layer before it, instead of
|
||||
# all of the neurons in a fully-connected manner. Moreover, the final
|
||||
# output layer could for this specific image have dimensions $1\times 1 \times 10$,
|
||||
# because by the
|
||||
# end of the CNN architecture we will reduce the full image into a
|
||||
# single vector of class scores, arranged along the depth
|
||||
# dimension.
|
||||
#
|
||||
# <!-- dom:FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels). -->
|
||||
# <!-- begin figure -->
|
||||
#
|
||||
# <img src="figslides/cnn.jpeg" width="500"><p style="font-size: 0.9em"><i>Figure 1: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).</i></p>
|
||||
# <!-- end figure -->
|
||||
|
||||
# ## Layers used to build CNNs
|
||||
#
|
||||
# A simple CNN is a sequence of layers, and every layer of a CNN
|
||||
# transforms one volume of activations to another through a
|
||||
# differentiable function. We use three main types of layers to build
|
||||
# CNN architectures: Convolutional Layer, Pooling Layer, and
|
||||
# Fully-Connected Layer (exactly as seen in regular Neural Networks). We
|
||||
# will stack these layers to form a full CNN architecture.
|
||||
#
|
||||
# A simple CNN for image classification could have the architecture:
|
||||
#
|
||||
# * **INPUT** ($32\times 32 \times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
|
||||
#
|
||||
# * **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters.
|
||||
#
|
||||
# * **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\times 32\times 12]$).
|
||||
#
|
||||
# * **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$.
|
||||
#
|
||||
# * **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\times 1\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
|
||||
#
|
||||
# CNNs transform the original image layer by layer from the original
|
||||
# pixel values to the final class scores.
|
||||
#
|
||||
# Observe that some layers contain
|
||||
# parameters and other don’t. In particular, the CNN layers perform
|
||||
# transformations that are a function of not only the activations in the
|
||||
# input volume, but also of the parameters (the weights and biases of
|
||||
# the neurons). On the other hand, the RELU/POOL layers will implement a
|
||||
# fixed function. The parameters in the CONV/FC layers will be trained
|
||||
# with gradient descent so that the class scores that the CNN computes
|
||||
# are consistent with the labels in the training set for each image.
|
||||
#
|
||||
# In summary:
|
||||
#
|
||||
# * A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
|
||||
#
|
||||
# * There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
|
||||
#
|
||||
# * Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
|
||||
#
|
||||
# * Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
|
||||
#
|
||||
# * Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
|
||||
#
|
||||
# A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included.
|
||||
#
|
||||
# The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect
|
||||
# only neighboring neurons in the input instead of connecting all with the first hidden layer.
|
||||
#
|
||||
# We say we perform a filtering (convolution is the mathematical operation).
|
||||
|
||||
# ## Mathematics of CNNs
|
||||
#
|
||||
# The mathematics of CNNs is based on the mathematical operation of
|
||||
# **convolution**. In mathematics (in particular in functional analysis),
|
||||
# convolution is represented by matheematical operation (integration,
|
||||
# summation etc) on two function in order to produce a third function
|
||||
# that expresses how the shape of one gets modified by the other.
|
||||
# Convolution has a plethora of applications in a variety of disciplines, spanning from statistics to signal processing, computer vision, solutions of differential equations,linear algebra, engineering, and yes, machine learning.
|
||||
#
|
||||
# Mathematically, convolution is defined as follows (one-dimensional example):
|
||||
# Let us define a continuous function $y(t)$ given by
|
||||
|
||||
# $$
|
||||
# y(t) = \int x(a) w(t-a) da,
|
||||
# $$
|
||||
|
||||
# where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel.
|
||||
#
|
||||
# The above integral is written in a more compact form as
|
||||
|
||||
# $$
|
||||
# y(t) = \left(x * w\right)(t).
|
||||
# $$
|
||||
|
||||
# The discretized version reads
|
||||
|
||||
# $$
|
||||
# y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a).
|
||||
# $$
|
||||
|
||||
# Computing the inverse of the above convolution operations is known as deconvolution.
|
||||
#
|
||||
# How can we use this? And what does it mean? Let us study some familiar examples first.
|
||||
|
||||
# ### Convolution Examples: Polynomial multiplication
|
||||
#
|
||||
# We have already met such an example in project 1 when we tried to set
|
||||
# up the design matrix for a two-dimensional function. This was an
|
||||
# example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation.
|
||||
# Let us look a the following polynomials to second and third order, respectively:
|
||||
|
||||
# $$
|
||||
# p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2,
|
||||
# $$
|
||||
|
||||
# and
|
||||
|
||||
# $$
|
||||
# s(t) = \beta_0+\beta_1 t+\beta_2 t^2+\beta_3 t^3.
|
||||
# $$
|
||||
|
||||
# The polynomial multiplication gives us a new polynomial of degree $5$
|
||||
|
||||
# $$
|
||||
# z(t) = \delta_0+\delta_1 t+\delta_2 t^2+\delta_3 t^3+\delta_4 t^4+\delta_5 t^5.
|
||||
# $$
|
||||
|
||||
# Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution.
|
||||
# We note first that the new coefficients are given as
|
||||
|
||||
# $$
|
||||
# \begin{split}
|
||||
# \delta_0=&\alpha_0\beta_0\\
|
||||
# \delta_1=&\alpha_1\beta_0+\alpha_1\beta_0\\
|
||||
# \delta_2=&\alpha_0\beta_2+\alpha_1\beta_1+\alpha_2\beta_0\\
|
||||
# \delta_3=&\alpha_1\beta_2+\alpha_2\beta_1+\alpha_0\beta_3\\
|
||||
# \delta_4=&\alpha_2\beta_2+\alpha_1\beta_3\\
|
||||
# \delta_5=&\alpha_2\beta_3.\\
|
||||
# \end{split}
|
||||
# $$
|
||||
|
||||
# We note that $\alpha_i=0$ except for $i\in \left\{0,1,2\right\}$ and $\beta_i=0$ except for $i\in\left\{0,1,2,3\right\}$.
|
||||
#
|
||||
# We can then rewrite the coefficients $\delta_j$ using a discrete convolution as
|
||||
|
||||
# $$
|
||||
# \delta_j = \sum_{i=-\infty}^{i=\infty}\alpha_i\beta_{j-i}=(\alpha * \beta)_j,
|
||||
# $$
|
||||
|
||||
# or as a double sum with restriction $l=i+j$
|
||||
|
||||
# $$
|
||||
# \delta_l = \sum_{ij}\alpha_i\beta_{j}.
|
||||
# $$
|
||||
|
||||
# Do you see a potential drawback with these equations?
|
||||
#
|
||||
# Since we only have a finite number of $\alpha$ and $\beta$ values
|
||||
# which are non-zero, we can rewrite the above convolution expressions
|
||||
# as a matrix-vector multiplication
|
||||
|
||||
# $$
|
||||
# \boldsymbol{\delta}=\begin{bmatrix}\alpha_0 & 0 & 0 & 0 \\
|
||||
# \alpha_1 & \alpha_0 & 0 & 0 \\
|
||||
# \alpha_2 & \alpha_1 & \alpha_0 & 0 \\
|
||||
# 0 & \alpha_2 & \alpha_1 & \alpha_0 \\
|
||||
# 0 & 0 & \alpha_2 & \alpha_1 \\
|
||||
# 0 & 0 & 0 & \alpha_2
|
||||
# \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}.
|
||||
# $$
|
||||
|
||||
# The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding $\beta$ and a vector holding $\alpha$.
|
||||
# In this case we have
|
||||
|
||||
# $$
|
||||
# \boldsymbol{\delta}=\begin{bmatrix}\beta_0 & 0 & 0 \\
|
||||
# \beta_1 & \beta_0 & 0 \\
|
||||
# \beta_2 & \beta_1 & \beta_0 \\
|
||||
# \beta_3 & \beta_2 & \beta_1 \\
|
||||
# 0 & \beta_3 & \beta_2 \\
|
||||
# 0 & 0 & \beta_3
|
||||
# \end{bmatrix}\begin{bmatrix} \alpha_0 \\ \alpha_1 \\ \alpha_2\end{bmatrix}.
|
||||
# $$
|
||||
|
||||
# Note that the use of these matrices is for mathematical purposes only and not implementation purposes.
|
||||
# When implementing the above equation we do not encode (and allocate memory) the matrices explicitely.
|
||||
# We rather code the convolutions in the minimal memory footprint that they require.
|
||||
#
|
||||
# Does the number of floating point operations change here when we use the commutative property?
|
||||
|
||||
# ### Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms)
|
||||
#
|
||||
# For problems with so-called harmonic oscillations, given by for example the following differential equation
|
||||
|
||||
# $$
|
||||
# m\frac{d^2x}{dt^2}+\eta\frac{dx}{dt}+x(t)=F(t),
|
||||
# $$
|
||||
|
||||
# where $F(t)$ is an applied external force acting on the system (often called a driving force), one can use the theory of Fourier transformations to find the solutions of this type of equations.
|
||||
#
|
||||
# If one has several driving forces, $F(t)=\sum_n F_n(t)$, one can find
|
||||
# the particular solution to each $F_n$, $x_{pn}(t)$, and the particular
|
||||
# solution for the entire driving force is then given by a series like
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="_auto1"></div>
|
||||
#
|
||||
# $$
|
||||
# \begin{equation}
|
||||
# x_p(t)=\sum_nx_{pn}(t).
|
||||
# \label{_auto1} \tag{1}
|
||||
# \end{equation}
|
||||
# $$
|
||||
|
||||
# This is known as the principle of superposition. It only applies when
|
||||
# the homogenous equation is linear. If there were an anharmonic term
|
||||
# such as $x^3$ in the homogenous equation, then when one summed various
|
||||
# solutions, $x=(\sum_n x_n)^2$, one would get cross
|
||||
# terms. Superposition is especially useful when $F(t)$ can be written
|
||||
# as a sum of sinusoidal terms, because the solutions for each
|
||||
# sinusoidal (sine or cosine) term is analytic.
|
||||
#
|
||||
# Driving forces are often periodic, even when they are not
|
||||
# sinusoidal. Periodicity implies that for some time $\tau$
|
||||
|
||||
# $$
|
||||
# \begin{eqnarray}
|
||||
# F(t+\tau)=F(t).
|
||||
# \end{eqnarray}
|
||||
# $$
|
||||
|
||||
# One example of a non-sinusoidal periodic force is a square wave. Many
|
||||
# components in electric circuits are non-linear, e.g. diodes, which
|
||||
# makes many wave forms non-sinusoidal even when the circuits are being
|
||||
# driven by purely sinusoidal sources.
|
||||
#
|
||||
# The code here shows a typical example of such a square wave generated using the functionality included in the **scipy** Python package. We have used a period of $\tau=0.2$.
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
get_ipython().run_line_magic('matplotlib', 'inline')
|
||||
|
||||
import numpy as np
|
||||
import math
|
||||
from scipy import signal
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# number of points
|
||||
n = 500
|
||||
# start and final times
|
||||
t0 = 0.0
|
||||
tn = 1.0
|
||||
# Period
|
||||
t = np.linspace(t0, tn, n, endpoint=False)
|
||||
SqrSignal = np.zeros(n)
|
||||
SqrSignal = 1.0+signal.square(2*np.pi*5*t)
|
||||
plt.plot(t, SqrSignal)
|
||||
plt.ylim(-0.5, 2.5)
|
||||
plt.show()
|
||||
|
||||
|
||||
# For the sinusoidal example the
|
||||
# period is $\tau=2\pi/\omega$. However, higher harmonics can also
|
||||
# satisfy the periodicity requirement. In general, any force that
|
||||
# satisfies the periodicity requirement can be expressed as a sum over
|
||||
# harmonics,
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="_auto2"></div>
|
||||
#
|
||||
# $$
|
||||
# \begin{equation}
|
||||
# F(t)=\frac{f_0}{2}+\sum_{n>0} f_n\cos(2n\pi t/\tau)+g_n\sin(2n\pi t/\tau).
|
||||
# \label{_auto2} \tag{2}
|
||||
# \end{equation}
|
||||
# $$
|
||||
|
||||
# We can write down the answer for
|
||||
# $x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$. By
|
||||
# writing each factor $2n\pi t/\tau$ as $n\omega t$, with $\omega\equiv
|
||||
# 2\pi/\tau$,
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="eq:fourierdef1"></div>
|
||||
#
|
||||
# $$
|
||||
# \begin{equation}
|
||||
# \label{eq:fourierdef1} \tag{3}
|
||||
# F(t)=\frac{f_0}{2}+\sum_{n>0}f_n\cos(n\omega t)+g_n\sin(n\omega t).
|
||||
# \end{equation}
|
||||
# $$
|
||||
|
||||
# The solutions for $x(t)$ then come from replacing $\omega$ with
|
||||
# $n\omega$ for each term in the particular solution,
|
||||
|
||||
# $$
|
||||
# \begin{eqnarray}
|
||||
# x_p(t)&=&\frac{f_0}{2k}+\sum_{n>0} \alpha_n\cos(n\omega t-\delta_n)+\beta_n\sin(n\omega t-\delta_n),\\
|
||||
# \nonumber
|
||||
# \alpha_n&=&\frac{f_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
|
||||
# \nonumber
|
||||
# \beta_n&=&\frac{g_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
|
||||
# \nonumber
|
||||
# \delta_n&=&\tan^{-1}\left(\frac{2\beta n\omega}{\omega_0^2-n^2\omega^2}\right).
|
||||
# \end{eqnarray}
|
||||
# $$
|
||||
|
||||
# Because the forces have been applied for a long time, any non-zero
|
||||
# damping eliminates the homogenous parts of the solution, so one need
|
||||
# only consider the particular solution for each $n$.
|
||||
#
|
||||
# The problem is considered solved if one can find expressions for the
|
||||
# coefficients $f_n$ and $g_n$, even though the solutions are expressed
|
||||
# as an infinite sum. The coefficients can be extracted from the
|
||||
# function $F(t)$ by
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="eq:fourierdef2"></div>
|
||||
#
|
||||
# $$
|
||||
# \begin{eqnarray}
|
||||
# \label{eq:fourierdef2} \tag{4}
|
||||
# f_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\cos(2n\pi t/\tau),\\
|
||||
# \nonumber
|
||||
# g_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\sin(2n\pi t/\tau).
|
||||
# \end{eqnarray}
|
||||
# $$
|
||||
|
||||
# To check the consistency of these expressions and to verify
|
||||
# Eq. ([4](#eq:fourierdef2)), one can insert the expansion of $F(t)$ in
|
||||
# Eq. ([3](#eq:fourierdef1)) into the expression for the coefficients in
|
||||
# Eq. ([4](#eq:fourierdef2)) and see whether
|
||||
|
||||
# $$
|
||||
# \begin{eqnarray}
|
||||
# f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~\left\{
|
||||
# \frac{f_0}{2}+\sum_{m>0}f_m\cos(m\omega t)+g_m\sin(m\omega t)
|
||||
# \right\}\cos(n\omega t).
|
||||
# \end{eqnarray}
|
||||
# $$
|
||||
|
||||
# Immediately, one can throw away all the terms with $g_m$ because they
|
||||
# convolute an even and an odd function. The term with $f_0/2$
|
||||
# disappears because $\cos(n\omega t)$ is equally positive and negative
|
||||
# over the interval and will integrate to zero. For all the terms
|
||||
# $f_m\cos(m\omega t)$ appearing in the sum, one can use angle addition
|
||||
# formulas to see that $\cos(m\omega t)\cos(n\omega
|
||||
# t)=(1/2)(\cos[(m+n)\omega t]+\cos[(m-n)\omega t]$. This will integrate
|
||||
# to zero unless $m=n$. In that case the $m=n$ term gives
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="_auto3"></div>
|
||||
#
|
||||
# $$
|
||||
# \begin{equation}
|
||||
# \int_{-\tau/2}^{\tau/2}dt~\cos^2(m\omega t)=\frac{\tau}{2},
|
||||
# \label{_auto3} \tag{5}
|
||||
# \end{equation}
|
||||
# $$
|
||||
|
||||
# and
|
||||
|
||||
# $$
|
||||
# \begin{eqnarray}
|
||||
# f_n&=?&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~f_n/2\\
|
||||
# \nonumber
|
||||
# &=&f_n~\checkmark.
|
||||
# \end{eqnarray}
|
||||
# $$
|
||||
|
||||
# The same method can be used to check for the consistency of $g_n$.
|
||||
#
|
||||
# The code here uses the Fourier series applied to a
|
||||
# square wave signal. The code here
|
||||
# visualizes the various approximations given by Fourier series compared
|
||||
# with a square wave with period $T=0.2$ (dimensionless time), width $0.1$ and max value of the force $F=2$. We
|
||||
# see that when we increase the number of components in the Fourier
|
||||
# series, the Fourier series approximation gets closer and closer to the
|
||||
# square wave signal.
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
import math
|
||||
from scipy import signal
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# number of points
|
||||
n = 500
|
||||
# start and final times
|
||||
t0 = 0.0
|
||||
tn = 1.0
|
||||
# Period
|
||||
T =0.2
|
||||
# Max value of square signal
|
||||
Fmax= 2.0
|
||||
# Width of signal
|
||||
Width = 0.1
|
||||
t = np.linspace(t0, tn, n, endpoint=False)
|
||||
SqrSignal = np.zeros(n)
|
||||
FourierSeriesSignal = np.zeros(n)
|
||||
SqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)
|
||||
a0 = Fmax*Width/T
|
||||
FourierSeriesSignal = a0
|
||||
Factor = 2.0*Fmax/np.pi
|
||||
for i in range(1,500):
|
||||
FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)
|
||||
plt.plot(t, SqrSignal)
|
||||
plt.plot(t, FourierSeriesSignal)
|
||||
plt.ylim(-0.5, 2.5)
|
||||
plt.show()
|
||||
|
||||
|
||||
# ## Two-dimensional Objects
|
||||
#
|
||||
# We often use convolutions over more than one dimension at a time. If
|
||||
# we have a two-dimensional image $I$ as input, we can have a **filter**
|
||||
# defined by a two-dimensional **kernel** $K$. This leads to an output $S$
|
||||
|
||||
# $$
|
||||
# S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(m,n)K(i-m,j-n).
|
||||
# $$
|
||||
|
||||
# Convolution is a commutatitave process, which means we can rewrite this equation as
|
||||
|
||||
# $$
|
||||
# S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i-m,j-n)K(m,n).
|
||||
# $$
|
||||
|
||||
# Normally the latter is more straightforward to implement in a machine elarning library since there is less variation in the range of values of $m$ and $n$.
|
||||
#
|
||||
# Many deep learning libraries implement cross-correlation instead of convolution
|
||||
|
||||
# $$
|
||||
# S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i+m,j-+)K(m,n).
|
||||
# $$
|
||||
|
||||
# ## More on Dimensionalities
|
||||
#
|
||||
# In fields like signal processing (and imaging as well), one designs
|
||||
# so-called filters. These filters are defined by the convolutions and
|
||||
# are often hand-crafted. One may specify filters for smoothing, edge
|
||||
# detection, frequency reshaping, and similar operations. However with
|
||||
# neural networks the idea is to automatically learn the filters and use
|
||||
# many of them in conjunction with non-linear operations (activation
|
||||
# functions).
|
||||
#
|
||||
# As an example consider a neural network operating on sound sequence
|
||||
# data. Assume that we an input vector $\boldsymbol{x}$ of length $d=10^6$. We
|
||||
# construct then a neural network with onle hidden layer only with
|
||||
# $10^4$ nodes. This means that we will have a weight matrix with
|
||||
# $10^4\times 10^6=10^{10}$ weights to be determined, together with $10^4$ biases.
|
||||
#
|
||||
# Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false).
|
||||
# It means that we have only one output node. But since this output node connects to $10^4$ nodes in the hidden layer, there are in total $10^4$ weights to be determined for the output layer, plus one bias. In total we have
|
||||
|
||||
# $$
|
||||
# \mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \approx 10^{10},
|
||||
# $$
|
||||
|
||||
# that is ten billion parameters to determine.
|
||||
|
||||
# ## Further Dimensionality Remarks
|
||||
#
|
||||
# In today’s architecture one can train such neural networks, however
|
||||
# this is a huge number of parameters for the task at hand. In general,
|
||||
# it is a very wasteful and inefficient use of dense matrices as
|
||||
# parameters. Just as importantly, such trained network parameters are
|
||||
# very specific for the type of input data on which they were trained
|
||||
# and the network is not likely to generalize easily to variations in
|
||||
# the input.
|
||||
#
|
||||
# The main principles that justify convolutions is locality of
|
||||
# information and repetion of patterns within the signal. Sound samples
|
||||
# of the input in adjacent spots are much more likely to affect each
|
||||
# other than those that are very far away. Similarly, sounds are
|
||||
# repeated in multiple times in the signal. While slightly simplistic,
|
||||
# reasoning about such a sound example demonstrates this. The same
|
||||
# principles then apply to images and other similar data.
|
||||
|
||||
# ## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
|
||||
#
|
||||
# As discussed above, CNNs are neural networks built from the assumption that the inputs
|
||||
# to the network are 2D images. This is important because the number of features or pixels in images
|
||||
# grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
|
||||
#
|
||||
# As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
|
||||
# are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.
|
||||
# In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
|
||||
# matrices, typically 1 for each color dimension (Red, Green, Blue).
|
||||
#
|
||||
# It means that to represent the entire
|
||||
# dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:
|
||||
|
||||
# $$
|
||||
# (n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
|
||||
# $$
|
||||
|
||||
# ### The MNIST dataset again
|
||||
#
|
||||
# The MNIST dataset consists of grayscale images with a pixel size of
|
||||
# $28\times 28$, meaning we require $28 \times 28 = 724$ weights to each
|
||||
# neuron in the first hidden layer.
|
||||
#
|
||||
# If we were to analyze images of size $128\times 128$ we would require
|
||||
# $128 \times 128 = 16384$ weights to each neuron. Even worse if we were
|
||||
# dealing with color images, as most images are, we have an image matrix
|
||||
# of size $128\times 128$ for each color dimension (Red, Green, Blue),
|
||||
# meaning 3 times the number of weights $= 49152$ are required for every
|
||||
# single neuron in the first hidden layer.
|
||||
#
|
||||
# Images typically have strong local correlations, meaning that a small
|
||||
# part of the image varies little from its neighboring regions. If for
|
||||
# example we have an image of a blue car, we can roughly assume that a
|
||||
# small blue part of the image is surrounded by other blue regions.
|
||||
#
|
||||
# Therefore, instead of connecting every single pixel to a neuron in the
|
||||
# first hidden layer, as we have previously done with deep neural
|
||||
# networks, we can instead connect each neuron to a small part of the
|
||||
# image (in all 3 RGB depth dimensions). The size of each small area is
|
||||
# fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).
|
||||
#
|
||||
# The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
|
||||
# The input image is typically a square matrix of depth 3.
|
||||
#
|
||||
# A **convolution** is performed on the image which outputs
|
||||
# a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.
|
||||
#
|
||||
# Each filter slides along the input image, taking the dot product
|
||||
# between each small part of the image and the filter, in all depth
|
||||
# dimensions. This is then passed through a non-linear function,
|
||||
# typically the **Rectified Linear (ReLu)** function, which serves as the
|
||||
# activation of the neurons in the first convolutional layer. This is
|
||||
# further passed through a **pooling layer**, which reduces the size of the
|
||||
# convolutional layer, e.g. by taking the maximum or average across some
|
||||
# small regions, and this serves as input to the next convolutional
|
||||
# layer.
|
||||
|
||||
# ### Systematic reduction
|
||||
#
|
||||
# By systematically reducing the size of the input volume, through
|
||||
# convolution and pooling, the network should create representations of
|
||||
# small parts of the input, and then from them assemble representations
|
||||
# of larger areas. The final pooling layer is flattened to serve as
|
||||
# input to a hidden layer, such that each neuron in the final pooling
|
||||
# layer is connected to every single neuron in the hidden layer. This
|
||||
# then serves as input to the output layer, e.g. a softmax output for
|
||||
# classification.
|
||||
|
||||
# ### Prerequisites: Collect and pre-process data
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
# import necessary packages
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn import datasets
|
||||
|
||||
|
||||
# ensure the same random numbers appear every time
|
||||
np.random.seed(0)
|
||||
|
||||
# display images in notebook
|
||||
get_ipython().run_line_magic('matplotlib', 'inline')
|
||||
plt.rcParams['figure.figsize'] = (12,12)
|
||||
|
||||
|
||||
# download MNIST dataset
|
||||
digits = datasets.load_digits()
|
||||
|
||||
# define inputs and labels
|
||||
inputs = digits.images
|
||||
labels = digits.target
|
||||
|
||||
# RGB images have a depth of 3
|
||||
# our images are grayscale so they should have a depth of 1
|
||||
inputs = inputs[:,:,:,np.newaxis]
|
||||
|
||||
print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
|
||||
print("labels = (n_inputs) = " + str(labels.shape))
|
||||
|
||||
|
||||
# choose some random images to display
|
||||
n_inputs = len(inputs)
|
||||
indices = np.arange(n_inputs)
|
||||
random_indices = np.random.choice(indices, size=5)
|
||||
|
||||
for i, image in enumerate(digits.images[random_indices]):
|
||||
plt.subplot(1, 5, i+1)
|
||||
plt.axis('off')
|
||||
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
|
||||
plt.title("Label: %d" % digits.target[random_indices[i]])
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
from tensorflow.keras import datasets, layers, models
|
||||
from tensorflow.keras.layers import Input
|
||||
from tensorflow.keras.models import Sequential #This allows appending layers to existing models
|
||||
from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer
|
||||
from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)
|
||||
from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)
|
||||
from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function
|
||||
#from tensorflow.keras import Conv2D
|
||||
#from tensorflow.keras import MaxPooling2D
|
||||
#from tensorflow.keras import Flatten
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
# representation of labels
|
||||
labels = to_categorical(labels)
|
||||
|
||||
# split into train and test data
|
||||
# one-liner from scikit-learn library
|
||||
train_size = 0.8
|
||||
test_size = 1 - train_size
|
||||
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
|
||||
test_size=test_size)
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
def create_convolutional_neural_network_keras(input_shape, receptive_field,
|
||||
n_filters, n_neurons_connected, n_categories,
|
||||
eta, lmbd):
|
||||
model = Sequential()
|
||||
model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
|
||||
activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
|
||||
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
|
||||
model.add(layers.Flatten())
|
||||
model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
|
||||
model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
|
||||
|
||||
sgd = optimizers.SGD(lr=eta)
|
||||
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
|
||||
|
||||
return model
|
||||
|
||||
epochs = 100
|
||||
batch_size = 100
|
||||
input_shape = X_train.shape[1:4]
|
||||
receptive_field = 3
|
||||
n_filters = 10
|
||||
n_neurons_connected = 50
|
||||
n_categories = 10
|
||||
|
||||
eta_vals = np.logspace(-5, 1, 7)
|
||||
lmbd_vals = np.logspace(-5, 1, 7)
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
|
||||
|
||||
for i, eta in enumerate(eta_vals):
|
||||
for j, lmbd in enumerate(lmbd_vals):
|
||||
CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
|
||||
n_filters, n_neurons_connected, n_categories,
|
||||
eta, lmbd)
|
||||
CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
|
||||
scores = CNN.evaluate(X_test, Y_test)
|
||||
|
||||
CNN_keras[i][j] = CNN
|
||||
|
||||
print("Learning rate = ", eta)
|
||||
print("Lambda = ", lmbd)
|
||||
print("Test accuracy: %.3f" % scores[1])
|
||||
print()
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
# visual representation of grid search
|
||||
# uses seaborn heatmap, could probably do this in matplotlib
|
||||
import seaborn as sns
|
||||
|
||||
sns.set()
|
||||
|
||||
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
|
||||
for i in range(len(eta_vals)):
|
||||
for j in range(len(lmbd_vals)):
|
||||
CNN = CNN_keras[i][j]
|
||||
|
||||
train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
|
||||
test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
|
||||
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Training Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Test Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
|
||||
|
||||
# ## The CIFAR01 data set
|
||||
#
|
||||
# The CIFAR10 dataset contains 60,000 color images in 10 classes, with
|
||||
# 6,000 images in each class. The dataset is divided into 50,000
|
||||
# training images and 10,000 testing images. The classes are mutually
|
||||
# exclusive and there is no overlap between them.
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
from tensorflow.keras import datasets, layers, models
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# We import the data set
|
||||
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
|
||||
|
||||
# Normalize pixel values to be between 0 and 1 by dividing by 255.
|
||||
train_images, test_images = train_images / 255.0, test_images / 255.0
|
||||
|
||||
|
||||
# To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
|
||||
'dog', 'frog', 'horse', 'ship', 'truck']
|
||||
|
||||
plt.figure(figsize=(10,10))
|
||||
for i in range(25):
|
||||
plt.subplot(5,5,i+1)
|
||||
plt.xticks([])
|
||||
plt.yticks([])
|
||||
plt.grid(False)
|
||||
plt.imshow(train_images[i], cmap=plt.cm.binary)
|
||||
# The CIFAR labels happen to be arrays,
|
||||
# which is why you need the extra index
|
||||
plt.xlabel(class_names[train_labels[i][0]])
|
||||
plt.show()
|
||||
|
||||
|
||||
# The six lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.
|
||||
#
|
||||
# As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
model = models.Sequential()
|
||||
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
|
||||
model.add(layers.MaxPooling2D((2, 2)))
|
||||
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
|
||||
model.add(layers.MaxPooling2D((2, 2)))
|
||||
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
|
||||
|
||||
# Let's display the architecture of our model so far.
|
||||
|
||||
model.summary()
|
||||
|
||||
|
||||
# You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.
|
||||
#
|
||||
# To complete our model, you will feed the last output tensor from the
|
||||
# convolutional base (of shape (4, 4, 64)) into one or more Dense layers
|
||||
# to perform classification. Dense layers take vectors as input (which
|
||||
# are 1D), while the current output is a 3D tensor. First, you will
|
||||
# flatten (or unroll) the 3D output to 1D, then add one or more Dense
|
||||
# layers on top. CIFAR has 10 output classes, so you use a final Dense
|
||||
# layer with 10 outputs and a softmax activation.
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
model.add(layers.Flatten())
|
||||
model.add(layers.Dense(64, activation='relu'))
|
||||
model.add(layers.Dense(10))
|
||||
Here's the complete architecture of our model.
|
||||
|
||||
model.summary()
|
||||
|
||||
|
||||
# As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
model.compile(optimizer='adam',
|
||||
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
|
||||
metrics=['accuracy'])
|
||||
|
||||
history = model.fit(train_images, train_labels, epochs=10,
|
||||
validation_data=(test_images, test_labels))
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
plt.plot(history.history['accuracy'], label='accuracy')
|
||||
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
|
||||
plt.xlabel('Epoch')
|
||||
plt.ylabel('Accuracy')
|
||||
plt.ylim([0.5, 1])
|
||||
plt.legend(loc='lower right')
|
||||
|
||||
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
|
||||
|
||||
print(test_acc)
|
||||
|
||||
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
@@ -1,6 +1,9 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
|
||||
# doconce format html chapteroptimization.do.txt -->
|
||||
|
||||
# # Optimization, the central part of any Machine Learning algortithm
|
||||
#
|
||||
# Almost every problem in machine learning and data science starts with
|
||||
@@ -12,9 +15,6 @@
|
||||
# analytically, however this is not possible in general and we must use
|
||||
# some approximative/numerical method to compute the minimum.
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
# In our discussion on Logistic Regression we studied the
|
||||
# case of
|
||||
# two classes, with $y_i$ either
|
||||
@@ -31,8 +31,6 @@
|
||||
|
||||
# where $\boldsymbol{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# Our compact equations used a definition of a vector $\boldsymbol{y}$ with $n$
|
||||
# elements $y_i$, an $n\times p$ matrix $\boldsymbol{X}$ which contains the
|
||||
# $x_i$ values and a vector $\boldsymbol{p}$ of fitted probabilities
|
||||
@@ -52,8 +50,6 @@
|
||||
|
||||
# This defines what is called the Hessian matrix.
|
||||
#
|
||||
#
|
||||
#
|
||||
# If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives.
|
||||
#
|
||||
# Our iterative scheme is then given by
|
||||
@@ -72,7 +68,6 @@
|
||||
#
|
||||
# If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement.
|
||||
#
|
||||
#
|
||||
# Let us quickly remind ourselves how we derive the above method.
|
||||
#
|
||||
# Perhaps the most celebrated of all one-dimensional root-finding
|
||||
@@ -83,8 +78,6 @@
|
||||
# numerically and/or your function is not of the smooth type, we
|
||||
# normally discourage the use of this method.
|
||||
#
|
||||
#
|
||||
#
|
||||
# The Newton-Raphson formula consists geometrically of extending the
|
||||
# tangent line at a current point until it crosses zero, then setting
|
||||
# the next guess to the abscissa of that zero-crossing. The mathematics
|
||||
@@ -130,9 +123,6 @@
|
||||
# guess near such a local extremum, so that the first derivative nearly
|
||||
# vanishes, then Newton-Raphson may fail totally
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
# Newton's method can be generalized to systems of several non-linear equations
|
||||
# and variables. Consider the case with two equations
|
||||
|
||||
@@ -183,11 +173,8 @@
|
||||
# arise in case $\boldsymbol{J}$ is nearly singular.
|
||||
#
|
||||
# It is rather straightforward to extend the above scheme to systems of
|
||||
# more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function.
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
# more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function.
|
||||
|
||||
# ## Steepest descent
|
||||
#
|
||||
# The basic idea of gradient descent is
|
||||
@@ -207,7 +194,6 @@
|
||||
# F(\mathbf{x}_k)$. This means that for a sufficiently small $\gamma_k$
|
||||
# we are always moving towards smaller function values, i.e a minimum.
|
||||
#
|
||||
#
|
||||
# The previous observation is the basis of the method of steepest
|
||||
# descent, which is also referred to as just gradient descent (GD). One
|
||||
# starts with an initial guess $\mathbf{x}_0$ for a minimum of $F$ and
|
||||
@@ -220,7 +206,6 @@
|
||||
# The parameter $\gamma_k$ is often referred to as the step length or
|
||||
# the learning rate within the context of Machine Learning.
|
||||
#
|
||||
#
|
||||
# Ideally the sequence $\{\mathbf{x}_k \}_{k=0}$ converges to a global
|
||||
# minimum of the function $F$. In general we do not know if we are in a
|
||||
# global or local minimum. In the special case when $F$ is a convex
|
||||
@@ -239,9 +224,6 @@
|
||||
# Note that the gradient is a function of $\mathbf{x} =
|
||||
# (x_1,\cdots,x_n)$ which makes it expensive to compute numerically.
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
# The gradient descent method
|
||||
# is sensitive to the choice of learning rate $\gamma_k$. This is due
|
||||
# to the fact that we are only guaranteed that $F(\mathbf{x}_{k+1}) \leq
|
||||
@@ -253,9 +235,7 @@
|
||||
# Many of these shortcomings can be alleviated by introducing
|
||||
# randomness. One such method is that of Stochastic Gradient Descent
|
||||
# (SGD), see below.
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
# ## Convex functions
|
||||
#
|
||||
# Ideally we want our cost/loss function to be convex(concave).
|
||||
@@ -270,11 +250,8 @@
|
||||
# $\mathbb{R}$. Examples of convex sets of $\mathbb{R}^2$ are the
|
||||
# regular polygons (triangles, rectangles, pentagons, etc...).
|
||||
#
|
||||
#
|
||||
#
|
||||
# **Convex function**: Let $X \subset \mathbb{R}^n$ be a convex set. Assume that the function $f: X \rightarrow \mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \in X$ and for all $t \in [0,1]$. If $\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \neq x_2$ and $t\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below.
|
||||
#
|
||||
#
|
||||
# In the following we state first and second-order conditions which
|
||||
# ensures convexity of a function $f$. We write $D_f$ to denote the
|
||||
# domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more
|
||||
@@ -291,8 +268,6 @@
|
||||
# make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and
|
||||
# note that it is always below the graph.
|
||||
#
|
||||
#
|
||||
#
|
||||
# **Second order condition.**
|
||||
#
|
||||
# Assume that $f$ is twice
|
||||
@@ -302,12 +277,8 @@
|
||||
# single-variable function this reduces to $f''(x) \geq 0$. Geometrically this means that $f$ has nonnegative curvature
|
||||
# everywhere.
|
||||
#
|
||||
#
|
||||
#
|
||||
# This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition.
|
||||
#
|
||||
#
|
||||
#
|
||||
# The next result is of great importance to us and the reason why we are
|
||||
# going on about convex functions. In machine learning we frequently
|
||||
# have to minimize a loss/cost function in order to find the best
|
||||
@@ -324,11 +295,8 @@
|
||||
# is minimal, where $f$ is convex and differentiable. Then, any point
|
||||
# $x^*$ that satisfies $\nabla f(x^*) = 0$ is a global minimum.
|
||||
#
|
||||
#
|
||||
#
|
||||
# This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum.
|
||||
#
|
||||
#
|
||||
|
||||
# ### Some simple problems
|
||||
#
|
||||
# 1. Show that $f(x)=x^2$ is convex for $x \in \mathbb{R}$ using the definition of convexity. Hint: If you re-write the definition, $f$ is convex if the following holds for all $x,y \in D_f$ and any $\lambda \in [0,1]$ $\lambda f(x)+(1-\lambda)f(y)-f(\lambda x + (1-\lambda) y ) \geq 0$.
|
||||
@@ -339,7 +307,6 @@
|
||||
#
|
||||
# * $g(x) = -\ln(x)$ is convex for $x \in (0,\infty)$.
|
||||
#
|
||||
#
|
||||
# 3. Let $f(x) = x^2$ and $g(x) = e^x$. Show that $f(g(x))$ and $g(f(x))$ is convex for $x \in \mathbb{R}$. Also show that if $f(x)$ is any convex function than $h(x) = e^{f(x)}$ is convex.
|
||||
#
|
||||
# 4. A norm is any function that satisfy the following properties
|
||||
@@ -350,13 +317,10 @@
|
||||
#
|
||||
# * $f(x) \leq 0$ for all $x \in \mathbb{R}^n$ with equality if and only if $x = 0$
|
||||
#
|
||||
#
|
||||
# Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this).
|
||||
#
|
||||
#
|
||||
|
||||
# ## Standard steepest descent
|
||||
#
|
||||
#
|
||||
# Before we proceed, we would like to discuss the approach called the
|
||||
# **standard Steepest descent** (different from the above steepest descent discussion), which again leads to us having to be able
|
||||
# to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG).
|
||||
@@ -381,8 +345,6 @@
|
||||
#
|
||||
# When we have found the exact solution, $\boldsymbol{r}=0$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# The residual is zero when we reach the minimum of the quadratic equation
|
||||
|
||||
# $$
|
||||
@@ -392,7 +354,6 @@
|
||||
# with the constraint that the matrix $\boldsymbol{A}$ is positive definite and
|
||||
# symmetric. This defines also the Hessian and we want it to be positive definite.
|
||||
#
|
||||
#
|
||||
# We denote the initial guess for $\boldsymbol{x}$ as $\boldsymbol{x}_0$.
|
||||
# We can assume without loss of generality that
|
||||
|
||||
@@ -408,7 +369,6 @@
|
||||
|
||||
# instead.
|
||||
#
|
||||
#
|
||||
# One can show that the solution $\boldsymbol{x}$ is also the unique minimizer of the quadratic form
|
||||
|
||||
# $$
|
||||
@@ -426,7 +386,6 @@
|
||||
# and
|
||||
# $\boldsymbol{x}_0=0$ it is equal $-\boldsymbol{b}$.
|
||||
#
|
||||
#
|
||||
# We can compute the residual iteratively as
|
||||
|
||||
# $$
|
||||
@@ -728,7 +687,6 @@ y = 4+3*x+np.random.randn(m,1)
|
||||
|
||||
# and we want to find $\beta$ such that $C(\beta)$ is minimized.
|
||||
#
|
||||
#
|
||||
# Computing $\partial C(\beta) / \partial \beta_0$ and $\partial C(\beta) / \partial \beta_1$ we can show that the gradient can be written as
|
||||
|
||||
# $$
|
||||
@@ -739,7 +697,6 @@ y = 4+3*x+np.random.randn(m,1)
|
||||
|
||||
# where $X$ is the design matrix defined above.
|
||||
#
|
||||
#
|
||||
# The Hessian matrix of $C(\beta)$ is given by
|
||||
|
||||
# $$
|
||||
@@ -751,8 +708,6 @@ y = 4+3*x+np.random.randn(m,1)
|
||||
|
||||
# This result implies that $C(\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite.
|
||||
#
|
||||
#
|
||||
#
|
||||
# We can now write a program that minimizes $C(\beta)$ using the gradient descent method with a constant learning rate $\gamma$ according to
|
||||
|
||||
# $$
|
||||
@@ -766,8 +721,6 @@ y = 4+3*x+np.random.randn(m,1)
|
||||
# And finally we can compare our solution for $\beta$ with the analytic result given by
|
||||
# $\beta= (X^TX)^{-1} X^T \mathbf{y}$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# Here is our simple example
|
||||
|
||||
# In[7]:
|
||||
@@ -925,8 +878,30 @@ plt.show()
|
||||
# * **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
|
||||
#
|
||||
# * 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.
|
||||
|
||||
# ## Stochastic Gradient Descent (SGD)
|
||||
#
|
||||
# ## Stochastic Gradient Descent
|
||||
# In stochastic gradient descent, the extreme case is the case where we
|
||||
# have only one batch, that is we include the whole data set.
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
# In our notes with SGD we mean stochastic gradient descent with mini-batches.
|
||||
#
|
||||
# Stochastic gradient descent (SGD) and variants thereof address some of
|
||||
# the shortcomings of the Gradient descent method discussed above.
|
||||
@@ -954,8 +929,6 @@ plt.show()
|
||||
# minibatches. We denote these minibatches by $B_k$ where
|
||||
# $k=1,\cdots,n/M$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# As an example, suppose we have $10$ data points $(\mathbf{x}_1,\cdots, \mathbf{x}_{10})$
|
||||
# and we choose to have $M=5$ minibathces,
|
||||
# then each minibatch contains two data points. In particular we have
|
||||
@@ -995,7 +968,7 @@ plt.show()
|
||||
import numpy as np
|
||||
|
||||
n = 100 #100 datapoints
|
||||
M = 5 #size of each minibatch
|
||||
M = 5 #size of each mini-batche
|
||||
m = int(n/M) #number of minibatches
|
||||
n_epochs = 10 #number of epochs
|
||||
|
||||
@@ -1016,8 +989,6 @@ for epoch in range(1,n_epochs+1):
|
||||
# cheaper since we sum over the datapoints in the $k-th$ minibatch and not
|
||||
# all $n$ datapoints.
|
||||
#
|
||||
#
|
||||
#
|
||||
# A natural question is when do we stop the search for a new minimum?
|
||||
# One possibility is to compute the full gradient after a given number
|
||||
# of epochs and check if the norm of the gradient is smaller than some
|
||||
@@ -1029,8 +1000,6 @@ for epoch in range(1,n_epochs+1):
|
||||
# compare the values of the cost function and keep the $\beta$ that
|
||||
# gave the lowest value.
|
||||
#
|
||||
#
|
||||
#
|
||||
# Another approach is to let the step length $\gamma_j$ depend on the
|
||||
# number of epochs in such a way that it becomes very small after a
|
||||
# reasonable time such that we do not move at all.
|
||||
@@ -1072,39 +1041,41 @@ for epoch in range(1,n_epochs+1):
|
||||
print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
|
||||
|
||||
|
||||
# We note that we have defined several hyperparameters. These are now the number of epochs, the number of mini-batches and the parameters $t_0$ and $t_1$.
|
||||
|
||||
# ### Program for stochastic gradient
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
# Importing various packages
|
||||
# Importing various packages
|
||||
from math import exp, sqrt
|
||||
from random import random, seed
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.linear_model import SGDRegressor
|
||||
|
||||
m = 100
|
||||
x = 2*np.random.rand(m,1)
|
||||
y = 4+3*x+np.random.randn(m,1)
|
||||
n = 100
|
||||
x = 2*np.random.rand(n,1)
|
||||
y = 4+3*x+np.random.randn(n,1)
|
||||
|
||||
X = np.c_[np.ones((m,1)), x]
|
||||
X = np.c_[np.ones((n,1)), x]
|
||||
XT_X = X.T @ X
|
||||
theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)
|
||||
print("Own inversion")
|
||||
print(theta_linreg)
|
||||
sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)
|
||||
sgdreg.fit(x,y.ravel())
|
||||
print("sgdreg from scikit")
|
||||
print(sgdreg.intercept_, sgdreg.coef_)
|
||||
|
||||
# Hessian matrix
|
||||
H = (2.0/n)* XT_X
|
||||
EigValues, EigVectors = np.linalg.eig(H)
|
||||
print(f"Eigenvalues of Hessian Matrix:{EigValues}")
|
||||
|
||||
theta = np.random.randn(2,1)
|
||||
eta = 0.1
|
||||
eta = 1.0/np.max(EigValues)
|
||||
Niterations = 1000
|
||||
|
||||
|
||||
for iter in range(Niterations):
|
||||
gradients = 2.0/m*X.T @ ((X @ theta)-y)
|
||||
gradients = 2.0/n*X.T @ ((X @ theta)-y)
|
||||
theta -= eta*gradients
|
||||
print("theta from own gd")
|
||||
print(theta)
|
||||
@@ -1114,8 +1085,9 @@ Xnew = np.c_[np.ones((2,1)), xnew]
|
||||
ypredict = Xnew.dot(theta)
|
||||
ypredict2 = Xnew.dot(theta_linreg)
|
||||
|
||||
|
||||
n_epochs = 50
|
||||
M = 5 #size of each minibatch
|
||||
m = int(n/M) #number of minibatches
|
||||
t0, t1 = 5, 50
|
||||
def learning_schedule(t):
|
||||
return t0/(t+t1)
|
||||
@@ -1123,16 +1095,20 @@ def learning_schedule(t):
|
||||
theta = np.random.randn(2,1)
|
||||
|
||||
for epoch in range(n_epochs):
|
||||
# Can you figure out a better way of setting up the contributions to each batch?
|
||||
for i in range(m):
|
||||
random_index = np.random.randint(m)
|
||||
xi = X[random_index:random_index+1]
|
||||
yi = y[random_index:random_index+1]
|
||||
gradients = 2 * xi.T @ ((xi @ theta)-yi)
|
||||
random_index = M*np.random.randint(m)
|
||||
xi = X[random_index:random_index+M]
|
||||
yi = y[random_index:random_index+M]
|
||||
gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)
|
||||
eta = learning_schedule(epoch*m+i)
|
||||
theta = theta - eta*gradients
|
||||
print("theta from own sdg")
|
||||
print(theta)
|
||||
|
||||
|
||||
|
||||
|
||||
plt.plot(xnew, ypredict, "r-")
|
||||
plt.plot(xnew, ypredict2, "b-")
|
||||
plt.plot(x, y ,'ro')
|
||||
@@ -1143,6 +1119,11 @@ plt.title(r'Random numbers ')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In the above code, we have use replacement in setting up the
|
||||
# mini-batches. The discussion
|
||||
# [here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be
|
||||
# useful. More material will be added later.
|
||||
|
||||
# ## Momentum based GD
|
||||
#
|
||||
# The stochastic gradient descent (SGD) is almost always used with a
|
||||
@@ -1181,8 +1162,6 @@ plt.show()
|
||||
|
||||
# where we have defined $\Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1}$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# Let us try to get more intuition from these equations. It is helpful
|
||||
# to consider a simple physical analogy with a particle of mass $m$
|
||||
# moving in a viscous medium with drag coefficient $\mu$ and potential
|
||||
@@ -1256,8 +1235,6 @@ plt.show()
|
||||
|
||||
# One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\gamma$.
|
||||
#
|
||||
#
|
||||
#
|
||||
# In stochastic gradient descent, with and without momentum, we still
|
||||
# have to specify a schedule for tuning the learning rates $\eta_t$
|
||||
# as a function of time. As discussed in the context of Newton's
|
||||
@@ -1276,10 +1253,9 @@ plt.show()
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
#
|
||||
|
||||
# ### RMS prop
|
||||
#
|
||||
# In RMS prop, in addition to keeping a running average of the first
|
||||
@@ -1314,7 +1290,7 @@ plt.show()
|
||||
# directions where the norm of the gradient is consistently large. This
|
||||
# greatly speeds up the convergence by allowing us to use a larger
|
||||
# learning rate for flat directions.
|
||||
#
|
||||
|
||||
# ### ADAM optimizer
|
||||
#
|
||||
# A related algorithm is the ADAM optimizer. In ADAM, we keep a running
|
||||
@@ -1393,7 +1369,7 @@ plt.show()
|
||||
# * **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.
|
||||
#
|
||||
# * **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
|
||||
#
|
||||
|
||||
# ## Automatic differentiation
|
||||
#
|
||||
# [Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation),
|
||||
@@ -1421,8 +1397,6 @@ plt.show()
|
||||
# while numerical differentiation can introduce round-off errors in the
|
||||
# discretization process and cancellation
|
||||
#
|
||||
#
|
||||
#
|
||||
# Python has tools for so-called **automatic differentiation**.
|
||||
# Consider the following example
|
||||
|
||||
@@ -1619,35 +1593,38 @@ x = 2.7
|
||||
print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
|
||||
|
||||
|
||||
# 1
|
||||
# 8
|
||||
#
|
||||
# <
|
||||
# <
|
||||
# <
|
||||
# !
|
||||
# !
|
||||
# C
|
||||
# O
|
||||
# D
|
||||
# E
|
||||
# _
|
||||
# B
|
||||
# L
|
||||
# O
|
||||
# C
|
||||
# K
|
||||
#
|
||||
#
|
||||
# p
|
||||
# y
|
||||
# c
|
||||
# o
|
||||
# d
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
from autograd import grad
|
||||
def f6_for(x):
|
||||
val = 0
|
||||
for i in range(10):
|
||||
val = val + x**i
|
||||
return val
|
||||
|
||||
def f6_while(x):
|
||||
val = 0
|
||||
i = 0
|
||||
while i < 10:
|
||||
val = val + x**i
|
||||
i = i + 1
|
||||
return val
|
||||
|
||||
f6_for_grad = grad(f6_for)
|
||||
f6_while_grad = grad(f6_while)
|
||||
|
||||
x = 0.5
|
||||
|
||||
# Print the computed derivaties of f6_for and f6_while
|
||||
print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
|
||||
print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
from autograd import grad
|
||||
# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
|
||||
@@ -1659,7 +1636,7 @@ for i in range(10):
|
||||
print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
|
||||
|
||||
|
||||
# In[20]:
|
||||
# In[21]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
@@ -1693,30 +1670,29 @@ print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
|
||||
|
||||
# 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.
|
||||
#
|
||||
# Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.
|
||||
#
|
||||
# Autograd supports many features. However, there are some functions that are not supported (yet) by Autograd.
|
||||
#
|
||||
# Assigning a value to the variable being differentiated with respect to is an example thereof.
|
||||
# Assigning a value to the variable being differentiated with respect to
|
||||
|
||||
# In[21]:
|
||||
# In[22]:
|
||||
|
||||
|
||||
#import autograd.numpy as np
|
||||
#from autograd import grad
|
||||
#def f8(x): # Assume x is an array
|
||||
# x[2] = 3
|
||||
# return x*2
|
||||
import autograd.numpy as np
|
||||
from autograd import grad
|
||||
def f8(x): # Assume x is an array
|
||||
x[2] = 3
|
||||
return x*2
|
||||
|
||||
#f8_grad = grad(f8)
|
||||
f8_grad = grad(f8)
|
||||
|
||||
#x = 8.4
|
||||
x = 8.4
|
||||
|
||||
#print("The derivative of f8 is:",f8_grad(x))
|
||||
print("The derivative of f8 is:",f8_grad(x))
|
||||
|
||||
|
||||
# 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.
|
||||
|
||||
# In[22]:
|
||||
# In[23]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
@@ -1736,7 +1712,7 @@ print("The derivative of f9 is:",f9_grad(x))
|
||||
# version of a Numpy array. To overcome this, an alternative syntax
|
||||
# which also computed the dot product can be used:
|
||||
|
||||
# In[ ]:
|
||||
# In[24]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
@@ -1757,7 +1733,7 @@ print("The gradient of f9 is:",f9_alternative_grad(x))
|
||||
|
||||
# The documentation recommends to avoid inplace operations such as
|
||||
|
||||
# In[ ]:
|
||||
# In[25]:
|
||||
|
||||
|
||||
a += b
|
||||
@@ -1766,4 +1742,184 @@ a*= b
|
||||
a /=b
|
||||
|
||||
|
||||
# More examples will be added, in particular how to compare autograd with own codes for the gradients.
|
||||
# ## Using Autograd with OLS
|
||||
#
|
||||
# We conclude the part on optmization by showing how we can make codes
|
||||
# for linear regression and logistic regression using **autograd**. The
|
||||
# first example shows results with ordinary leats squares.
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
# Using Autograd to calculate gradients for OLS
|
||||
from random import random, seed
|
||||
import numpy as np
|
||||
import autograd.numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from autograd import grad
|
||||
|
||||
def CostOLS(beta):
|
||||
return (1.0/n)*np.sum((y-X @ beta)**2)
|
||||
|
||||
n = 100
|
||||
x = 2*np.random.rand(n,1)
|
||||
y = 4+3*x+np.random.randn(n,1)
|
||||
|
||||
X = np.c_[np.ones((n,1)), x]
|
||||
XT_X = X.T @ X
|
||||
theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
|
||||
print("Own inversion")
|
||||
print(theta_linreg)
|
||||
# Hessian matrix
|
||||
H = (2.0/n)* XT_X
|
||||
EigValues, EigVectors = np.linalg.eig(H)
|
||||
print(f"Eigenvalues of Hessian Matrix:{EigValues}")
|
||||
|
||||
theta = np.random.randn(2,1)
|
||||
eta = 1.0/np.max(EigValues)
|
||||
Niterations = 1000
|
||||
# define the gradient
|
||||
training_gradient = grad(CostOLS)
|
||||
|
||||
for iter in range(Niterations):
|
||||
gradients = training_gradient(theta)
|
||||
theta -= eta*gradients
|
||||
print("theta from own gd")
|
||||
print(theta)
|
||||
|
||||
xnew = np.array([[0],[2]])
|
||||
Xnew = np.c_[np.ones((2,1)), xnew]
|
||||
ypredict = Xnew.dot(theta)
|
||||
ypredict2 = Xnew.dot(theta_linreg)
|
||||
|
||||
plt.plot(xnew, ypredict, "r-")
|
||||
plt.plot(xnew, ypredict2, "b-")
|
||||
plt.plot(x, y ,'ro')
|
||||
plt.axis([0,2.0,0, 15.0])
|
||||
plt.xlabel(r'$x$')
|
||||
plt.ylabel(r'$y$')
|
||||
plt.title(r'Random numbers ')
|
||||
plt.show()
|
||||
|
||||
|
||||
# ### Including Stochastic Gradient Descent with Autograd
|
||||
#
|
||||
# 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 **autograd**.
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
# Using Autograd to calculate gradients using SGD
|
||||
# OLS example
|
||||
from random import random, seed
|
||||
import numpy as np
|
||||
import autograd.numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from autograd import grad
|
||||
|
||||
# Note change from previous example
|
||||
def CostOLS(y,X,theta):
|
||||
return np.sum((y-X @ theta)**2)
|
||||
|
||||
n = 100
|
||||
x = 2*np.random.rand(n,1)
|
||||
y = 4+3*x+np.random.randn(n,1)
|
||||
|
||||
X = np.c_[np.ones((n,1)), x]
|
||||
XT_X = X.T @ X
|
||||
theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)
|
||||
print("Own inversion")
|
||||
print(theta_linreg)
|
||||
# Hessian matrix
|
||||
H = (2.0/n)* XT_X
|
||||
EigValues, EigVectors = np.linalg.eig(H)
|
||||
print(f"Eigenvalues of Hessian Matrix:{EigValues}")
|
||||
|
||||
theta = np.random.randn(2,1)
|
||||
eta = 1.0/np.max(EigValues)
|
||||
Niterations = 1000
|
||||
|
||||
# Note that we request the derivative wrt third argument (theta, 2 here)
|
||||
training_gradient = grad(CostOLS,2)
|
||||
|
||||
for iter in range(Niterations):
|
||||
gradients = (1.0/n)*training_gradient(y, X, theta)
|
||||
theta -= eta*gradients
|
||||
print("theta from own gd")
|
||||
print(theta)
|
||||
|
||||
xnew = np.array([[0],[2]])
|
||||
Xnew = np.c_[np.ones((2,1)), xnew]
|
||||
ypredict = Xnew.dot(theta)
|
||||
ypredict2 = Xnew.dot(theta_linreg)
|
||||
|
||||
plt.plot(xnew, ypredict, "r-")
|
||||
plt.plot(xnew, ypredict2, "b-")
|
||||
plt.plot(x, y ,'ro')
|
||||
plt.axis([0,2.0,0, 15.0])
|
||||
plt.xlabel(r'$x$')
|
||||
plt.ylabel(r'$y$')
|
||||
plt.title(r'Random numbers ')
|
||||
plt.show()
|
||||
|
||||
n_epochs = 50
|
||||
M = 5 #size of each minibatch
|
||||
m = int(n/M) #number of minibatches
|
||||
t0, t1 = 5, 50
|
||||
def learning_schedule(t):
|
||||
return t0/(t+t1)
|
||||
|
||||
theta = np.random.randn(2,1)
|
||||
|
||||
for epoch in range(n_epochs):
|
||||
# Can you figure out a better way of setting up the contributions to each batch?
|
||||
for i in range(m):
|
||||
random_index = M*np.random.randint(m)
|
||||
xi = X[random_index:random_index+M]
|
||||
yi = y[random_index:random_index+M]
|
||||
gradients = (1.0/M)*training_gradient(yi, xi, theta)
|
||||
eta = learning_schedule(epoch*m+i)
|
||||
theta = theta - eta*gradients
|
||||
print("theta from own sdg")
|
||||
print(theta)
|
||||
|
||||
|
||||
# ### And Logistic Regression
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
import autograd.numpy as np
|
||||
from autograd import grad
|
||||
|
||||
def sigmoid(x):
|
||||
return 0.5 * (np.tanh(x / 2.) + 1)
|
||||
|
||||
def logistic_predictions(weights, inputs):
|
||||
# Outputs probability of a label being true according to logistic model.
|
||||
return sigmoid(np.dot(inputs, weights))
|
||||
|
||||
def training_loss(weights):
|
||||
# Training loss is the negative log-likelihood of the training labels.
|
||||
preds = logistic_predictions(weights, inputs)
|
||||
label_probabilities = preds * targets + (1 - preds) * (1 - targets)
|
||||
return -np.sum(np.log(label_probabilities))
|
||||
|
||||
# Build a toy dataset.
|
||||
inputs = np.array([[0.52, 1.12, 0.77],
|
||||
[0.88, -1.08, 0.15],
|
||||
[0.52, 0.06, -1.30],
|
||||
[0.74, -2.49, 1.39]])
|
||||
targets = np.array([True, True, False, True])
|
||||
|
||||
# Define a function that returns gradients of training loss using Autograd.
|
||||
training_gradient_fun = grad(training_loss)
|
||||
|
||||
# Optimize weights using gradient descent.
|
||||
weights = np.array([0.0, 0.0, 0.0])
|
||||
print("Initial loss:", training_loss(weights))
|
||||
for i in range(100):
|
||||
weights -= training_gradient_fun(weights) * 0.01
|
||||
|
||||
print("Trained loss:", training_loss(weights))
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 99 KiB |
@@ -0,0 +1,443 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
# <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
|
||||
# doconce format html clustering.do.txt -->
|
||||
|
||||
# # Clustering and Unsupervised Learning
|
||||
#
|
||||
# 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 **metric** or **similarity
|
||||
# measure** in the literature (note: sometimes we deal with a **dissimilarity
|
||||
# measure** instead). Usually, these metrics are formulated as some kind of
|
||||
# distance function between points in a high-dimensional space.
|
||||
#
|
||||
# The simplest, and also the most
|
||||
# common is the **Euclidean distance**.
|
||||
#
|
||||
# The simplest of all clustering algorithms is the **k-means algorithm**
|
||||
# , sometimes also referred to as *Lloyds algorithm*. 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 $k$-means algorithm is a
|
||||
# **centroid based** clustering algorithm.
|
||||
#
|
||||
# Assume, we are given $n$ data points and we wish to split the data into $K < n$
|
||||
# different categories, or clusters. We label each cluster by an integer
|
||||
|
||||
# $$
|
||||
# k\in\{1, \cdots, K \}.
|
||||
# $$
|
||||
|
||||
# In the basic k-means algorithm each point is assigned to only
|
||||
# one cluster $k$, and these assignments are *non-injective* i.e. many-to-one. We
|
||||
# can think of these mappings as an encoder $k = C(i)$, which assigns the $i$-th
|
||||
# data-point $\bf x_i$ to the $k$-th cluster.
|
||||
#
|
||||
# $k$-means algorithm in words:
|
||||
# 1. We start with guesses / random initializations of our $k$ cluster centers/centroids
|
||||
#
|
||||
# 2. For each centroid the points that are most similar are identified
|
||||
#
|
||||
# 3. Then we move / replace each centroid with a coordinate average of all the points that were assigned to that centroid.
|
||||
#
|
||||
# 4. Iterate 2-3 until the centroids no longer move (to some tolerance)
|
||||
#
|
||||
# We assume we have $n$ data-points
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="eq:kmeanspoints"></div>
|
||||
#
|
||||
# $$
|
||||
# \begin{equation}\label{eq:kmeanspoints} \tag{1}
|
||||
# \boldsymbol{x_i} = \{x_{i, 1}, \cdots, x_{i, p}\}\in\mathbb{R}^p.
|
||||
# \end{equation}
|
||||
# $$
|
||||
|
||||
# which we wish to group into $K < n$ clusters. For our dissimilarity measure we
|
||||
# use the *squared Euclidean distance*
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="eq:squaredeuclidean"></div>
|
||||
#
|
||||
# $$
|
||||
# \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}
|
||||
# $$
|
||||
|
||||
# We define the so called *within-cluster point scatter* which gives us a
|
||||
# measure of how close each data point assigned to the same cluster tends to be to
|
||||
# the all the others.
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="eq:withincluster"></div>
|
||||
#
|
||||
# $$
|
||||
# \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}
|
||||
# $$
|
||||
|
||||
# where $\boldsymbol{\overline{x_k}}$ is the mean vector associated with the $k$-th
|
||||
# cluster, and $N_k = \sum_{i=1}^nI(C(i) = k)$, where the $I()$ notation is
|
||||
# similar to the Kronecker delta (*Commonly used in statistics, it just means that
|
||||
# when $i = k$ we have the encoder $C(i)$*). 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 $k$-means algorithm aims
|
||||
# to minimize. We refer to this quantity $W(C)$ as the within cluster scatter
|
||||
# because of its relation to the *total scatter*.
|
||||
#
|
||||
# We have
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="eq:totalscatter"></div>
|
||||
#
|
||||
# $$
|
||||
# \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}
|
||||
# $$
|
||||
|
||||
# This is a quantity that is conserved throughout the $k$-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 *between-cluster scatter*
|
||||
# $B(C)$. In methods such as principle component analysis the total scatter is not
|
||||
# conserved.
|
||||
#
|
||||
# Given a cluster mean $\boldsymbol{m_k}$ we define the **total cluster variance**
|
||||
|
||||
# <!-- Equation labels as ordinary links -->
|
||||
# <div id="eq:totalclustervariance"></div>
|
||||
#
|
||||
# $$
|
||||
# \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}
|
||||
# $$
|
||||
|
||||
# Now we have all the pieces necessary to formally revisit the $k$-means algorithm.
|
||||
#
|
||||
# The $k$-means clustering algorithm goes as follows
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
# 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$$
|
||||
#
|
||||
# 3. Steps 1 and 2 are repeated until the assignments do not change.
|
||||
|
||||
# ## Codes and Approaches
|
||||
#
|
||||
# 1. Before we start we specify a number $k$ which is the number of clusters we want to try to separate our data into.
|
||||
#
|
||||
# 2. We initially choose $k$ random data points in our data as our initial centroids, *or means* (this is where the name comes from).
|
||||
#
|
||||
# 3. Assign each data point to their closest centroid, based on the squared Euclidean distance.
|
||||
#
|
||||
# 4. For each of the $k$ cluster we update the centroid by calculating new mean values for all the data points in the cluster.
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
# We need first a dataset to do our cluster analysis on. In our case
|
||||
# this is a plain *vanilla* data set using random numbers using a
|
||||
# Gaussian distribution.
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
get_ipython().run_line_magic('matplotlib', 'inline')
|
||||
|
||||
import time
|
||||
import numpy as np
|
||||
import tensorflow as tf
|
||||
from matplotlib import image
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.cluster import KMeans
|
||||
from IPython.display import display
|
||||
|
||||
np.random.seed(2021)
|
||||
|
||||
|
||||
# Next we define functions, for ease of use later, to generate Gaussians and to
|
||||
# set up our toy data set.
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
def gaussian_points(dim=2, n_points=1000, mean_vector=np.array([0, 0]),
|
||||
sample_variance=1):
|
||||
"""
|
||||
Very simple custom function to generate gaussian distributed point clusters
|
||||
with variable dimension, number of points, means in each direction
|
||||
(must match dim) and sample variance.
|
||||
|
||||
Inputs:
|
||||
dim (int)
|
||||
n_points (int)
|
||||
mean_vector (np.array) (where index 0 is x, index 1 is y etc.)
|
||||
sample_variance (float)
|
||||
|
||||
Returns:
|
||||
data (np.array): with dimensions (dim x n_points)
|
||||
"""
|
||||
|
||||
mean_matrix = np.zeros(dim) + mean_vector
|
||||
covariance_matrix = np.eye(dim) * sample_variance
|
||||
data = np.random.multivariate_normal(mean_matrix, covariance_matrix,
|
||||
n_points)
|
||||
return data
|
||||
|
||||
|
||||
|
||||
def generate_simple_clustering_dataset(dim=2, n_points=1000, plotting=True,
|
||||
return_data=True):
|
||||
"""
|
||||
Toy model to illustrate k-means clustering
|
||||
"""
|
||||
|
||||
data1 = gaussian_points(mean_vector=np.array([5, 5]))
|
||||
data2 = gaussian_points()
|
||||
data3 = gaussian_points(mean_vector=np.array([1, 4.5]))
|
||||
data4 = gaussian_points(mean_vector=np.array([5, 1]))
|
||||
data = np.concatenate((data1, data2, data3, data4), axis=0)
|
||||
|
||||
if plotting:
|
||||
fig, ax = plt.subplots()
|
||||
ax.scatter(data[:, 0], data[:, 1], alpha=0.2)
|
||||
ax.set_title('Toy Model Dataset')
|
||||
plt.show()
|
||||
|
||||
|
||||
if return_data:
|
||||
return data
|
||||
|
||||
|
||||
data = generate_simple_clustering_dataset()
|
||||
|
||||
|
||||
# With the above dataset we start
|
||||
# implementing the $k$-means algorithm.
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
|
||||
n_samples, dimensions = data.shape
|
||||
n_clusters = 4
|
||||
|
||||
# we randomly initialize our centroids
|
||||
np.random.seed(2021)
|
||||
centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]
|
||||
distances = np.zeros((n_samples, n_clusters))
|
||||
|
||||
# first we need to calculate the distance to each centroid from our data
|
||||
for k in range(n_clusters):
|
||||
for n in range(n_samples):
|
||||
dist = 0
|
||||
for d in range(dimensions):
|
||||
dist += np.abs(data[n, d] - centroids[k, d])**2
|
||||
distances[n, k] = dist
|
||||
|
||||
# we initialize an array to keep track of to which cluster each point belongs
|
||||
# the way we set it up here the index tracks which point and the value which
|
||||
# cluster the point belongs to
|
||||
cluster_labels = np.zeros(n_samples, dtype='int')
|
||||
|
||||
# next we loop through our samples and for every point assign it to the cluster
|
||||
# to which it has the smallest distance to
|
||||
for n in range(n_samples):
|
||||
# tracking variables (all of this is basically just an argmin)
|
||||
smallest = 1e10
|
||||
smallest_row_index = 1e10
|
||||
for k in range(n_clusters):
|
||||
if distances[n, k] < smallest:
|
||||
smallest = distances[n, k]
|
||||
smallest_row_index = k
|
||||
|
||||
cluster_labels[n] = smallest_row_index
|
||||
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot()
|
||||
unique_cluster_labels = np.unique(cluster_labels)
|
||||
for i in unique_cluster_labels:
|
||||
ax.scatter(data[cluster_labels == i, 0],
|
||||
data[cluster_labels == i, 1],
|
||||
label = i,
|
||||
alpha = 0.2)
|
||||
ax.scatter(centroids[:, 0], centroids[:, 1], c='black')
|
||||
|
||||
ax.set_title("First Grouping of Points to Centroids")
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
# So what do we have so far? We have 'picked' $k$ 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,
|
||||
# *or dissimilarity*, 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.
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
|
||||
max_iterations = 100
|
||||
tolerance = 1e-8
|
||||
|
||||
for iteration in range(max_iterations):
|
||||
prev_centroids = centroids.copy()
|
||||
for k in range(n_clusters):
|
||||
# this array will be used to update our centroid positions
|
||||
vector_mean = np.zeros(dimensions)
|
||||
mean_divisor = 0
|
||||
for n in range(n_samples):
|
||||
if cluster_labels[n] == k:
|
||||
vector_mean += data[n, :]
|
||||
mean_divisor += 1
|
||||
|
||||
# update according to the k means
|
||||
centroids[k, :] = vector_mean / mean_divisor
|
||||
|
||||
# we find the dissimilarity
|
||||
for k in range(n_clusters):
|
||||
for n in range(n_samples):
|
||||
dist = 0
|
||||
for d in range(dimensions):
|
||||
dist += np.abs(data[n, d] - centroids[k, d])**2
|
||||
distances[n, k] = dist
|
||||
|
||||
# assign each point
|
||||
for n in range(n_samples):
|
||||
smallest = 1e10
|
||||
smallest_row_index = 1e10
|
||||
for k in range(n_clusters):
|
||||
if distances[n, k] < smallest:
|
||||
smallest = distances[n, k]
|
||||
smallest_row_index = k
|
||||
|
||||
cluster_labels[n] = smallest_row_index
|
||||
|
||||
# convergence criteria
|
||||
centroid_difference = np.sum(np.abs(centroids - prev_centroids))
|
||||
if centroid_difference < tolerance:
|
||||
print(f'Converged at iteration {iteration}')
|
||||
break
|
||||
|
||||
elif iteration == max_iterations:
|
||||
print(f'Did not converge in {max_iterations} iterations')
|
||||
|
||||
|
||||
# We now have a simple , un-optimized $k$-means
|
||||
# clustering implementation. Lets plot the final result
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot()
|
||||
unique_cluster_labels = np.unique(cluster_labels)
|
||||
for i in unique_cluster_labels:
|
||||
ax.scatter(data[cluster_labels == i, 0],
|
||||
data[cluster_labels == i, 1],
|
||||
label = i,
|
||||
alpha = 0.2)
|
||||
ax.scatter(centroids[:, 0], centroids[:, 1], c='black')
|
||||
|
||||
ax.set_title("Final Result of K-means Clustering")
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
def naive_kmeans(data, n_clusters=4, max_iterations=100, tolerance=1e-8):
|
||||
start_time = time.time()
|
||||
|
||||
n_samples, dimensions = data.shape
|
||||
n_clusters = 4
|
||||
#np.random.seed(2021)
|
||||
centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]
|
||||
distances = np.zeros((n_samples, n_clusters))
|
||||
|
||||
for k in range(n_clusters):
|
||||
for n in range(n_samples):
|
||||
dist = 0
|
||||
for d in range(dimensions):
|
||||
dist += np.abs(data[n, d] - centroids[k, d])**2
|
||||
distances[n, k] = dist
|
||||
|
||||
cluster_labels = np.zeros(n_samples, dtype='int')
|
||||
|
||||
for n in range(n_samples):
|
||||
smallest = 1e10
|
||||
smallest_row_index = 1e10
|
||||
for k in range(n_clusters):
|
||||
if distances[n, k] < smallest:
|
||||
smallest = distances[n, k]
|
||||
smallest_row_index = k
|
||||
|
||||
cluster_labels[n] = smallest_row_index
|
||||
|
||||
for iteration in range(max_iterations):
|
||||
prev_centroids = centroids.copy()
|
||||
for k in range(n_clusters):
|
||||
vector_mean = np.zeros(dimensions)
|
||||
mean_divisor = 0
|
||||
for n in range(n_samples):
|
||||
if cluster_labels[n] == k:
|
||||
vector_mean += data[n, :]
|
||||
mean_divisor += 1
|
||||
|
||||
centroids[k, :] = vector_mean / mean_divisor
|
||||
|
||||
for k in range(n_clusters):
|
||||
for n in range(n_samples):
|
||||
dist = 0
|
||||
for d in range(dimensions):
|
||||
dist += np.abs(data[n, d] - centroids[k, d])**2
|
||||
distances[n, k] = dist
|
||||
|
||||
for n in range(n_samples):
|
||||
smallest = 1e10
|
||||
smallest_row_index = 1e10
|
||||
for k in range(n_clusters):
|
||||
if distances[n, k] < smallest:
|
||||
smallest = distances[n, k]
|
||||
smallest_row_index = k
|
||||
|
||||
cluster_labels[n] = smallest_row_index
|
||||
|
||||
centroid_difference = np.sum(np.abs(centroids - prev_centroids))
|
||||
if centroid_difference < tolerance:
|
||||
print(f'Converged at iteration {iteration}')
|
||||
print(f'Runtime: {time.time() - start_time} seconds')
|
||||
|
||||
return cluster_labels, centroids
|
||||
|
||||
print(f'Did not converge in {max_iterations} iterations')
|
||||
print(f'Runtime: {time.time() - start_time} seconds')
|
||||
|
||||
return cluster_labels, centroids
|
||||
|
||||
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 78 KiB |