From 87d1e4455c7bab80d4c3381b48c17c4c19905c12 Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Tue, 8 Oct 2024 09:33:49 +0200 Subject: [PATCH] update --- .../exercisesweek41-checkpoint.ipynb | 1066 +++++++++++++++++ .../project2-checkpoint.ipynb | 341 ++++++ doc/LectureNotes/exercisesweek41.ipynb | 200 +--- doc/LectureNotes/project2.ipynb | 76 +- 4 files changed, 1501 insertions(+), 182 deletions(-) create mode 100644 doc/LectureNotes/.ipynb_checkpoints/exercisesweek41-checkpoint.ipynb create mode 100644 doc/LectureNotes/.ipynb_checkpoints/project2-checkpoint.ipynb diff --git a/doc/LectureNotes/.ipynb_checkpoints/exercisesweek41-checkpoint.ipynb b/doc/LectureNotes/.ipynb_checkpoints/exercisesweek41-checkpoint.ipynb new file mode 100644 index 000000000..f57ebb43b --- /dev/null +++ b/doc/LectureNotes/.ipynb_checkpoints/exercisesweek41-checkpoint.ipynb @@ -0,0 +1,1066 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b18bcd06", + "metadata": {}, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "7542d6aa", + "metadata": {}, + "source": [ + "# Exercises week 41\n", + "**October 4-11, 2024**\n", + "\n", + "Date: **Deadline is Friday October 11 at midnight**" + ] + }, + { + "cell_type": "markdown", + "id": "80943a15", + "metadata": {}, + "source": [ + "# Overarching aims of the exercises this week\n", + "\n", + "The aim of the exercises this week is to get started with implementing\n", + "gradient methods of relevance for project 2. This exercise will also\n", + "be continued next week with the addition of automatic differentation.\n", + "Everything you develop here will be used in project 2.\n", + "\n", + "In order to get started, we will now replace in our standard ordinary\n", + "least squares (OLS) and Ridge regression codes (from project 1) the\n", + "matrix inversion algorithm with our own gradient descent (GD) and SGD\n", + "codes. You can use the Franke function or the terrain data from\n", + "project 1. **However, we recommend using a simpler function like**\n", + "$f(x)=a_0+a_1x+a_2x^2$ or higher-order one-dimensional polynomials.\n", + "You can obviously test your final codes against for example the Franke\n", + "function. Automatic differentiation will be discussed next week.\n", + "\n", + "You should include in your analysis of the GD and SGD codes the following elements\n", + "1. A plain gradient descent with a fixed learning rate (you will need to tune it) using the analytical expression of the gradients\n", + "\n", + "2. Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate), again using the analytical expression of the gradients.\n", + "\n", + "3. Repeat these steps for stochastic gradient descent with mini batches and a given number of epochs. Use a tunable learning rate as discussed in the lectures from week 39. Discuss the results as functions of the various parameters (size of batches, number of epochs etc)\n", + "\n", + "4. Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD.\n", + "\n", + "5. Add RMSprop and Adam to your library of methods for tuning the learning rate.\n", + "\n", + "The lecture notes from weeks 39 and 40 contain more information and code examples. Feel free to use these examples.\n", + "\n", + "In summary, you should \n", + "perform an analysis of the results for OLS and Ridge regression as\n", + "function of the chosen learning rates, the number of mini-batches and\n", + "epochs as well as algorithm for scaling the learning rate. You can\n", + "also compare your own results with those that can be obtained using\n", + "for example **Scikit-Learn**'s various SGD options. Discuss your\n", + "results. For Ridge regression you need now to study the results as functions of the hyper-parameter $\\lambda$ and \n", + "the learning rate $\\eta$. Discuss your results.\n", + "\n", + "You will need your SGD code for the setup of the Neural Network and\n", + "Logistic Regression codes. You will find the Python [Seaborn\n", + "package](https://seaborn.pydata.org/generated/seaborn.heatmap.html)\n", + "useful when plotting the results as function of the learning rate\n", + "$\\eta$ and the hyper-parameter $\\lambda$ when you use Ridge\n", + "regression.\n", + "\n", + "We recommend reading chapter 8 on optimization from the textbook of [Goodfellow, Bengio and Courville](https://www.deeplearningbook.org/). This chapter contains many useful insights and discussions on the optimization part of machine learning." + ] + }, + { + "cell_type": "markdown", + "id": "2095d197", + "metadata": {}, + "source": [ + "# Code examples from week 39 and 40" + ] + }, + { + "cell_type": "markdown", + "id": "f428decb", + "metadata": {}, + "source": [ + "## Code with a Number of Minibatches which varies, analytical gradient\n", + "\n", + "In the code here we vary the number of mini-batches." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "ba38d454", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "de04b41a", + "metadata": {}, + "source": [ + "In the above code, we have use replacement in setting up the\n", + "mini-batches. The discussion\n", + "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", + "useful." + ] + }, + { + "cell_type": "markdown", + "id": "77fc1cca", + "metadata": {}, + "source": [ + "## Momentum based GD\n", + "\n", + "The stochastic gradient descent (SGD) is almost always used with a\n", + "*momentum* or inertia term that serves as a memory of the direction we\n", + "are moving in parameter space. This is typically implemented as\n", + "follows" + ] + }, + { + "cell_type": "markdown", + "id": "441d1f36", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "47434945", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", + "\\label{_auto1} \\tag{1}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f3ea5060", + "metadata": {}, + "source": [ + "where we have introduced a momentum parameter $\\gamma$, with\n", + "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", + "indicate the gradient is to be taken over a different mini-batch at\n", + "each step. We call this algorithm gradient descent with momentum\n", + "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n", + "running average of recently encountered gradients and\n", + "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n", + "used in the averaging procedure. Consistent with this, when\n", + "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n", + "earlier. An equivalent way of writing the updates is" + ] + }, + { + "cell_type": "markdown", + "id": "923628c8", + "metadata": {}, + "source": [ + "$$\n", + "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5c94031c", + "metadata": {}, + "source": [ + "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." + ] + }, + { + "cell_type": "markdown", + "id": "f3f0e9c9", + "metadata": {}, + "source": [ + "## Algorithms and codes for Adagrad, RMSprop and Adam\n", + "\n", + "The algorithms we have implemented are well described in the text by [Goodfellow, Bengio and Courville, chapter 8](https://www.deeplearningbook.org/contents/optimization.html).\n", + "\n", + "The codes which implement these algorithms are discussed after our presentation of automatic differentiation." + ] + }, + { + "cell_type": "markdown", + "id": "92253eff", + "metadata": {}, + "source": [ + "## Practical tips\n", + "\n", + "* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n", + "\n", + "* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n", + "\n", + "* **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.\n", + "\n", + "* **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.\n", + "\n", + "Geron's text, see chapter 11, has several interesting discussions." + ] + }, + { + "cell_type": "markdown", + "id": "08209015", + "metadata": {}, + "source": [ + "## Using Automatic differentation with OLS\n", + "\n", + "We conclude the part on optmization by showing how we can make codes\n", + "for linear regression and logistic regression using **autograd**. The\n", + "first example shows results with ordinary leats squares." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "f1f7d4aa", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "1bc83f33", + "metadata": {}, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "dc2a3f65", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients for OLS\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x#+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 30\n", + "\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(theta)\n", + " theta -= eta*gradients\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "# Now improve with momentum gradient descent\n", + "change = 0.0\n", + "delta_momentum = 0.3\n", + "for iter in range(Niterations):\n", + " # calculate gradient\n", + " gradients = training_gradient(theta)\n", + " # calculate update\n", + " new_change = eta*gradients+delta_momentum*change\n", + " # take a step\n", + " theta -= new_change\n", + " # save the change\n", + " change = new_change\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"theta from own gd wth momentum\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "0ef007d0", + "metadata": {}, + "source": [ + "## But noen of these can compete with Newton's method" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "0e498aa4", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Newton's method\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "def CostOLS(beta):\n", + " return (1.0/n)*np.sum((y-X @ beta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(beta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "# Note that here the Hessian does not depend on the parameters beta\n", + "invH = np.linalg.pinv(H)\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "beta = np.random.randn(2,1)\n", + "Niterations = 5\n", + "\n", + "# define the gradient\n", + "training_gradient = grad(CostOLS)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = training_gradient(beta)\n", + " beta -= invH @ gradients\n", + " print(iter,gradients[0],gradients[1])\n", + "print(\"beta from own Newton code\")\n", + "print(beta)" + ] + }, + { + "cell_type": "markdown", + "id": "40292cf3", + "metadata": {}, + "source": [ + "## Including Stochastic Gradient Descent with Autograd\n", + "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**." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "fa819b9d", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 1000\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "Xnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = Xnew.dot(theta)\n", + "ypredict2 = Xnew.dot(theta_linreg)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + "# Can you figure out a better way of setting up the contributions to each batch?\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "2ca466b4", + "metadata": {}, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "0d44a49c", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using SGD\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 100\n", + "x = 2*np.random.rand(n,1)\n", + "y = 4+3*x+np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "# Hessian matrix\n", + "H = (2.0/n)* XT_X\n", + "EigValues, EigVectors = np.linalg.eig(H)\n", + "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 1.0/np.max(EigValues)\n", + "Niterations = 100\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = (1.0/n)*training_gradient(y, X, theta)\n", + " theta -= eta*gradients\n", + "print(\"theta from own gd\")\n", + "print(theta)\n", + "\n", + "\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "change = 0.0\n", + "delta_momentum = 0.3\n", + "\n", + "for epoch in range(n_epochs):\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " eta = learning_schedule(epoch*m+i)\n", + " # calculate update\n", + " new_change = eta*gradients+delta_momentum*change\n", + " # take a step\n", + " theta -= new_change\n", + " # save the change\n", + " change = new_change\n", + "print(\"theta from own sdg with momentum\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "b82627f6", + "metadata": {}, + "source": [ + "## AdaGrad algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", + "\n", + "\n", + "\n", + "\n", + "

Figure 1:

\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "00d3aff0", + "metadata": {}, + "source": [ + "## Similar (second order function now) problem but now with AdaGrad" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "6b85aacc", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-8\n", + "for epoch in range(n_epochs):\n", + " Giter = 0.0\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " Giter += gradients*gradients\n", + " update = gradients*eta/(delta+np.sqrt(Giter))\n", + " theta -= update\n", + "print(\"theta from own AdaGrad\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "d8ddde38", + "metadata": {}, + "source": [ + "Running this code we note an almost perfect agreement with the results from matrix inversion." + ] + }, + { + "cell_type": "markdown", + "id": "ff15b503", + "metadata": {}, + "source": [ + "## RMSProp algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", + "\n", + "\n", + "\n", + "\n", + "

Figure 1:

\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "66f96d12", + "metadata": {}, + "source": [ + "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "888f1b4e", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Value for parameter rho\n", + "rho = 0.99\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-8\n", + "for epoch in range(n_epochs):\n", + " Giter = 0.0\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + "\t# Accumulated gradient\n", + "\t# Scaling with rho the new and the previous results\n", + " Giter = (rho*Giter+(1-rho)*gradients*gradients)\n", + "\t# Taking the diagonal only and inverting\n", + " update = gradients*eta/(delta+np.sqrt(Giter))\n", + "\t# Hadamard product\n", + " theta -= update\n", + "print(\"theta from own RMSprop\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "2e0860f7", + "metadata": {}, + "source": [ + "## ADAM algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", + "\n", + "\n", + "\n", + "\n", + "

Figure 1:

\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "ab4a9859", + "metadata": {}, + "source": [ + "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "ccdd4d77", + "metadata": {}, + "outputs": [], + "source": [ + "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", + "# OLS example\n", + "from random import random, seed\n", + "import numpy as np\n", + "import autograd.numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from autograd import grad\n", + "\n", + "# Note change from previous example\n", + "def CostOLS(y,X,theta):\n", + " return np.sum((y-X @ theta)**2)\n", + "\n", + "n = 1000\n", + "x = np.random.rand(n,1)\n", + "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", + "\n", + "X = np.c_[np.ones((n,1)), x, x*x]\n", + "XT_X = X.T @ X\n", + "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "\n", + "\n", + "# Note that we request the derivative wrt third argument (theta, 2 here)\n", + "training_gradient = grad(CostOLS,2)\n", + "# Define parameters for Stochastic Gradient Descent\n", + "n_epochs = 50\n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "# Guess for unknown parameters theta\n", + "theta = np.random.randn(3,1)\n", + "\n", + "# Value for learning rate\n", + "eta = 0.01\n", + "# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980\n", + "beta1 = 0.9\n", + "beta2 = 0.999\n", + "# Including AdaGrad parameter to avoid possible division by zero\n", + "delta = 1e-7\n", + "iter = 0\n", + "for epoch in range(n_epochs):\n", + " first_moment = 0.0\n", + " second_moment = 0.0\n", + " iter += 1\n", + " for i in range(m):\n", + " random_index = M*np.random.randint(m)\n", + " xi = X[random_index:random_index+M]\n", + " yi = y[random_index:random_index+M]\n", + " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", + " # Computing moments first\n", + " first_moment = beta1*first_moment + (1-beta1)*gradients\n", + " second_moment = beta2*second_moment+(1-beta2)*gradients*gradients\n", + " first_term = first_moment/(1.0-beta1**iter)\n", + " second_term = second_moment/(1.0-beta2**iter)\n", + "\t# Scaling with rho the new and the previous results\n", + " update = eta*first_term/(np.sqrt(second_term)+delta)\n", + " theta -= update\n", + "print(\"theta from own ADAM\")\n", + "print(theta)" + ] + }, + { + "cell_type": "markdown", + "id": "25ac988c", + "metadata": {}, + "source": [ + "## Introducing [JAX](https://jax.readthedocs.io/en/latest/)\n", + "\n", + "Presently, instead of using **autograd**, we recommend using [JAX](https://jax.readthedocs.io/en/latest/)\n", + "\n", + "**JAX** is Autograd and [XLA (Accelerated Linear Algebra))](https://www.tensorflow.org/xla),\n", + "brought together for high-performance numerical computing and machine learning research.\n", + "It provides composable transformations of Python+NumPy programs: differentiate, vectorize, parallelize, Just-In-Time compile to GPU/TPU, and more." + ] + }, + { + "cell_type": "markdown", + "id": "37d556d0", + "metadata": {}, + "source": [ + "### Getting started with Jax, note the way we import numpy" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "5b81d6e4", + "metadata": {}, + "outputs": [], + "source": [ + "import jax\n", + "import jax.numpy as jnp\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from jax import grad as jax_grad" + ] + }, + { + "cell_type": "markdown", + "id": "c42db672", + "metadata": {}, + "source": [ + "### A warm-up example" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "98eb2f26", + "metadata": {}, + "outputs": [], + "source": [ + "def function(x):\n", + " return x**2\n", + "\n", + "def analytical_gradient(x):\n", + " return 2*x\n", + "\n", + "def gradient_descent(starting_point, learning_rate, num_iterations, solver=\"analytical\"):\n", + " x = starting_point\n", + " trajectory_x = [x]\n", + " trajectory_y = [function(x)]\n", + "\n", + " if solver == \"analytical\":\n", + " grad = analytical_gradient \n", + " elif solver == \"jax\":\n", + " grad = jax_grad(function)\n", + " x = jnp.float64(x)\n", + " learning_rate = jnp.float64(learning_rate)\n", + "\n", + " for _ in range(num_iterations):\n", + " \n", + " x = x - learning_rate * grad(x)\n", + " trajectory_x.append(x)\n", + " trajectory_y.append(function(x))\n", + "\n", + " return trajectory_x, trajectory_y\n", + "\n", + "x = np.linspace(-5, 5, 100)\n", + "plt.plot(x, function(x), label=\"f(x)\")\n", + "\n", + "descent_x, descent_y = gradient_descent(5, 0.1, 10, solver=\"analytical\")\n", + "jax_descend_x, jax_descend_y = gradient_descent(5, 0.1, 10, solver=\"jax\")\n", + "\n", + "plt.plot(descent_x, descent_y, label=\"Gradient descent\", marker=\"o\")\n", + "plt.plot(jax_descend_x, jax_descend_y, label=\"JAX\", marker=\"x\")" + ] + }, + { + "cell_type": "markdown", + "id": "8a5f19b5", + "metadata": {}, + "source": [ + "### A more advanced example" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "d8f5eb38", + "metadata": {}, + "outputs": [], + "source": [ + "backend = np\n", + "\n", + "def function(x):\n", + " return x*backend.sin(x**2 + 1)\n", + "\n", + "def analytical_gradient(x):\n", + " return backend.sin(x**2 + 1) + 2*x**2*backend.cos(x**2 + 1)\n", + "\n", + "\n", + "x = np.linspace(-5, 5, 100)\n", + "plt.plot(x, function(x), label=\"f(x)\")\n", + "\n", + "descent_x, descent_y = gradient_descent(1, 0.01, 300, solver=\"analytical\")\n", + "\n", + "# Change the backend to JAX\n", + "backend = jnp\n", + "jax_descend_x, jax_descend_y = gradient_descent(1, 0.01, 300, solver=\"jax\")\n", + "\n", + "plt.scatter(descent_x, descent_y, label=\"Gradient descent\", marker=\"v\", s=10, color=\"red\") \n", + "plt.scatter(jax_descend_x, jax_descend_y, label=\"JAX\", marker=\"x\", s=5, color=\"black\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.18" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/.ipynb_checkpoints/project2-checkpoint.ipynb b/doc/LectureNotes/.ipynb_checkpoints/project2-checkpoint.ipynb new file mode 100644 index 000000000..9a6c5c33c --- /dev/null +++ b/doc/LectureNotes/.ipynb_checkpoints/project2-checkpoint.ipynb @@ -0,0 +1,341 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "5b2f9dda", + "metadata": {}, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "cacbd604", + "metadata": {}, + "source": [ + "# Project 2 on Machine Learning, deadline November 4 (Midnight)\n", + "**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n", + "\n", + "Date: **Oct 8, 2024**\n", + "\n", + "Copyright 1999-2024, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "acb32119", + "metadata": {}, + "source": [ + "## Classification and Regression, from linear and logistic regression to neural networks\n", + "\n", + "The main aim of this project is to study both classification and\n", + "regression problems by developing our own feed-forward neural network\n", + "(FFNN) code. We can reuse the regression algorithms studied in project\n", + "1. We will also include logistic regression for classification\n", + "problems and write our own FFNN code for studying both regression and\n", + "classification problems. The codes developed in project 1, including\n", + "bootstrap **and/or** cross-validation as well as the computation of the\n", + "mean-squared error and/or the $R2$ or the accuracy score\n", + "(classification problems) functions can also be utilized in the\n", + "present analysis.\n", + "\n", + "The data sets that we propose here are (the default sets)\n", + "\n", + "* Regression (fitting a continuous function). In this part you will need to bring back your results from project 1 and compare these with what you get from your Neural Network code to be developed here. The data sets could be\n", + "\n", + "a. A simple one-dimensional function or the Franke function or the terrain data from project 1, or data sets your propose. It could be a simpler function than the Franke function. We recommend testing a simpler function (see below). But if you wish to try more complex function, feel free to do so.\n", + "\n", + "* Classification. Here you will also need to develop a Logistic regression code that you will use to compare with the Neural Network code. The data set we propose are the so-called [Wisconsin Breat Cancer Data](https://www.kaggle.com/uciml/breast-cancer-wisconsin-data) data set of images representing various features of tumors. A longer explanation with links to the scientific literature can be found at the [Machine Learning repository of the University of California at Irvine](https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnostic%29). Feel free to consult this site and the pertinent literature.\n", + "\n", + "You can find more information about this at the [Scikit-Learn site](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html) or at the [University of California at Irvine](https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)). \n", + "\n", + "However, if you would like to study other data sets, feel free to\n", + "propose other sets. What we list here are mere suggestions from our\n", + "side. If you opt for another data set, consider using a set which has\n", + "been studied in the scientific literature. This makes it easier for\n", + "you to compare and analyze your results. Comparing with existing\n", + "results from the scientific literature is also an essential element of\n", + "the scientific discussion. The University of California at Irvine\n", + "with its Machine Learning repository at\n", + " is an excellent site to\n", + "look up for examples and\n", + "inspiration. [Kaggle.com](https://www.kaggle.com/) is an equally\n", + "interesting site. Feel free to explore these sites.\n", + "\n", + "We will start with a regression problem and we will reuse our codes from project 1 starting with writing our own Stochastic Gradient Descent (SGD) code." + ] + }, + { + "cell_type": "markdown", + "id": "027202f0", + "metadata": {}, + "source": [ + "### Part a): Write your own Stochastic Gradient Descent code, first step\n", + "\n", + "In order to get started, we will now replace in our standard ordinary\n", + "least squares (OLS) and Ridge regression codes (from project 1) the\n", + "matrix inversion algorithm with our own gradient descent (GD) and SGD\n", + "codes. You can use the Franke function or the terrain data from\n", + "project 1. **However, we recommend using a simpler function like**\n", + "$f(x)=a_0+a_1x+a_2x^2$ or higher-order one-dimensional polynomials.\n", + "You can obviously test your final codes against for example the Franke\n", + "function.\n", + "\n", + "The exercise set for week 41 should help in solving this part of the project.\n", + "\n", + "You should include in your analysis of the GD and SGD codes the following elements\n", + "1. A plain gradient descent with a fixed learning rate (you will need to tune it) using the analytical expression for the gradient.\n", + "\n", + "2. Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate). Keep using the analytical expression for the gradient.\n", + "\n", + "3. Repeat these steps for stochastic gradient descent with mini batches and a given number of epochs. Use a tunable learning rate as discussed in the lectures from weeks 39 and 40. Discuss the results as functions of the various parameters (size of batches, number of epochs etc). Use the analytical gradient.\n", + "\n", + "4. Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD.\n", + "\n", + "5. Add RMSprop and Adam to your library of methods for tuning the learning rate.\n", + "\n", + "The lecture notes from [weeks 39 and 40 contain more\n", + "details](https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html) and code examples. Feel free to use these examples.\n", + "1. Replace thereafter your analytical gradient with either **Autograd** or **JAX**\n", + "\n", + "**Feel free to use codes on these methods from the lecture notes from week 39 and week 40**.\n", + "\n", + "In summary, you should \n", + "perform an analysis of the results for OLS and Ridge regression as\n", + "function of the chosen learning rates, the number of mini-batches and\n", + "epochs as well as algorithm for scaling the learning rate. You can\n", + "also compare your own results with those that can be obtained using\n", + "for example **Scikit-Learn**'s various SGD options. Discuss your\n", + "results. For Ridge regression you need now to study the results as functions of the hyper-parameter $\\lambda$ and \n", + "the learning rate $\\eta$. Discuss your results.\n", + "\n", + "You will need your SGD code for the setup of the Neural Network and\n", + "Logistic Regression codes. You will find the Python [Seaborn\n", + "package](https://seaborn.pydata.org/generated/seaborn.heatmap.html)\n", + "useful when plotting the results as function of the learning rate\n", + "$\\eta$ and the hyper-parameter $\\lambda$ when you use Ridge\n", + "regression. Since you will use different gradient descent methods, you can also add Lasse regression. This is however optional. How to code Lasso regression is discussed in the lecture notes from week 40.\n", + "\n", + "We recommend reading chapter 8 on optimization from the textbook of Goodfellow, Bengio and Courville at . This chapter contains many useful insights and discussions on the optimization part of machine learning." + ] + }, + { + "cell_type": "markdown", + "id": "9388fa74", + "metadata": {}, + "source": [ + "### Part b): Writing your own Neural Network code\n", + "\n", + "Your aim now, and this is the central part of this project, is to\n", + "write your own Feed Forward Neural Network code implementing the back\n", + "propagation algorithm discussed in the lecture slides from [week 41](https://compphysics.github.io/MachineLearning/doc/pub/week41/ipynb/week41.ipynb) and\n", + "[week 42](https://compphysics.github.io/MachineLearning/doc/pub/week42/ipynb/week42.ipynb).\n", + "\n", + "We will focus on a regression problem first and study either the simple second-order polynomial from part a) or the \n", + "Franke function or terrain data (or both or other data sets) from\n", + "project 1.\n", + "\n", + "Discuss again your choice of cost function.\n", + "\n", + "Write an FFNN code for regression with a flexible number of hidden\n", + "layers and nodes using the Sigmoid function as activation function for\n", + "the hidden layers. Initialize the weights using a normal\n", + "distribution. How would you initialize the biases? And which\n", + "activation function would you select for the final output layer?\n", + "\n", + "Train your network and compare the results with those from your OLS and Ridge Regression codes from project 1 if you use the Franke function or the terrain data.\n", + "You should test your results against a similar code using **Scikit-Learn** (see the examples in the above lecture notes from weeks 41 and 42) or **tensorflow/keras** or **Pytorch** (for Pytorch, see Raschka et al.'s text chapters 12 and 13). \n", + "\n", + "Comment your results and give a critical discussion of the results\n", + "obtained with the Linear Regression code and your own Neural Network\n", + "code. \n", + "Make an analysis of the regularization parameters and the learning rates employed to find the optimal MSE and $R2$ scores.\n", + "\n", + "A useful reference on the back progagation algorithm is Nielsen's book at . It is an excellent\n", + "read." + ] + }, + { + "cell_type": "markdown", + "id": "49666354", + "metadata": {}, + "source": [ + "### Part c): Testing different activation functions\n", + "\n", + "You should now also test different activation functions for the hidden layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and discuss your results. You may also study the way you initialize your weights and biases." + ] + }, + { + "cell_type": "markdown", + "id": "79aacf29", + "metadata": {}, + "source": [ + "### Part d): Classification analysis using neural networks\n", + "\n", + "With a well-written code it should now be easy to change the\n", + "activation function for the output layer.\n", + "\n", + "Here we will change the cost function for our neural network code\n", + "developed in parts b) and c) in order to perform a classification analysis. \n", + "\n", + "We will here study the Wisconsin Breast Cancer data set. This is a typical binary classification problem with just one single output, either True or Fale, $0$ or $1$ etc.\n", + "You find more information about this at the [Scikit-Learn\n", + "site](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html) or at the [University of California\n", + "at Irvine](https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)). \n", + "\n", + "To measure the performance of our classification problem we use the\n", + "so-called *accuracy* score. The accuracy is as you would expect just\n", + "the number of correctly guessed targets $t_i$ divided by the total\n", + "number of targets, that is" + ] + }, + { + "cell_type": "markdown", + "id": "42e22900", + "metadata": {}, + "source": [ + "$$\n", + "\\text{Accuracy} = \\frac{\\sum_{i=1}^n I(t_i = y_i)}{n} ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "82ae763d", + "metadata": {}, + "source": [ + "where $I$ is the indicator function, $1$ if $t_i = y_i$ and $0$\n", + "otherwise if we have a binary classification problem. Here $t_i$\n", + "represents the target and $y_i$ the outputs of your FFNN code and $n$ is simply the number of targets $t_i$.\n", + "\n", + "Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\\lambda$ (as you did in Ridge Regression), various activation functions, number of hidden layers and nodes and activation functions. \n", + "\n", + "As stated in the introduction, it can also be useful to study other\n", + "datasets. \n", + "\n", + "Again, we strongly recommend that you compare your own neural Network\n", + "code for classification and pertinent results against a similar code using **Scikit-Learn** or **tensorflow/keras** or **pytorch**." + ] + }, + { + "cell_type": "markdown", + "id": "1d6b84d1", + "metadata": {}, + "source": [ + "### Part e): Write your Logistic Regression code, final step\n", + "\n", + "Finally, we want to compare the FFNN code we have developed with\n", + "Logistic regression, that is we wish to compare our neural network\n", + "classification results with the results we can obtain with another\n", + "method.\n", + "\n", + "Define your cost function and the design matrix before you start writing your code.\n", + "Write thereafter a Logistic regression code using your SGD algorithm. You can also use standard gradient descent in this case, with a learning rate as hyper-parameter.\n", + "Study the results as functions of the chosen learning rates.\n", + "Add also an $l_2$ regularization parameter $\\lambda$. Compare your results with those from your FFNN code as well as those obtained using **Scikit-Learn**'s logistic regression functionality.\n", + "\n", + "The weblink here compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article." + ] + }, + { + "cell_type": "markdown", + "id": "0bce8832", + "metadata": {}, + "source": [ + "### Part f) Critical evaluation of the various algorithms\n", + "\n", + "After all these glorious calculations, you should now summarize the\n", + "various algorithms and come with a critical evaluation of their pros\n", + "and cons. Which algorithm works best for the regression case and which\n", + "is best for the classification case. These codes can also be part of\n", + "your final project 3, but now applied to other data sets." + ] + }, + { + "cell_type": "markdown", + "id": "51b1b29b", + "metadata": {}, + "source": [ + "## Background literature\n", + "\n", + "1. The text of Michael Nielsen is highly recommended, see Nielsen's book at . It is an excellent read.\n", + "\n", + "2. Goodfellow, Bengio and Courville, Deep Learning at . Here we recommend chapters 6, 7 and 8\n", + "\n", + "3. Raschka et al. at . Here we recommend chapters 11, 12 and 13." + ] + }, + { + "cell_type": "markdown", + "id": "7e4ffbbd", + "metadata": {}, + "source": [ + "## Introduction to numerical projects\n", + "\n", + "Here follows a brief recipe and recommendation on how to write a report for each\n", + "project.\n", + "\n", + " * Give a short description of the nature of the problem and the eventual numerical methods you have used.\n", + "\n", + " * Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.\n", + "\n", + " * Include the source code of your program. Comment your program properly.\n", + "\n", + " * If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.\n", + "\n", + " * Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.\n", + "\n", + " * Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.\n", + "\n", + " * Try to give an interpretation of you results in your answers to the problems.\n", + "\n", + " * Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.\n", + "\n", + " * Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning." + ] + }, + { + "cell_type": "markdown", + "id": "56112b03", + "metadata": {}, + "source": [ + "## Format for electronic delivery of report and programs\n", + "\n", + "The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:\n", + "\n", + " * Use Canvas to hand in your projects, log in at with your normal UiO username and password.\n", + "\n", + " * Upload **only** the report file or the link to your GitHub/GitLab or similar typo of repos! For the source code file(s) you have developed please provide us with your link to your GitHub/GitLab or similar domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.\n", + "\n", + " * In your GitHub/GitLab or similar repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.\n", + "\n", + "Finally, \n", + "we encourage you to collaborate. Optimal working groups consist of \n", + "2-3 students. You can then hand in a common report." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.18" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/exercisesweek41.ipynb b/doc/LectureNotes/exercisesweek41.ipynb index d776eda31..f57ebb43b 100644 --- a/doc/LectureNotes/exercisesweek41.ipynb +++ b/doc/LectureNotes/exercisesweek41.ipynb @@ -3,9 +3,7 @@ { "cell_type": "markdown", "id": "b18bcd06", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", @@ -15,9 +13,7 @@ { "cell_type": "markdown", "id": "7542d6aa", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Exercises week 41\n", "**October 4-11, 2024**\n", @@ -28,9 +24,7 @@ { "cell_type": "markdown", "id": "80943a15", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Overarching aims of the exercises this week\n", "\n", @@ -83,9 +77,7 @@ { "cell_type": "markdown", "id": "2095d197", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Code examples from week 39 and 40" ] @@ -93,9 +85,7 @@ { "cell_type": "markdown", "id": "f428decb", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Code with a Number of Minibatches which varies, analytical gradient\n", "\n", @@ -106,10 +96,7 @@ "cell_type": "code", "execution_count": 1, "id": "ba38d454", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", @@ -185,9 +172,7 @@ { "cell_type": "markdown", "id": "de04b41a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "In the above code, we have use replacement in setting up the\n", "mini-batches. The discussion\n", @@ -198,9 +183,7 @@ { "cell_type": "markdown", "id": "77fc1cca", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Momentum based GD\n", "\n", @@ -213,9 +196,7 @@ { "cell_type": "markdown", "id": "441d1f36", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", @@ -225,9 +206,7 @@ { "cell_type": "markdown", "id": "47434945", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", "
\n", @@ -243,9 +222,7 @@ { "cell_type": "markdown", "id": "f3ea5060", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we have introduced a momentum parameter $\\gamma$, with\n", "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", @@ -262,9 +239,7 @@ { "cell_type": "markdown", "id": "923628c8", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", @@ -274,9 +249,7 @@ { "cell_type": "markdown", "id": "5c94031c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." ] @@ -284,9 +257,7 @@ { "cell_type": "markdown", "id": "f3f0e9c9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Algorithms and codes for Adagrad, RMSprop and Adam\n", "\n", @@ -298,9 +269,7 @@ { "cell_type": "markdown", "id": "92253eff", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Practical tips\n", "\n", @@ -318,9 +287,7 @@ { "cell_type": "markdown", "id": "08209015", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Using Automatic differentation with OLS\n", "\n", @@ -333,10 +300,7 @@ "cell_type": "code", "execution_count": 2, "id": "f1f7d4aa", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Autograd to calculate gradients for OLS\n", @@ -393,9 +357,7 @@ { "cell_type": "markdown", "id": "1bc83f33", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Same code but now with momentum gradient descent" ] @@ -404,10 +366,7 @@ "cell_type": "code", "execution_count": 3, "id": "dc2a3f65", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Autograd to calculate gradients for OLS\n", @@ -468,9 +427,7 @@ { "cell_type": "markdown", "id": "0ef007d0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## But noen of these can compete with Newton's method" ] @@ -479,10 +436,7 @@ "cell_type": "code", "execution_count": 4, "id": "0e498aa4", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Newton's method\n", @@ -528,9 +482,7 @@ { "cell_type": "markdown", "id": "40292cf3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Including Stochastic Gradient Descent with Autograd\n", "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**." @@ -540,10 +492,7 @@ "cell_type": "code", "execution_count": 5, "id": "fa819b9d", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Autograd to calculate gradients using SGD\n", @@ -624,9 +573,7 @@ { "cell_type": "markdown", "id": "2ca466b4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Same code but now with momentum gradient descent" ] @@ -635,10 +582,7 @@ "cell_type": "code", "execution_count": 6, "id": "0d44a49c", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Autograd to calculate gradients using SGD\n", @@ -713,9 +657,7 @@ { "cell_type": "markdown", "id": "b82627f6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## AdaGrad algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", "\n", @@ -729,9 +671,7 @@ { "cell_type": "markdown", "id": "00d3aff0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Similar (second order function now) problem but now with AdaGrad" ] @@ -740,10 +680,7 @@ "cell_type": "code", "execution_count": 7, "id": "6b85aacc", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent\n", @@ -799,9 +736,7 @@ { "cell_type": "markdown", "id": "d8ddde38", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Running this code we note an almost perfect agreement with the results from matrix inversion." ] @@ -809,9 +744,7 @@ { "cell_type": "markdown", "id": "ff15b503", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## RMSProp algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", "\n", @@ -825,9 +758,7 @@ { "cell_type": "markdown", "id": "66f96d12", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" ] @@ -836,10 +767,7 @@ "cell_type": "code", "execution_count": 8, "id": "888f1b4e", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", @@ -901,9 +829,7 @@ { "cell_type": "markdown", "id": "2e0860f7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## ADAM algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", "\n", @@ -917,9 +843,7 @@ { "cell_type": "markdown", "id": "ab4a9859", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" ] @@ -928,10 +852,7 @@ "cell_type": "code", "execution_count": 9, "id": "ccdd4d77", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", @@ -998,9 +919,7 @@ { "cell_type": "markdown", "id": "25ac988c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Introducing [JAX](https://jax.readthedocs.io/en/latest/)\n", "\n", @@ -1014,9 +933,7 @@ { "cell_type": "markdown", "id": "37d556d0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Getting started with Jax, note the way we import numpy" ] @@ -1025,10 +942,7 @@ "cell_type": "code", "execution_count": 10, "id": "5b81d6e4", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "import jax\n", @@ -1042,9 +956,7 @@ { "cell_type": "markdown", "id": "c42db672", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### A warm-up example" ] @@ -1053,10 +965,7 @@ "cell_type": "code", "execution_count": 11, "id": "98eb2f26", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "def function(x):\n", @@ -1098,9 +1007,7 @@ { "cell_type": "markdown", "id": "8a5f19b5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### A more advanced example" ] @@ -1109,10 +1016,7 @@ "cell_type": "code", "execution_count": 12, "id": "d8f5eb38", - "metadata": { - "collapsed": false, - "editable": true - }, + "metadata": {}, "outputs": [], "source": [ "backend = np\n", @@ -1138,7 +1042,25 @@ ] } ], - "metadata": {}, + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.18" + } + }, "nbformat": 4, "nbformat_minor": 5 } diff --git a/doc/LectureNotes/project2.ipynb b/doc/LectureNotes/project2.ipynb index c1411ffd6..9a6c5c33c 100644 --- a/doc/LectureNotes/project2.ipynb +++ b/doc/LectureNotes/project2.ipynb @@ -3,9 +3,7 @@ { "cell_type": "markdown", "id": "5b2f9dda", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "\n", @@ -15,9 +13,7 @@ { "cell_type": "markdown", "id": "cacbd604", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "# Project 2 on Machine Learning, deadline November 4 (Midnight)\n", "**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n", @@ -30,9 +26,7 @@ { "cell_type": "markdown", "id": "acb32119", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Classification and Regression, from linear and logistic regression to neural networks\n", "\n", @@ -76,9 +70,7 @@ { "cell_type": "markdown", "id": "027202f0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Part a): Write your own Stochastic Gradient Descent code, first step\n", "\n", @@ -132,9 +124,7 @@ { "cell_type": "markdown", "id": "9388fa74", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Part b): Writing your own Neural Network code\n", "\n", @@ -170,9 +160,7 @@ { "cell_type": "markdown", "id": "49666354", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Part c): Testing different activation functions\n", "\n", @@ -182,9 +170,7 @@ { "cell_type": "markdown", "id": "79aacf29", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Part d): Classification analysis using neural networks\n", "\n", @@ -208,9 +194,7 @@ { "cell_type": "markdown", "id": "42e22900", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\text{Accuracy} = \\frac{\\sum_{i=1}^n I(t_i = y_i)}{n} ,\n", @@ -220,9 +204,7 @@ { "cell_type": "markdown", "id": "82ae763d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $I$ is the indicator function, $1$ if $t_i = y_i$ and $0$\n", "otherwise if we have a binary classification problem. Here $t_i$\n", @@ -240,9 +222,7 @@ { "cell_type": "markdown", "id": "1d6b84d1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Part e): Write your Logistic Regression code, final step\n", "\n", @@ -262,9 +242,7 @@ { "cell_type": "markdown", "id": "0bce8832", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "### Part f) Critical evaluation of the various algorithms\n", "\n", @@ -278,9 +256,7 @@ { "cell_type": "markdown", "id": "51b1b29b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Background literature\n", "\n", @@ -294,9 +270,7 @@ { "cell_type": "markdown", "id": "7e4ffbbd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Introduction to numerical projects\n", "\n", @@ -325,9 +299,7 @@ { "cell_type": "markdown", "id": "56112b03", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Format for electronic delivery of report and programs\n", "\n", @@ -345,7 +317,25 @@ ] } ], - "metadata": {}, + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.18" + } + }, "nbformat": 4, "nbformat_minor": 5 }