diff --git a/doc/HandWrittenNotes/2025/FYSSTKweek43.pdf b/doc/HandWrittenNotes/2025/FYSSTKweek43.pdf new file mode 100644 index 000000000..4186ab06a Binary files /dev/null and b/doc/HandWrittenNotes/2025/FYSSTKweek43.pdf differ diff --git a/doc/LectureNotes/.ipynb_checkpoints/exercisesweek43-checkpoint.ipynb b/doc/LectureNotes/.ipynb_checkpoints/exercisesweek43-checkpoint.ipynb index 6d6019289..f80e8787a 100644 --- a/doc/LectureNotes/.ipynb_checkpoints/exercisesweek43-checkpoint.ipynb +++ b/doc/LectureNotes/.ipynb_checkpoints/exercisesweek43-checkpoint.ipynb @@ -2,1492 +2,624 @@ "cells": [ { "cell_type": "markdown", - "id": "b2937d10", - "metadata": {}, + "id": "860d70d8", + "metadata": { + "editable": true + }, "source": [ "\n", - "" + "" ] }, { "cell_type": "markdown", - "id": "3dd00d19", - "metadata": {}, + "id": "119c0988", + "metadata": { + "editable": true + }, "source": [ - "# Exercises weeks 43 and 44 \n", - "**October 23-27, 2023**\n", + "# Exercises week 43 \n", + "**October 20-24, 2025**\n", "\n", - "Date: **Deadline is Sunday November 5 at midnight**\n", - "\n", - "You can hand in the exercises from week 43 and week 44 as one exercise and get a total score of two additional points." + "Date: **Deadline Friday October 24 at midnight**" ] }, { "cell_type": "markdown", - "id": "82a19a1d", - "metadata": {}, + "id": "909887eb", + "metadata": { + "editable": true + }, "source": [ - "# Overarching aims of the exercises weeks 43 and 44\n", + "# Overarching aims of the exercises for week 43\n", "\n", - "The aim of the exercises this week and next week is to get started with writing a neural network code\n", - "of relevance for project 2. \n", + "The aim of the exercises this week is to gain some confidence with\n", + "ways to visualize the results of a classification problem. We will\n", + "target three ways of setting up the analysis. The first and simplest\n", + "one is the\n", + "1. so-called confusion matrix. The next one is the so-called\n", "\n", - "During week 41 we discussed three different types of gates, the\n", - "so-called XOR, the OR and the AND gates. In order to develop a code\n", - "for neural networks, it can be useful to set up a simpler system with\n", - "only two inputs and one output. This can make it easier to debug and\n", - "study the feed forward pass and the back propagation part. In the\n", - "exercise this and next week, we propose to study this system with just\n", - "one hidden layer and two hidden nodes. There is only one output node\n", - "and we can choose to use either a simple regression case (fitting a\n", - "line) or just a binary classification case with the cross-entropy as\n", - "cost function.\n", + "2. ROC curve. Finally we have the\n", "\n", - "Their inputs and outputs can be\n", - "summarized using the following tables, first for the OR gate with\n", - "inputs $x_1$ and $x_2$ and outputs $y$:\n", + "3. Cumulative gain curve.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 1
" + "We will use Logistic Regression as method for the classification in\n", + "this exercise. You can compare these results with those obtained with\n", + "your neural network code from project 2 without a hidden layer.\n", + "\n", + "In these exercises we will use binary and multi-class data sets\n", + "(the Iris data set from week 41).\n", + "\n", + "The underlying mathematics is described here." ] }, { "cell_type": "markdown", - "id": "f74f69af", - "metadata": {}, + "id": "1e1cb4fb", + "metadata": { + "editable": true + }, "source": [ - "## The AND and XOR Gates\n", + "### Confusion Matrix\n", "\n", - "The AND gate is defined as\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 0
1 0 0
1 1 1
\n", - "\n", - "And finally we have the XOR gate\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 0
" + "A **confusion matrix** summarizes a classifier’s performance by\n", + "tabulating predictions versus true labels. For binary classification,\n", + "it is a $2\\times2$ table whose entries are counts of outcomes:" ] }, { "cell_type": "markdown", - "id": "1b52d47a", - "metadata": {}, - "source": [ - "## Representing the Data Sets\n", - "\n", - "Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads" - ] - }, - { - "cell_type": "markdown", - "id": "3e6910cb", - "metadata": {}, + "id": "7b090385", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", - " 0 & 1 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 1 & 1 \\end{bmatrix},\n", + "\\begin{array}{l|cc} & \\text{Predicted Positive} & \\text{Predicted Negative} \\\\ \\hline \\text{Actual Positive} & TP & FN \\\\ \\text{Actual Negative} & FP & TN \\end{array}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "90a3b78a", - "metadata": {}, + "id": "1e14904b", + "metadata": { + "editable": true + }, "source": [ - "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate.\n", - "\n", - "Your tasks here are\n", - "\n", - "1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.\n", - "\n", - "2. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.\n", - "\n", - "3. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.\n", - "\n", - "4. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.\n", - "\n", - "5. Set up the cost function (cross entropy for classification of binary cases).\n", - "\n", - "6. Calculate the gradients needed for the back propagation part.\n", - "\n", - "7. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.\n", - "\n", - "8. Train the network and study your results and compare with results obtained either with **scikit-learn** or **TensorFlow**.\n", - "\n", - "Everything you develop here can be used directly into the code for the project." + "Here TP (true positives) is the number of cases correctly predicted as\n", + "positive, FP (false positives) is the number incorrectly predicted as\n", + "positive, TN (true negatives) is correctly predicted negative, and FN\n", + "(false negatives) is incorrectly predicted negative . In other words,\n", + "“positive” means class 1 and “negative” means class 0; for example, TP\n", + "occurs when the prediction and actual are both positive. Formally:" ] }, { "cell_type": "markdown", - "id": "d6a3ab1e", - "metadata": {}, + "id": "e93ea290", + "metadata": { + "editable": true + }, "source": [ - "## Setting up the Neural Network\n", + "$$\n", + "\\text{TPR} = \\frac{\\text{TP}}{\\text{TP} + \\text{FN}}, \\quad \\text{FPR} = \\frac{\\text{FP}}{\\text{FP} + \\text{TN}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c80bea5b", + "metadata": { + "editable": true + }, + "source": [ + "where TPR and FPR are the true and false positive rates defined below.\n", "\n", - "We define first our design matrix and the various output vectors for the different gates." + "In multiclass classification with $K$ classes, the confusion matrix\n", + "generalizes to a $K\\times K$ table. Entry $N_{ij}$ in the table is\n", + "the count of instances whose true class is $i$ and whose predicted\n", + "class is $j$. For example, a three-class confusion matrix can be written\n", + "as:" + ] + }, + { + "cell_type": "markdown", + "id": "a0f68f5f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{array}{c|ccc} & \\text{Pred Class 1} & \\text{Pred Class 2} & \\text{Pred Class 3} \\\\ \\hline \\text{Act Class 1} & N_{11} & N_{12} & N_{13} \\\\ \\text{Act Class 2} & N_{21} & N_{22} & N_{23} \\\\ \\text{Act Class 3} & N_{31} & N_{32} & N_{33} \\end{array}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "869669b2", + "metadata": { + "editable": true + }, + "source": [ + "Here the diagonal entries $N_{ii}$ are the true positives for each\n", + "class, and off-diagonal entries are misclassifications. This matrix\n", + "allows computation of per-class metrics: e.g. for class $i$,\n", + "$\\mathrm{TP}_i=N_{ii}$, $\\mathrm{FN}_i=\\sum_{j\\neq i}N_{ij}$,\n", + "$\\mathrm{FP}_i=\\sum_{j\\neq i}N_{ji}$, and $\\mathrm{TN}_i$ is the sum of\n", + "all remaining entries.\n", + "\n", + "As defined above, TPR and FPR come from the binary case. In binary\n", + "terms with $P$ actual positives and $N$ actual negatives, one has" + ] + }, + { + "cell_type": "markdown", + "id": "2abd82a7", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\text{TPR} = \\frac{TP}{P} = \\frac{TP}{TP+FN}, \\quad \\text{FPR} =\n", + "\\frac{FP}{N} = \\frac{FP}{FP+TN},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2f79325c", + "metadata": { + "editable": true + }, + "source": [ + "as used in standard confusion-matrix\n", + "formulations. These rates will be used in constructing ROC curves." + ] + }, + { + "cell_type": "markdown", + "id": "0ce65a47", + "metadata": { + "editable": true + }, + "source": [ + "### ROC Curve\n", + "\n", + "The Receiver Operating Characteristic (ROC) curve plots the trade-off\n", + "between true positives and false positives as a discrimination\n", + "threshold varies. Specifically, for a binary classifier that outputs\n", + "a score or probability, one varies the threshold $t$ for declaring\n", + "**positive**, and computes at each $t$ the true positive rate\n", + "$\\mathrm{TPR}(t)$ and false positive rate $\\mathrm{FPR}(t)$ using the\n", + "confusion matrix at that threshold. The ROC curve is then the graph\n", + "of TPR versus FPR. By definition," + ] + }, + { + "cell_type": "markdown", + "id": "d750fdff", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{TPR} = \\frac{TP}{TP+FN}, \\qquad \\mathrm{FPR} = \\frac{FP}{FP+TN},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "561bfb2c", + "metadata": { + "editable": true + }, + "source": [ + "where $TP,FP,TN,FN$ are counts determined by threshold $t$. A perfect\n", + "classifier would reach the point (FPR=0, TPR=1) at some threshold.\n", + "\n", + "Formally, the ROC curve is obtained by plotting\n", + "$(\\mathrm{FPR}(t),\\mathrm{TPR}(t))$ for all $t\\in[0,1]$ (or as $t$\n", + "sweeps through the sorted scores). The Area Under the ROC Curve (AUC)\n", + "quantifies the average performance over all thresholds. It can be\n", + "interpreted probabilistically: $\\mathrm{AUC} =\n", + "\\Pr\\bigl(s(X^+)>s(X^-)\\bigr)$, the probability that a random positive\n", + "instance $X^+$ receives a higher score $s$ than a random negative\n", + "instance $X^-$ . Equivalently, the AUC is the integral under the ROC\n", + "curve:" + ] + }, + { + "cell_type": "markdown", + "id": "5ca722fe", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{AUC} \\;=\\; \\int_{0}^{1} \\mathrm{TPR}(f)\\,df,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "30080a86", + "metadata": { + "editable": true + }, + "source": [ + "where $f$ ranges over FPR (or fraction of negatives). A model that guesses at random yields a diagonal ROC (AUC=0.5), whereas a perfect model yields AUC=1.0." + ] + }, + { + "cell_type": "markdown", + "id": "9e627156", + "metadata": { + "editable": true + }, + "source": [ + "### Cumulative Gain\n", + "\n", + "The cumulative gain curve (or gains chart) evaluates how many\n", + "positives are captured as one targets an increasing fraction of the\n", + "population, sorted by model confidence. To construct it, sort all\n", + "instances by decreasing predicted probability of the positive class.\n", + "Then, for the top $\\alpha$ fraction of instances, compute the fraction\n", + "of all actual positives that fall in this subset. In formula form, if\n", + "$P$ is the total number of positive instances and $P(\\alpha)$ is the\n", + "number of positives among the top $\\alpha$ of the data, the cumulative\n", + "gain at level $\\alpha$ is" + ] + }, + { + "cell_type": "markdown", + "id": "3e9132ef", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{Gain}(\\alpha) \\;=\\; \\frac{P(\\alpha)}{P}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "75be6f5c", + "metadata": { + "editable": true + }, + "source": [ + "For example, cutting off at the top 10% of predictions yields a gain\n", + "equal to (positives in top 10%) divided by (total positives) .\n", + "Plotting $\\mathrm{Gain}(\\alpha)$ versus $\\alpha$ (often in percent)\n", + "gives the gain curve. The baseline (random) curve is the diagonal\n", + "$\\mathrm{Gain}(\\alpha)=\\alpha$, while an ideal model has a steep climb\n", + "toward 1.\n", + "\n", + "A related measure is the {\\em lift}, often called the gain ratio. It is the ratio of the model’s capture rate to that of random selection. Equivalently," + ] + }, + { + "cell_type": "markdown", + "id": "e5525570", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{Lift}(\\alpha) \\;=\\; \\frac{\\mathrm{Gain}(\\alpha)}{\\alpha}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "18ff8dc2", + "metadata": { + "editable": true + }, + "source": [ + "A lift $>1$ indicates better-than-random targeting. In practice, gain\n", + "and lift charts (used e.g.\\ in marketing or imbalanced classification)\n", + "show how many positives can be “gained” by focusing on a fraction of\n", + "the population ." + ] + }, + { + "cell_type": "markdown", + "id": "c3d3fde8", + "metadata": { + "editable": true + }, + "source": [ + "### Other measures: Precision, Recall, and the F$_1$ Measure\n", + "\n", + "Precision and recall (sensitivity) quantify binary classification\n", + "accuracy in terms of positive predictions. They are defined from the\n", + "confusion matrix as:" + ] + }, + { + "cell_type": "markdown", + "id": "f1f14c8e", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\text{Precision} = \\frac{TP}{TP + FP}, \\qquad \\text{Recall} = \\frac{TP}{TP + FN}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "422cc743", + "metadata": { + "editable": true + }, + "source": [ + "Precision is the fraction of predicted positives that are correct, and\n", + "recall is the fraction of actual positives that are correctly\n", + "identified . A high-precision classifier makes few false-positive\n", + "errors, while a high-recall classifier makes few false-negative\n", + "errors.\n", + "\n", + "The F$_1$ score (balanced F-measure) combines precision and recall into a single metric via their harmonic mean. The usual formula is:" + ] + }, + { + "cell_type": "markdown", + "id": "621a2e8b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "F_1 =2\\frac{\\text{Precision}\\times\\text{Recall}}{\\text{Precision} + \\text{Recall}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "62eee54a", + "metadata": { + "editable": true + }, + "source": [ + "This can be shown to equal" + ] + }, + { + "cell_type": "markdown", + "id": "7a6a2e7a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{2\\,TP}{2\\,TP + FP + FN}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b96c9ff4", + "metadata": { + "editable": true + }, + "source": [ + "The F$_1$ score ranges from 0 (worst) to 1 (best), and balances the\n", + "trade-off between precision and recall.\n", + "\n", + "For multi-class classification, one computes per-class\n", + "precision/recall/F$_1$ (treating each class as “positive” in a\n", + "one-vs-rest manner) and then averages. Common averaging methods are:\n", + "\n", + "Micro-averaging: Sum all true positives, false positives, and false negatives across classes, then compute precision/recall/F$_1$ from these totals.\n", + "Macro-averaging: Compute the F$1$ score $F{1,i}$ for each class $i$ separately, then take the unweighted mean: $F_{1,\\mathrm{macro}} = \\frac{1}{K}\\sum_{i=1}^K F_{1,i}$ . This treats all classes equally regardless of size.\n", + "Weighted-averaging: Like macro-average, but weight each class’s $F_{1,i}$ by its support $n_i$ (true count): $F_{1,\\mathrm{weighted}} = \\frac{1}{N}\\sum_{i=1}^K n_i F_{1,i}$, where $N=\\sum_i n_i$. This accounts for class imbalance by giving more weight to larger classes .\n", + "\n", + "Each of these averages has different use-cases. Micro-average is\n", + "dominated by common classes, macro-average highlights performance on\n", + "rare classes, and weighted-average is a compromise. These formulas\n", + "and concepts allow rigorous evaluation of classifier performance in\n", + "both binary and multi-class settings." + ] + }, + { + "cell_type": "markdown", + "id": "9274bf3f", + "metadata": { + "editable": true + }, + "source": [ + "## Exercises\n", + "\n", + "Here is a simple code example which uses the Logistic regression machinery from **scikit-learn**.\n", + "At the end it sets up the confusion matrix and the ROC and cumulative gain curves.\n", + "Feel free to use these functionalities (we don't expect you to write your own code for say the confusion matrix)." ] }, { "cell_type": "code", "execution_count": 1, - "id": "152123b0", - "metadata": {}, + "id": "be9ff0b9", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "%matplotlib inline\n", "\n", - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "# import necessary packages\n", - "import numpy as np\n", "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " probabilities = sigmoid(z_o)\n", - " return probabilities\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 2\n", - "n_features = 2\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01\n", - "\n", - "probabilities = feed_forward(X)\n", - "print(probabilities)\n", - "\n", - "\n", - "predictions = predict(X)\n", - "print(predictions)" - ] - }, - { - "cell_type": "markdown", - "id": "73319f0a", - "metadata": {}, - "source": [ - "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." - ] - }, - { - "cell_type": "markdown", - "id": "a7e0c47a", - "metadata": {}, - "source": [ - "## The Code using Scikit-Learn" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "dbbacc67", - "metadata": {}, - "outputs": [], - "source": [ - "# import necessary packages\n", "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.metrics import accuracy_score\n", - "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split \n", + "# from sklearn.datasets import fill in the data set\n", + "from sklearn.linear_model import LogisticRegression\n", "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", + "# Load the data, fill inn\n", + "mydata.data = ?\n", "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", + "X_train, X_test, y_train, y_test = train_test_split(mydata.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "# Logistic Regression\n", + "# define which type of problem, binary or multiclass\n", + "logreg = LogisticRegression(solver='lbfgs')\n", + "logreg.fit(X_train, y_train)\n", "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import cross_validate\n", + "#Cross validation\n", + "accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score']\n", + "print(accuracy)\n", + "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 2\n", - "n_features = 2\n", - "\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "epochs = 100\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X, yXOR)\n", - " DNN_scikit[i][j] = dnn\n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on data set: \", dnn.score(X, yXOR))\n", - " print()\n", - "\n", - "sns.set()\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " test_pred = dnn.predict(X)\n", - " test_accuracy[i][j] = accuracy_score(yXOR, test_pred)\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", + "import scikitplot as skplt\n", + "y_pred = logreg.predict(X_test)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "plt.show()\n", + "y_probas = logreg.predict_proba(X_test)\n", + "skplt.metrics.plot_roc(y_test, y_probas)\n", + "plt.show()\n", + "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "1cac501a", - "metadata": {}, + "id": "51760b3e", + "metadata": { + "editable": true + }, "source": [ - "## Building a neural network code\n", + "### Exercise a)\n", "\n", - "Here we present a flexible object oriented codebase\n", - "for a feed forward neural network, along with a demonstration of how\n", - "to use it. Before we get into the details of the neural network, we\n", - "will first present some implementations of various schedulers, cost\n", - "functions and activation functions that can be used together with the\n", - "neural network.\n", - "\n", - "The codes here were developed by Eric Reber and Gregor Kajda during spring 2023." + "Convince yourself about the mathematics for the confusion matrix, the ROC and the cumlative gain curves for both a binary and a multiclass classification problem." ] }, { "cell_type": "markdown", - "id": "dd153528", - "metadata": {}, + "id": "c1d42f5f", + "metadata": { + "editable": true + }, "source": [ - "### Learning rate methods\n", + "### Exercise b)\n", "\n", - "The code below shows object oriented implementations of the Constant,\n", - "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", - "of the classes belong to the shared abstract Scheduler class, and\n", - "share the update_change() and reset() methods allowing for any of the\n", - "schedulers to be seamlessly used during the training stage, as will\n", - "later be shown in the fit() method of the neural\n", - "network. Update_change() only has one parameter, the gradient\n", - "($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted\n", - "from the weights. The reset() function takes no parameters, and resets\n", - "the desired variables. For Constant and Momentum, reset does nothing." + "Use a binary classification data available from **scikit-learn**. As an example you can use\n", + "the MNIST data set and just specialize to two numbers. To do so you can use the following code lines" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "d20bb8be", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_digits\n", + "digits = load_digits(n_class=2) # Load only two classes, e.g., 0 and 1\n", + "X, y = digits.data, digits.target" + ] + }, + { + "cell_type": "markdown", + "id": "828ea1cd", + "metadata": { + "editable": true + }, + "source": [ + "Alternatively, you can use the _make$\\_$classification_\n", + "functionality. This function generates a random $n$-class classification\n", + "dataset, which can be configured for binary classification by setting\n", + "n_classes=2. You can also control the number of samples, features,\n", + "informative features, redundant features, and more." ] }, { "cell_type": "code", "execution_count": 3, - "id": "f55eea63", - "metadata": {}, + "id": "d271f0ba", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ - "import autograd.numpy as np\n", - "\n", - "class Scheduler:\n", - " \"\"\"\n", - " Abstract class for Schedulers\n", - " \"\"\"\n", - "\n", - " def __init__(self, eta):\n", - " self.eta = eta\n", - "\n", - " # should be overwritten\n", - " def update_change(self, gradient):\n", - " raise NotImplementedError\n", - "\n", - " # overwritten if needed\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Constant(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - "\n", - " def update_change(self, gradient):\n", - " return self.eta * gradient\n", - " \n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Momentum(Scheduler):\n", - " def __init__(self, eta: float, momentum: float):\n", - " super().__init__(eta)\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " self.change = self.momentum * self.change + self.eta * gradient\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Adagrad(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " return self.eta * gradient * G_t_inverse\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class AdagradMomentum(Scheduler):\n", - " def __init__(self, eta, momentum):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class RMS_prop(Scheduler):\n", - " def __init__(self, eta, rho):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.second = 0.0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", - " return self.eta * gradient / (np.sqrt(self.second + delta))\n", - "\n", - " def reset(self):\n", - " self.second = 0.0\n", - "\n", - "\n", - "class Adam(Scheduler):\n", - " def __init__(self, eta, rho, rho2):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.rho2 = rho2\n", - " self.moment = 0\n", - " self.second = 0\n", - " self.n_epochs = 1\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", - " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", - "\n", - " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", - " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", - "\n", - " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", - "\n", - " def reset(self):\n", - " self.n_epochs += 1\n", - " self.moment = 0\n", - " self.second = 0" + "from sklearn.datasets import make_classification\n", + "X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, n_redundant=5, n_classes=2, random_state=42)" ] }, { "cell_type": "markdown", - "id": "1a9bcb3e", - "metadata": {}, + "id": "0068b032", + "metadata": { + "editable": true + }, "source": [ - "### Usage of the above learning rate schedulers\n", + "You can use this option for the multiclass case as well, see the next exercise.\n", + "If you prefer to study other binary classification datasets, feel free\n", + "to replace the above suggestions with your own dataset.\n", "\n", - "To initalize a scheduler, simply create the object and pass in the\n", - "necessary parameters such as the learning rate and the momentum as\n", - "shown below. As the Scheduler class is an abstract class it should not\n", - "called directly, and will raise an error upon usage." + "Make plots of the confusion matrix, the ROC curve and the cumulative gain curve." + ] + }, + { + "cell_type": "markdown", + "id": "c45f5b41", + "metadata": { + "editable": true + }, + "source": [ + "### Exercise c) week 43\n", + "\n", + "As a multiclass problem, we will use the Iris data set discussed in\n", + "the exercises from weeks 41 and 42. This is a three-class data set and\n", + "you can set it up using **scikit-learn**," ] }, { "cell_type": "code", "execution_count": 4, - "id": "86013cb4", - "metadata": {}, + "id": "3b045d56", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ - "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", - "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" + "from sklearn.datasets import load_iris\n", + "iris = load_iris()\n", + "X = iris.data # Features\n", + "y = iris.target # Target labels" ] }, { "cell_type": "markdown", - "id": "535331f6", - "metadata": {}, + "id": "14cc859c", + "metadata": { + "editable": true + }, "source": [ - "Here is a small example for how a segment of code using schedulers\n", - "could look. Switching out the schedulers is simple." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "7e0f6b5a", - "metadata": {}, - "outputs": [], - "source": [ - "weights = np.ones((3,3))\n", - "print(f\"Before scheduler:\\n{weights=}\")\n", - "\n", - "epochs = 10\n", - "for e in range(epochs):\n", - " gradient = np.random.rand(3, 3)\n", - " change = adam_scheduler.update_change(gradient)\n", - " weights = weights - change\n", - " adam_scheduler.reset()\n", - "\n", - "print(f\"\\nAfter scheduler:\\n{weights=}\")" - ] - }, - { - "cell_type": "markdown", - "id": "f018ae57", - "metadata": {}, - "source": [ - "### Cost functions\n", - "\n", - "Here we discuss cost functions that can be used when creating the\n", - "neural network. Every cost function takes the target vector as its\n", - "parameter, and returns a function valued only at $x$ such that it may\n", - "easily be differentiated." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "c13507bf", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "def CostOLS(target):\n", - " \n", - " def func(X):\n", - " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostLogReg(target):\n", - "\n", - " def func(X):\n", - " \n", - " return -(1.0 / target.shape[0]) * np.sum(\n", - " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", - " )\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostCrossEntropy(target):\n", - " \n", - " def func(X):\n", - " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", - "\n", - " return func" - ] - }, - { - "cell_type": "markdown", - "id": "6dab17bc", - "metadata": {}, - "source": [ - "Below we give a short example of how these cost function may be used\n", - "to obtain results if you wish to test them out on your own using\n", - "AutoGrad's automatics differentiation." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "a5dbba01", - "metadata": {}, - "outputs": [], - "source": [ - "from autograd import grad\n", - "\n", - "target = np.array([[1, 2, 3]]).T\n", - "a = np.array([[4, 5, 6]]).T\n", - "\n", - "cost_func = CostCrossEntropy\n", - "cost_func_derivative = grad(cost_func(target))\n", - "\n", - "valued_at_a = cost_func_derivative(a)\n", - "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" - ] - }, - { - "cell_type": "markdown", - "id": "b55d31d4", - "metadata": {}, - "source": [ - "### Activation functions\n", - "\n", - "Finally, before we look at the neural network, we will look at the\n", - "activation functions which can be specified between the hidden layers\n", - "and as the output function. Each function can be valued for any given\n", - "vector or matrix X, and can be differentiated via derivate()." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "b3e045a6", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import elementwise_grad\n", - "\n", - "def identity(X):\n", - " return X\n", - "\n", - "\n", - "def sigmoid(X):\n", - " try:\n", - " return 1.0 / (1 + np.exp(-X))\n", - " except FloatingPointError:\n", - " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", - "\n", - "\n", - "def softmax(X):\n", - " X = X - np.max(X, axis=-1, keepdims=True)\n", - " delta = 10e-10\n", - " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", - "\n", - "\n", - "def RELU(X):\n", - " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", - "\n", - "\n", - "def LRELU(X):\n", - " delta = 10e-4\n", - " return np.where(X > np.zeros(X.shape), X, delta * X)\n", - "\n", - "\n", - "def derivate(func):\n", - " if func.__name__ == \"RELU\":\n", - "\n", - " def func(X):\n", - " return np.where(X > 0, 1, 0)\n", - "\n", - " return func\n", - "\n", - " elif func.__name__ == \"LRELU\":\n", - "\n", - " def func(X):\n", - " delta = 10e-4\n", - " return np.where(X > 0, 1, delta)\n", - "\n", - " return func\n", - "\n", - " else:\n", - " return elementwise_grad(func)" - ] - }, - { - "cell_type": "markdown", - "id": "c0189342", - "metadata": {}, - "source": [ - "Below follows a short demonstration of how to use an activation\n", - "function. The derivative of the activation function will be important\n", - "when calculating the output delta term during backpropagation. Note\n", - "that derivate() can also be used for cost functions for a more\n", - "generalized approach." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "640aa861", - "metadata": {}, - "outputs": [], - "source": [ - "z = np.array([[4, 5, 6]]).T\n", - "print(f\"Input to activation function:\\n{z}\")\n", - "\n", - "act_func = sigmoid\n", - "a = act_func(z)\n", - "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", - "\n", - "act_func_derivative = derivate(act_func)\n", - "valued_at_z = act_func_derivative(a)\n", - "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" - ] - }, - { - "cell_type": "markdown", - "id": "1007ccdd", - "metadata": {}, - "source": [ - "### The Neural Network\n", - "\n", - "Now that we have gotten a good understanding of the implementation of\n", - "some important components, we can take a look at an object oriented\n", - "implementation of a feed forward neural network. The feed forward\n", - "neural network has been implemented as a class named FFNN, which can\n", - "be initiated as a regressor or classifier dependant on the choice of\n", - "cost function. The FFNN can have any number of input nodes, hidden\n", - "layers with any amount of hidden nodes, and any amount of output nodes\n", - "meaning it can perform multiclass classification as well as binary\n", - "classification and regression problems. Although there is a lot of\n", - "code present, it makes for an easy to use and generalizeable interface\n", - "for creating many types of neural networks as will be demonstrated\n", - "below." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "9584a2da", - "metadata": {}, - "outputs": [], - "source": [ - "import math\n", - "import autograd.numpy as np\n", - "import sys\n", - "import warnings\n", - "from autograd import grad, elementwise_grad\n", - "from random import random, seed\n", - "from copy import deepcopy, copy\n", - "from typing import Tuple, Callable\n", - "from sklearn.utils import resample\n", - "\n", - "warnings.simplefilter(\"error\")\n", - "\n", - "\n", - "class FFNN:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Feed Forward Neural Network with interface enabling flexible design of a\n", - " nerual networks architecture and the specification of activation function\n", - " in the hidden layers and output layer respectively. This model can be used\n", - " for both regression and classification problems, depending on the output function.\n", - "\n", - " Attributes:\n", - " ------------\n", - " I dimensions (tuple[int]): A list of positive integers, which specifies the\n", - " number of nodes in each of the networks layers. The first integer in the array\n", - " defines the number of nodes in the input layer, the second integer defines number\n", - " of nodes in the first hidden layer and so on until the last number, which\n", - " specifies the number of nodes in the output layer.\n", - " II hidden_func (Callable): The activation function for the hidden layers\n", - " III output_func (Callable): The activation function for the output layer\n", - " IV cost_func (Callable): Our cost function\n", - " V seed (int): Sets random seed, makes results reproducible\n", - " \"\"\"\n", - "\n", - " def __init__(\n", - " self,\n", - " dimensions: tuple[int],\n", - " hidden_func: Callable = sigmoid,\n", - " output_func: Callable = lambda x: x,\n", - " cost_func: Callable = CostOLS,\n", - " seed: int = None,\n", - " ):\n", - " self.dimensions = dimensions\n", - " self.hidden_func = hidden_func\n", - " self.output_func = output_func\n", - " self.cost_func = cost_func\n", - " self.seed = seed\n", - " self.weights = list()\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - " self.classification = None\n", - "\n", - " self.reset_weights()\n", - " self._set_classification()\n", - "\n", - " def fit(\n", - " self,\n", - " X: np.ndarray,\n", - " t: np.ndarray,\n", - " scheduler: Scheduler,\n", - " batches: int = 1,\n", - " epochs: int = 100,\n", - " lam: float = 0,\n", - " X_val: np.ndarray = None,\n", - " t_val: np.ndarray = None,\n", - " ):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " This function performs the training the neural network by performing the feedforward and backpropagation\n", - " algorithm to update the networks weights.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray) : training data\n", - " II t (np.ndarray) : target data\n", - " III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)\n", - " IV scheduler_args (list[int]) : list of all arguments necessary for scheduler\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " V batches (int) : number of batches the datasets are split into, default equal to 1\n", - " VI epochs (int) : number of iterations used to train the network, default equal to 100\n", - " VII lam (float) : regularization hyperparameter lambda\n", - " VIII X_val (np.ndarray) : validation set\n", - " IX t_val (np.ndarray) : validation target set\n", - "\n", - " Returns:\n", - " ------------\n", - " I scores (dict) : A dictionary containing the performance metrics of the model.\n", - " The number of the metrics depends on the parameters passed to the fit-function.\n", - "\n", - " \"\"\"\n", - "\n", - " # setup \n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " val_set = False\n", - " if X_val is not None and t_val is not None:\n", - " val_set = True\n", - "\n", - " # creating arrays for score metrics\n", - " train_errors = np.empty(epochs)\n", - " train_errors.fill(np.nan)\n", - " val_errors = np.empty(epochs)\n", - " val_errors.fill(np.nan)\n", - "\n", - " train_accs = np.empty(epochs)\n", - " train_accs.fill(np.nan)\n", - " val_accs = np.empty(epochs)\n", - " val_accs.fill(np.nan)\n", - "\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - "\n", - " batch_size = X.shape[0] // batches\n", - "\n", - " X, t = resample(X, t)\n", - "\n", - " # this function returns a function valued only at X\n", - " cost_function_train = self.cost_func(t)\n", - " if val_set:\n", - " cost_function_val = self.cost_func(t_val)\n", - "\n", - " # create schedulers for each weight matrix\n", - " for i in range(len(self.weights)):\n", - " self.schedulers_weight.append(copy(scheduler))\n", - " self.schedulers_bias.append(copy(scheduler))\n", - "\n", - " print(f\"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}\")\n", - "\n", - " try:\n", - " for e in range(epochs):\n", - " for i in range(batches):\n", - " # allows for minibatch gradient descent\n", - " if i == batches - 1:\n", - " # If the for loop has reached the last batch, take all thats left\n", - " X_batch = X[i * batch_size :, :]\n", - " t_batch = t[i * batch_size :, :]\n", - " else:\n", - " X_batch = X[i * batch_size : (i + 1) * batch_size, :]\n", - " t_batch = t[i * batch_size : (i + 1) * batch_size, :]\n", - "\n", - " self._feedforward(X_batch)\n", - " self._backpropagate(X_batch, t_batch, lam)\n", - "\n", - " # reset schedulers for each epoch (some schedulers pass in this call)\n", - " for scheduler in self.schedulers_weight:\n", - " scheduler.reset()\n", - "\n", - " for scheduler in self.schedulers_bias:\n", - " scheduler.reset()\n", - "\n", - " # computing performance metrics\n", - " pred_train = self.predict(X)\n", - " train_error = cost_function_train(pred_train)\n", - "\n", - " train_errors[e] = train_error\n", - " if val_set:\n", - " \n", - " pred_val = self.predict(X_val)\n", - " val_error = cost_function_val(pred_val)\n", - " val_errors[e] = val_error\n", - "\n", - " if self.classification:\n", - " train_acc = self._accuracy(self.predict(X), t)\n", - " train_accs[e] = train_acc\n", - " if val_set:\n", - " val_acc = self._accuracy(pred_val, t_val)\n", - " val_accs[e] = val_acc\n", - "\n", - " # printing progress bar\n", - " progression = e / epochs\n", - " print_length = self._progress_bar(\n", - " progression,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " except KeyboardInterrupt:\n", - " # allows for stopping training at any point and seeing the result\n", - " pass\n", - "\n", - " # visualization of training progression (similiar to tensorflow progression bar)\n", - " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", - " sys.stdout.flush()\n", - " self._progress_bar(\n", - " 1,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " sys.stdout.write(\"\")\n", - "\n", - " # return performance metrics for the entire run\n", - " scores = dict()\n", - "\n", - " scores[\"train_errors\"] = train_errors\n", - "\n", - " if val_set:\n", - " scores[\"val_errors\"] = val_errors\n", - "\n", - " if self.classification:\n", - " scores[\"train_accs\"] = train_accs\n", - "\n", - " if val_set:\n", - " scores[\"val_accs\"] = val_accs\n", - "\n", - " return scores\n", - "\n", - " def predict(self, X: np.ndarray, *, threshold=0.5):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs prediction after training of the network has been finished.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " II threshold (float) : sets minimal value for a prediction to be predicted as the positive class\n", - " in classification problems\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " This vector is thresholded if regression=False, meaning that classification results\n", - " in a vector of 1s and 0s, while regressions in an array of decimal numbers\n", - "\n", - " \"\"\"\n", - "\n", - " predict = self._feedforward(X)\n", - "\n", - " if self.classification:\n", - " return np.where(predict > threshold, 1, 0)\n", - " else:\n", - " return predict\n", - "\n", - " def reset_weights(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Resets/Reinitializes the weights in order to train the network for a new problem.\n", - "\n", - " \"\"\"\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " self.weights = list()\n", - " for i in range(len(self.dimensions) - 1):\n", - " weight_array = np.random.randn(\n", - " self.dimensions[i] + 1, self.dimensions[i + 1]\n", - " )\n", - " weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01\n", - "\n", - " self.weights.append(weight_array)\n", - "\n", - " def _feedforward(self, X: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates the activation of each layer starting at the input and ending at the output.\n", - " Each following activation is calculated from a weighted sum of each of the preceeding\n", - " activations (except in the case of the input layer).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " \"\"\"\n", - "\n", - " # reset matrices\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - "\n", - " # if X is just a vector, make it into a matrix\n", - " if len(X.shape) == 1:\n", - " X = X.reshape((1, X.shape[0]))\n", - "\n", - " # Add a coloumn of zeros as the first coloumn of the design matrix, in order\n", - " # to add bias to our data\n", - " bias = np.ones((X.shape[0], 1)) * 0.01\n", - " X = np.hstack([bias, X])\n", - "\n", - " # a^0, the nodes in the input layer (one a^0 for each row in X - where the\n", - " # exponent indicates layer number).\n", - " a = X\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(a)\n", - "\n", - " # The feed forward algorithm\n", - " for i in range(len(self.weights)):\n", - " if i < len(self.weights) - 1:\n", - " z = a @ self.weights[i]\n", - " self.z_matrices.append(z)\n", - " a = self.hidden_func(z)\n", - " # bias column again added to the data here\n", - " bias = np.ones((a.shape[0], 1)) * 0.01\n", - " a = np.hstack([bias, a])\n", - " self.a_matrices.append(a)\n", - " else:\n", - " try:\n", - " # a^L, the nodes in our output layers\n", - " z = a @ self.weights[i]\n", - " a = self.output_func(z)\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(z)\n", - " except Exception as OverflowError:\n", - " print(\n", - " \"OverflowError in fit() in FFNN\\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling\"\n", - " )\n", - "\n", - " # this will be a^L\n", - " return a\n", - "\n", - " def _backpropagate(self, X, t, lam):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs the backpropagation algorithm. In other words, this method\n", - " calculates the gradient of all the layers starting at the\n", - " output layer, and moving from right to left accumulates the gradient until\n", - " the input layer is reached. Each layers respective weights are updated while\n", - " the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each.\n", - " II t (np.ndarray): The target vector, with n rows of p targets.\n", - " III lam (float32): regularization parameter used to punish the weights in case of overfitting\n", - "\n", - " Returns:\n", - " ------------\n", - " No return value.\n", - "\n", - " \"\"\"\n", - " out_derivative = derivate(self.output_func)\n", - " hidden_derivative = derivate(self.hidden_func)\n", - "\n", - " for i in range(len(self.weights) - 1, -1, -1):\n", - " # delta terms for output\n", - " if i == len(self.weights) - 1:\n", - " # for multi-class classification\n", - " if (\n", - " self.output_func.__name__ == \"softmax\"\n", - " ):\n", - " delta_matrix = self.a_matrices[i + 1] - t\n", - " # for single class classification\n", - " else:\n", - " cost_func_derivative = grad(self.cost_func(t))\n", - " delta_matrix = out_derivative(\n", - " self.z_matrices[i + 1]\n", - " ) * cost_func_derivative(self.a_matrices[i + 1])\n", - "\n", - " # delta terms for hidden layer\n", - " else:\n", - " delta_matrix = (\n", - " self.weights[i + 1][1:, :] @ delta_matrix.T\n", - " ).T * hidden_derivative(self.z_matrices[i + 1])\n", - "\n", - " # calculate gradient\n", - " gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix\n", - " gradient_bias = np.sum(delta_matrix, axis=0).reshape(\n", - " 1, delta_matrix.shape[1]\n", - " )\n", - "\n", - " # regularization term\n", - " gradient_weights += self.weights[i][1:, :] * lam\n", - "\n", - " # use scheduler\n", - " update_matrix = np.vstack(\n", - " [\n", - " self.schedulers_bias[i].update_change(gradient_bias),\n", - " self.schedulers_weight[i].update_change(gradient_weights),\n", - " ]\n", - " )\n", - "\n", - " # update weights and bias\n", - " self.weights[i] -= update_matrix\n", - "\n", - " def _accuracy(self, prediction: np.ndarray, target: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates accuracy of given prediction to target\n", - "\n", - " Parameters:\n", - " ------------\n", - " I prediction (np.ndarray): vector of predicitons output network\n", - " (1s and 0s in case of classification, and real numbers in case of regression)\n", - " II target (np.ndarray): vector of true values (What the network ideally should predict)\n", - "\n", - " Returns:\n", - " ------------\n", - " A floating point number representing the percentage of correctly classified instances.\n", - " \"\"\"\n", - " assert prediction.size == target.size\n", - " return np.average((target == prediction))\n", - " def _set_classification(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Decides if FFNN acts as classifier (True) og regressor (False),\n", - " sets self.classification during init()\n", - " \"\"\"\n", - " self.classification = False\n", - " if (\n", - " self.cost_func.__name__ == \"CostLogReg\"\n", - " or self.cost_func.__name__ == \"CostCrossEntropy\"\n", - " ):\n", - " self.classification = True\n", - "\n", - " def _progress_bar(self, progression, **kwargs):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Displays progress of training\n", - " \"\"\"\n", - " print_length = 40\n", - " num_equals = int(progression * print_length)\n", - " num_not = print_length - num_equals\n", - " arrow = \">\" if num_equals > 0 else \"\"\n", - " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", - " perc_print = self._format(progression * 100, decimals=5)\n", - " line = f\" {bar} {perc_print}% \"\n", - "\n", - " for key in kwargs:\n", - " if not np.isnan(kwargs[key]):\n", - " value = self._format(kwargs[key], decimals=4)\n", - " line += f\"| {key}: {value} \"\n", - " sys.stdout.write(\"\\r\" + line)\n", - " sys.stdout.flush()\n", - " return len(line)\n", - "\n", - " def _format(self, value, decimals=4):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Formats decimal numbers for progress bar\n", - " \"\"\"\n", - " if value > 0:\n", - " v = value\n", - " elif value < 0:\n", - " v = -10 * value\n", - " else:\n", - " v = 1\n", - " n = 1 + math.floor(math.log10(v))\n", - " if n >= decimals - 1:\n", - " return str(round(value))\n", - " return f\"{value:.{decimals-n-1}f}\"" - ] - }, - { - "cell_type": "markdown", - "id": "9ccd1fc1", - "metadata": {}, - "source": [ - "Before we make a model, we will quickly generate a dataset we can use\n", - "for our linear regression problem as shown below" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "7f3a5b31", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "def SkrankeFunction(x, y):\n", - " return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)\n", - "\n", - "def create_X(x, y, n):\n", - " if len(x.shape) > 1:\n", - " x = np.ravel(x)\n", - " y = np.ravel(y)\n", - "\n", - " N = len(x)\n", - " l = int((n + 1) * (n + 2) / 2) # Number of elements in beta\n", - " X = np.ones((N, l))\n", - "\n", - " for i in range(1, n + 1):\n", - " q = int((i) * (i + 1) / 2)\n", - " for k in range(i + 1):\n", - " X[:, q + k] = (x ** (i - k)) * (y**k)\n", - "\n", - " return X\n", - "\n", - "step=0.5\n", - "x = np.arange(0, 1, step)\n", - "y = np.arange(0, 1, step)\n", - "x, y = np.meshgrid(x, y)\n", - "target = SkrankeFunction(x, y)\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "poly_degree=3\n", - "X = create_X(x, y, poly_degree)\n", - "\n", - "X_train, X_test, t_train, t_test = train_test_split(X, target)" - ] - }, - { - "cell_type": "markdown", - "id": "1ac05bb6", - "metadata": {}, - "source": [ - "Now that we have our dataset ready for the regression, we can create\n", - "our regressor. Note that with the seed parameter, we can make sure our\n", - "results stay the same every time we run the neural network. For\n", - "inititialization, we simply specify the dimensions (we wish the amount\n", - "of input nodes to be equal to the datapoints, and the output to\n", - "predict one value)." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "0f857604", - "metadata": {}, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "eeff4315", - "metadata": {}, - "source": [ - "We then fit our model with our training data using the scheduler of our choice." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "46246810", - "metadata": {}, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Constant(eta=1e-3)\n", - "scores = linear_regression.fit(X_train, t_train, scheduler)" - ] - }, - { - "cell_type": "markdown", - "id": "8c6f9954", - "metadata": {}, - "source": [ - "Due to the progress bar we can see the MSE (train_error) throughout\n", - "the FFNN's training. Note that the fit() function has some optional\n", - "parameters with defualt arguments. For example, the regularization\n", - "hyperparameter can be left ignored if not needed, and equally the FFNN\n", - "will by default run for 100 epochs. These can easily be changed, such\n", - "as for example:" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "2661939c", - "metadata": {}, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "74c5624c", - "metadata": {}, - "source": [ - "We see that given more epochs to train on, the regressor reaches a lower MSE.\n", - "\n", - "Let us then switch to a binary classification. We use a binary\n", - "classification dataset, and follow a similar setup to the regression\n", - "case." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "4b8eb115", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.preprocessing import MinMaxScaler\n", - "\n", - "wisconsin = load_breast_cancer()\n", - "X = wisconsin.data\n", - "target = wisconsin.target\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "X_train, X_val, t_train, t_val = train_test_split(X, target)\n", - "\n", - "scaler = MinMaxScaler()\n", - "scaler.fit(X_train)\n", - "X_train = scaler.transform(X_train)\n", - "X_val = scaler.transform(X_val)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "2c0f92bd", - "metadata": {}, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "49201ae4", - "metadata": {}, - "source": [ - "We will now make use of our validation data by passing it into our fit function as a keyword argument" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "55b5e426", - "metadata": {}, - "outputs": [], - "source": [ - "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", - "scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "b51762fb", - "metadata": {}, - "source": [ - "Finally, we will create a neural network with 2 hidden layers with activation functions." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "6b59e27d", - "metadata": {}, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 1\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "72c87921", - "metadata": {}, - "outputs": [], - "source": [ - "neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "ed40d7d2", - "metadata": {}, - "source": [ - "### Multiclass classification\n", - "\n", - "Finally, we will demonstrate the use case of multiclass classification\n", - "using our FFNN with the famous MNIST dataset, which contain images of\n", - "digits between the range of 0 to 9." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "315ef3fe", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.datasets import load_digits\n", - "\n", - "def onehot(target: np.ndarray):\n", - " onehot = np.zeros((target.size, target.max() + 1))\n", - " onehot[np.arange(target.size), target] = 1\n", - " return onehot\n", - "\n", - "digits = load_digits()\n", - "\n", - "X = digits.data\n", - "target = digits.target\n", - "target = onehot(target)\n", - "\n", - "input_nodes = 64\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 10\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)\n", - "\n", - "multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = multiclass.fit(X, target, scheduler, epochs=1000)" + "Make plots of the confusion matrix, the ROC curve and the cumulative\n", + "gain curve for this (or other) multiclass data set." ] } ], @@ -1507,7 +639,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.10" + "version": "3.9.15" } }, "nbformat": 4, diff --git a/doc/LectureNotes/_build/.doctrees/environment.pickle b/doc/LectureNotes/_build/.doctrees/environment.pickle index fd4f70d25..8cbf31117 100644 Binary files a/doc/LectureNotes/_build/.doctrees/environment.pickle and b/doc/LectureNotes/_build/.doctrees/environment.pickle differ diff --git a/doc/LectureNotes/_build/.doctrees/exercisesweek43.doctree b/doc/LectureNotes/_build/.doctrees/exercisesweek43.doctree new file mode 100644 index 000000000..793ebcfad Binary files /dev/null and b/doc/LectureNotes/_build/.doctrees/exercisesweek43.doctree differ diff --git a/doc/LectureNotes/_build/.doctrees/intro.doctree b/doc/LectureNotes/_build/.doctrees/intro.doctree index f3aa1e84d..e75534081 100644 Binary files a/doc/LectureNotes/_build/.doctrees/intro.doctree and b/doc/LectureNotes/_build/.doctrees/intro.doctree differ diff --git a/doc/LectureNotes/_build/.doctrees/week43.doctree b/doc/LectureNotes/_build/.doctrees/week43.doctree new file mode 100644 index 000000000..66ccdcbeb Binary files /dev/null and b/doc/LectureNotes/_build/.doctrees/week43.doctree differ diff --git a/doc/LectureNotes/_build/html/_sources/exercisesweek43.ipynb b/doc/LectureNotes/_build/html/_sources/exercisesweek43.ipynb new file mode 100644 index 000000000..f80e8787a --- /dev/null +++ b/doc/LectureNotes/_build/html/_sources/exercisesweek43.ipynb @@ -0,0 +1,647 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "860d70d8", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "119c0988", + "metadata": { + "editable": true + }, + "source": [ + "# Exercises week 43 \n", + "**October 20-24, 2025**\n", + "\n", + "Date: **Deadline Friday October 24 at midnight**" + ] + }, + { + "cell_type": "markdown", + "id": "909887eb", + "metadata": { + "editable": true + }, + "source": [ + "# Overarching aims of the exercises for week 43\n", + "\n", + "The aim of the exercises this week is to gain some confidence with\n", + "ways to visualize the results of a classification problem. We will\n", + "target three ways of setting up the analysis. The first and simplest\n", + "one is the\n", + "1. so-called confusion matrix. The next one is the so-called\n", + "\n", + "2. ROC curve. Finally we have the\n", + "\n", + "3. Cumulative gain curve.\n", + "\n", + "We will use Logistic Regression as method for the classification in\n", + "this exercise. You can compare these results with those obtained with\n", + "your neural network code from project 2 without a hidden layer.\n", + "\n", + "In these exercises we will use binary and multi-class data sets\n", + "(the Iris data set from week 41).\n", + "\n", + "The underlying mathematics is described here." + ] + }, + { + "cell_type": "markdown", + "id": "1e1cb4fb", + "metadata": { + "editable": true + }, + "source": [ + "### Confusion Matrix\n", + "\n", + "A **confusion matrix** summarizes a classifier’s performance by\n", + "tabulating predictions versus true labels. For binary classification,\n", + "it is a $2\\times2$ table whose entries are counts of outcomes:" + ] + }, + { + "cell_type": "markdown", + "id": "7b090385", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{array}{l|cc} & \\text{Predicted Positive} & \\text{Predicted Negative} \\\\ \\hline \\text{Actual Positive} & TP & FN \\\\ \\text{Actual Negative} & FP & TN \\end{array}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1e14904b", + "metadata": { + "editable": true + }, + "source": [ + "Here TP (true positives) is the number of cases correctly predicted as\n", + "positive, FP (false positives) is the number incorrectly predicted as\n", + "positive, TN (true negatives) is correctly predicted negative, and FN\n", + "(false negatives) is incorrectly predicted negative . In other words,\n", + "“positive” means class 1 and “negative” means class 0; for example, TP\n", + "occurs when the prediction and actual are both positive. Formally:" + ] + }, + { + "cell_type": "markdown", + "id": "e93ea290", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\text{TPR} = \\frac{\\text{TP}}{\\text{TP} + \\text{FN}}, \\quad \\text{FPR} = \\frac{\\text{FP}}{\\text{FP} + \\text{TN}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c80bea5b", + "metadata": { + "editable": true + }, + "source": [ + "where TPR and FPR are the true and false positive rates defined below.\n", + "\n", + "In multiclass classification with $K$ classes, the confusion matrix\n", + "generalizes to a $K\\times K$ table. Entry $N_{ij}$ in the table is\n", + "the count of instances whose true class is $i$ and whose predicted\n", + "class is $j$. For example, a three-class confusion matrix can be written\n", + "as:" + ] + }, + { + "cell_type": "markdown", + "id": "a0f68f5f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{array}{c|ccc} & \\text{Pred Class 1} & \\text{Pred Class 2} & \\text{Pred Class 3} \\\\ \\hline \\text{Act Class 1} & N_{11} & N_{12} & N_{13} \\\\ \\text{Act Class 2} & N_{21} & N_{22} & N_{23} \\\\ \\text{Act Class 3} & N_{31} & N_{32} & N_{33} \\end{array}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "869669b2", + "metadata": { + "editable": true + }, + "source": [ + "Here the diagonal entries $N_{ii}$ are the true positives for each\n", + "class, and off-diagonal entries are misclassifications. This matrix\n", + "allows computation of per-class metrics: e.g. for class $i$,\n", + "$\\mathrm{TP}_i=N_{ii}$, $\\mathrm{FN}_i=\\sum_{j\\neq i}N_{ij}$,\n", + "$\\mathrm{FP}_i=\\sum_{j\\neq i}N_{ji}$, and $\\mathrm{TN}_i$ is the sum of\n", + "all remaining entries.\n", + "\n", + "As defined above, TPR and FPR come from the binary case. In binary\n", + "terms with $P$ actual positives and $N$ actual negatives, one has" + ] + }, + { + "cell_type": "markdown", + "id": "2abd82a7", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\text{TPR} = \\frac{TP}{P} = \\frac{TP}{TP+FN}, \\quad \\text{FPR} =\n", + "\\frac{FP}{N} = \\frac{FP}{FP+TN},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2f79325c", + "metadata": { + "editable": true + }, + "source": [ + "as used in standard confusion-matrix\n", + "formulations. These rates will be used in constructing ROC curves." + ] + }, + { + "cell_type": "markdown", + "id": "0ce65a47", + "metadata": { + "editable": true + }, + "source": [ + "### ROC Curve\n", + "\n", + "The Receiver Operating Characteristic (ROC) curve plots the trade-off\n", + "between true positives and false positives as a discrimination\n", + "threshold varies. Specifically, for a binary classifier that outputs\n", + "a score or probability, one varies the threshold $t$ for declaring\n", + "**positive**, and computes at each $t$ the true positive rate\n", + "$\\mathrm{TPR}(t)$ and false positive rate $\\mathrm{FPR}(t)$ using the\n", + "confusion matrix at that threshold. The ROC curve is then the graph\n", + "of TPR versus FPR. By definition," + ] + }, + { + "cell_type": "markdown", + "id": "d750fdff", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{TPR} = \\frac{TP}{TP+FN}, \\qquad \\mathrm{FPR} = \\frac{FP}{FP+TN},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "561bfb2c", + "metadata": { + "editable": true + }, + "source": [ + "where $TP,FP,TN,FN$ are counts determined by threshold $t$. A perfect\n", + "classifier would reach the point (FPR=0, TPR=1) at some threshold.\n", + "\n", + "Formally, the ROC curve is obtained by plotting\n", + "$(\\mathrm{FPR}(t),\\mathrm{TPR}(t))$ for all $t\\in[0,1]$ (or as $t$\n", + "sweeps through the sorted scores). The Area Under the ROC Curve (AUC)\n", + "quantifies the average performance over all thresholds. It can be\n", + "interpreted probabilistically: $\\mathrm{AUC} =\n", + "\\Pr\\bigl(s(X^+)>s(X^-)\\bigr)$, the probability that a random positive\n", + "instance $X^+$ receives a higher score $s$ than a random negative\n", + "instance $X^-$ . Equivalently, the AUC is the integral under the ROC\n", + "curve:" + ] + }, + { + "cell_type": "markdown", + "id": "5ca722fe", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{AUC} \\;=\\; \\int_{0}^{1} \\mathrm{TPR}(f)\\,df,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "30080a86", + "metadata": { + "editable": true + }, + "source": [ + "where $f$ ranges over FPR (or fraction of negatives). A model that guesses at random yields a diagonal ROC (AUC=0.5), whereas a perfect model yields AUC=1.0." + ] + }, + { + "cell_type": "markdown", + "id": "9e627156", + "metadata": { + "editable": true + }, + "source": [ + "### Cumulative Gain\n", + "\n", + "The cumulative gain curve (or gains chart) evaluates how many\n", + "positives are captured as one targets an increasing fraction of the\n", + "population, sorted by model confidence. To construct it, sort all\n", + "instances by decreasing predicted probability of the positive class.\n", + "Then, for the top $\\alpha$ fraction of instances, compute the fraction\n", + "of all actual positives that fall in this subset. In formula form, if\n", + "$P$ is the total number of positive instances and $P(\\alpha)$ is the\n", + "number of positives among the top $\\alpha$ of the data, the cumulative\n", + "gain at level $\\alpha$ is" + ] + }, + { + "cell_type": "markdown", + "id": "3e9132ef", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{Gain}(\\alpha) \\;=\\; \\frac{P(\\alpha)}{P}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "75be6f5c", + "metadata": { + "editable": true + }, + "source": [ + "For example, cutting off at the top 10% of predictions yields a gain\n", + "equal to (positives in top 10%) divided by (total positives) .\n", + "Plotting $\\mathrm{Gain}(\\alpha)$ versus $\\alpha$ (often in percent)\n", + "gives the gain curve. The baseline (random) curve is the diagonal\n", + "$\\mathrm{Gain}(\\alpha)=\\alpha$, while an ideal model has a steep climb\n", + "toward 1.\n", + "\n", + "A related measure is the {\\em lift}, often called the gain ratio. It is the ratio of the model’s capture rate to that of random selection. Equivalently," + ] + }, + { + "cell_type": "markdown", + "id": "e5525570", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{Lift}(\\alpha) \\;=\\; \\frac{\\mathrm{Gain}(\\alpha)}{\\alpha}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "18ff8dc2", + "metadata": { + "editable": true + }, + "source": [ + "A lift $>1$ indicates better-than-random targeting. In practice, gain\n", + "and lift charts (used e.g.\\ in marketing or imbalanced classification)\n", + "show how many positives can be “gained” by focusing on a fraction of\n", + "the population ." + ] + }, + { + "cell_type": "markdown", + "id": "c3d3fde8", + "metadata": { + "editable": true + }, + "source": [ + "### Other measures: Precision, Recall, and the F$_1$ Measure\n", + "\n", + "Precision and recall (sensitivity) quantify binary classification\n", + "accuracy in terms of positive predictions. They are defined from the\n", + "confusion matrix as:" + ] + }, + { + "cell_type": "markdown", + "id": "f1f14c8e", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\text{Precision} = \\frac{TP}{TP + FP}, \\qquad \\text{Recall} = \\frac{TP}{TP + FN}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "422cc743", + "metadata": { + "editable": true + }, + "source": [ + "Precision is the fraction of predicted positives that are correct, and\n", + "recall is the fraction of actual positives that are correctly\n", + "identified . A high-precision classifier makes few false-positive\n", + "errors, while a high-recall classifier makes few false-negative\n", + "errors.\n", + "\n", + "The F$_1$ score (balanced F-measure) combines precision and recall into a single metric via their harmonic mean. The usual formula is:" + ] + }, + { + "cell_type": "markdown", + "id": "621a2e8b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "F_1 =2\\frac{\\text{Precision}\\times\\text{Recall}}{\\text{Precision} + \\text{Recall}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "62eee54a", + "metadata": { + "editable": true + }, + "source": [ + "This can be shown to equal" + ] + }, + { + "cell_type": "markdown", + "id": "7a6a2e7a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{2\\,TP}{2\\,TP + FP + FN}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b96c9ff4", + "metadata": { + "editable": true + }, + "source": [ + "The F$_1$ score ranges from 0 (worst) to 1 (best), and balances the\n", + "trade-off between precision and recall.\n", + "\n", + "For multi-class classification, one computes per-class\n", + "precision/recall/F$_1$ (treating each class as “positive” in a\n", + "one-vs-rest manner) and then averages. Common averaging methods are:\n", + "\n", + "Micro-averaging: Sum all true positives, false positives, and false negatives across classes, then compute precision/recall/F$_1$ from these totals.\n", + "Macro-averaging: Compute the F$1$ score $F{1,i}$ for each class $i$ separately, then take the unweighted mean: $F_{1,\\mathrm{macro}} = \\frac{1}{K}\\sum_{i=1}^K F_{1,i}$ . This treats all classes equally regardless of size.\n", + "Weighted-averaging: Like macro-average, but weight each class’s $F_{1,i}$ by its support $n_i$ (true count): $F_{1,\\mathrm{weighted}} = \\frac{1}{N}\\sum_{i=1}^K n_i F_{1,i}$, where $N=\\sum_i n_i$. This accounts for class imbalance by giving more weight to larger classes .\n", + "\n", + "Each of these averages has different use-cases. Micro-average is\n", + "dominated by common classes, macro-average highlights performance on\n", + "rare classes, and weighted-average is a compromise. These formulas\n", + "and concepts allow rigorous evaluation of classifier performance in\n", + "both binary and multi-class settings." + ] + }, + { + "cell_type": "markdown", + "id": "9274bf3f", + "metadata": { + "editable": true + }, + "source": [ + "## Exercises\n", + "\n", + "Here is a simple code example which uses the Logistic regression machinery from **scikit-learn**.\n", + "At the end it sets up the confusion matrix and the ROC and cumulative gain curves.\n", + "Feel free to use these functionalities (we don't expect you to write your own code for say the confusion matrix)." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "be9ff0b9", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "# from sklearn.datasets import fill in the data set\n", + "from sklearn.linear_model import LogisticRegression\n", + "\n", + "# Load the data, fill inn\n", + "mydata.data = ?\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(mydata.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "# Logistic Regression\n", + "# define which type of problem, binary or multiclass\n", + "logreg = LogisticRegression(solver='lbfgs')\n", + "logreg.fit(X_train, y_train)\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import cross_validate\n", + "#Cross validation\n", + "accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score']\n", + "print(accuracy)\n", + "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", + "\n", + "import scikitplot as skplt\n", + "y_pred = logreg.predict(X_test)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "plt.show()\n", + "y_probas = logreg.predict_proba(X_test)\n", + "skplt.metrics.plot_roc(y_test, y_probas)\n", + "plt.show()\n", + "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "51760b3e", + "metadata": { + "editable": true + }, + "source": [ + "### Exercise a)\n", + "\n", + "Convince yourself about the mathematics for the confusion matrix, the ROC and the cumlative gain curves for both a binary and a multiclass classification problem." + ] + }, + { + "cell_type": "markdown", + "id": "c1d42f5f", + "metadata": { + "editable": true + }, + "source": [ + "### Exercise b)\n", + "\n", + "Use a binary classification data available from **scikit-learn**. As an example you can use\n", + "the MNIST data set and just specialize to two numbers. To do so you can use the following code lines" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "d20bb8be", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_digits\n", + "digits = load_digits(n_class=2) # Load only two classes, e.g., 0 and 1\n", + "X, y = digits.data, digits.target" + ] + }, + { + "cell_type": "markdown", + "id": "828ea1cd", + "metadata": { + "editable": true + }, + "source": [ + "Alternatively, you can use the _make$\\_$classification_\n", + "functionality. This function generates a random $n$-class classification\n", + "dataset, which can be configured for binary classification by setting\n", + "n_classes=2. You can also control the number of samples, features,\n", + "informative features, redundant features, and more." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "d271f0ba", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "from sklearn.datasets import make_classification\n", + "X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, n_redundant=5, n_classes=2, random_state=42)" + ] + }, + { + "cell_type": "markdown", + "id": "0068b032", + "metadata": { + "editable": true + }, + "source": [ + "You can use this option for the multiclass case as well, see the next exercise.\n", + "If you prefer to study other binary classification datasets, feel free\n", + "to replace the above suggestions with your own dataset.\n", + "\n", + "Make plots of the confusion matrix, the ROC curve and the cumulative gain curve." + ] + }, + { + "cell_type": "markdown", + "id": "c45f5b41", + "metadata": { + "editable": true + }, + "source": [ + "### Exercise c) week 43\n", + "\n", + "As a multiclass problem, we will use the Iris data set discussed in\n", + "the exercises from weeks 41 and 42. This is a three-class data set and\n", + "you can set it up using **scikit-learn**," + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "3b045d56", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_iris\n", + "iris = load_iris()\n", + "X = iris.data # Features\n", + "y = iris.target # Target labels" + ] + }, + { + "cell_type": "markdown", + "id": "14cc859c", + "metadata": { + "editable": true + }, + "source": [ + "Make plots of the confusion matrix, the ROC curve and the cumulative\n", + "gain curve for this (or other) multiclass data set." + ] + } + ], + "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.15" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/_build/html/_sources/week43.ipynb b/doc/LectureNotes/_build/html/_sources/week43.ipynb new file mode 100644 index 000000000..b190102b6 --- /dev/null +++ b/doc/LectureNotes/_build/html/_sources/week43.ipynb @@ -0,0 +1,5950 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "5e07edf2", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "44b465a0", + "metadata": { + "editable": true + }, + "source": [ + "# Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway\n", + "\n", + "Date: **October 20, 2025**" + ] + }, + { + "cell_type": "markdown", + "id": "9d7bd8c9", + "metadata": { + "editable": true + }, + "source": [ + "## Plans for week 43\n", + "\n", + "**Material for the lecture on Monday October 20, 2025.**\n", + "\n", + "1. Reminder from last week, see also lecture notes from week 42 at as well as those from week 41, see see . \n", + "\n", + "2. Building our own Feed-forward Neural Network.\n", + "\n", + "3. Coding examples using Tensorflow/Keras and Pytorch examples. The Pytorch examples are adapted from Rashcka's text, see chapters 11-13.. \n", + "\n", + "4. Start discussions on how to use neural networks for solving differential equations (ordinary and partial ones). This topic continues next week as well.\n", + "\n", + "5. Video of lecture at \n", + "\n", + "6. Whiteboard notes at " + ] + }, + { + "cell_type": "markdown", + "id": "c50cff0f", + "metadata": { + "editable": true + }, + "source": [ + "## Exercises and lab session week 43\n", + "**Lab sessions on Tuesday and Wednesday.**\n", + "\n", + "1. Work on writing your own neural network code and discussions of project 2. If you didn't get time to do the exercises from the two last weeks, we recommend doing so as these exercises give you the basic elements of a neural network code.\n", + "\n", + "2. The exercises this week are tailored to the optional part of project 2, and deal with studying ways to display results from classification problems" + ] + }, + { + "cell_type": "markdown", + "id": "fe8d32ed", + "metadata": { + "editable": true + }, + "source": [ + "## Using Automatic differentiation\n", + "\n", + "In our discussions of ordinary differential equations and neural network codes\n", + "we will also study the usage of Autograd, see for example in computing gradients for deep learning. For the documentation of Autograd and examples see the Autograd documentation at and the lecture slides from week 41, see ." + ] + }, + { + "cell_type": "markdown", + "id": "99999ab4", + "metadata": { + "editable": true + }, + "source": [ + "## Back propagation and automatic differentiation\n", + "\n", + "For more details on the back propagation algorithm and automatic differentiation see\n", + "1. \n", + "\n", + "2. \n", + "\n", + "3. Slides 12-44 at " + ] + }, + { + "cell_type": "markdown", + "id": "b4489372", + "metadata": { + "editable": true + }, + "source": [ + "## Lecture Monday October 20" + ] + }, + { + "cell_type": "markdown", + "id": "f7435e4a", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations\n", + "This is a reminder from last week.\n", + "\n", + "**The architecture (our model).**\n", + "\n", + "1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)\n", + "\n", + "2. Define the number of hidden layers and hidden nodes\n", + "\n", + "3. Define activation functions for hidden layers and output layers\n", + "\n", + "4. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates\n", + "\n", + "5. Define cost function and possible regularization terms with hyperparameters\n", + "\n", + "6. Initialize weights and biases\n", + "\n", + "7. Fix number of iterations for the feed forward part and back propagation part" + ] + }, + { + "cell_type": "markdown", + "id": "e2561576", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the back propagation algorithm, part 1\n", + "\n", + "Let us write this out in the form of an algorithm.\n", + "\n", + "**First**, we set up the input data $\\boldsymbol{x}$ and the activations\n", + "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", + "the pertinent outputs $\\boldsymbol{a}^1$.\n", + "\n", + "**Secondly**, we perform then the feed forward till we reach the output\n", + "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", + "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", + "$l=1,2,3,\\dots,L$.\n", + "\n", + "**Notation**: The first hidden layer has $l=1$ as label and the final output layer has $l=L$." + ] + }, + { + "cell_type": "markdown", + "id": "39ed46ed", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the back propagation algorithm, part 2\n", + "\n", + "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" + ] + }, + { + "cell_type": "markdown", + "id": "776b50ac", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j^L = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b0ad385d", + "metadata": { + "editable": true + }, + "source": [ + "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,1$ as" + ] + }, + { + "cell_type": "markdown", + "id": "bb592830", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "41259526", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the Back propagation algorithm, part 3\n", + "\n", + "Finally, we update the weights and the biases using gradient descent\n", + "for each $l=L-1,L-2,\\dots,1$ (the first hidden layer) and update the weights and biases\n", + "according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "47eaff91", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "05b74533", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6edb8648", + "metadata": { + "editable": true + }, + "source": [ + "with $\\eta$ being the learning rate." + ] + }, + { + "cell_type": "markdown", + "id": "a663fc08", + "metadata": { + "editable": true + }, + "source": [ + "## Updating the gradients\n", + "\n", + "With the back propagate error for each $l=L-1,L-2,\\dots,1$ as" + ] + }, + { + "cell_type": "markdown", + "id": "479150e0", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "41b9b1ea", + "metadata": { + "editable": true + }, + "source": [ + "we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,1$ and update the weights and biases according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "590c403a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3db8cbb4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a204182a", + "metadata": { + "editable": true + }, + "source": [ + "## Activation functions\n", + "\n", + "A property that characterizes a neural network, other than its\n", + "connectivity, is the choice of activation function(s). The following\n", + "restrictions are imposed on an activation function for an FFNN to\n", + "fulfill the universal approximation theorem\n", + "\n", + " * Non-constant\n", + "\n", + " * Bounded\n", + "\n", + " * Monotonically-increasing\n", + "\n", + " * Continuous" + ] + }, + { + "cell_type": "markdown", + "id": "4fe58cce", + "metadata": { + "editable": true + }, + "source": [ + "### Activation functions, examples\n", + "\n", + "Typical examples are the logistic *Sigmoid*" + ] + }, + { + "cell_type": "markdown", + "id": "a14f6d08", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sigma(x) = \\frac{1}{1 + e^{-x}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4c290410", + "metadata": { + "editable": true + }, + "source": [ + "and the *hyperbolic tangent* function" + ] + }, + { + "cell_type": "markdown", + "id": "ca1ac514", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sigma(x) = \\tanh(x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b9bcfab3", + "metadata": { + "editable": true + }, + "source": [ + "## The RELU function family\n", + "\n", + "The ReLU activation function suffers from a problem known as the dying\n", + "ReLUs: during training, some neurons effectively die, meaning they\n", + "stop outputting anything other than 0.\n", + "\n", + "In some cases, you may find that half of your network’s neurons are\n", + "dead, especially if you used a large learning rate. During training,\n", + "if a neuron’s weights get updated such that the weighted sum of the\n", + "neuron’s inputs is negative, it will start outputting 0. When this\n", + "happen, the neuron is unlikely to come back to life since the gradient\n", + "of the ReLU function is 0 when its input is negative." + ] + }, + { + "cell_type": "markdown", + "id": "2fdf56f7", + "metadata": { + "editable": true + }, + "source": [ + "## ELU function\n", + "\n", + "To solve this problem, nowadays practitioners use a variant of the\n", + "ReLU function, such as the leaky ReLU discussed above or the so-called\n", + "exponential linear unit (ELU) function" + ] + }, + { + "cell_type": "markdown", + "id": "14bf193c", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "df29068f", + "metadata": { + "editable": true + }, + "source": [ + "## Which activation function should we use?\n", + "\n", + "In general it seems that the ELU activation function is better than\n", + "the leaky ReLU function (and its variants), which is better than\n", + "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", + "than the logistic function.\n", + "\n", + "If runtime performance is an issue, then you may opt for the leaky\n", + "ReLU function over the ELU function If you don’t want to tweak yet\n", + "another hyperparameter, you may just use the default $\\alpha$ of\n", + "$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and\n", + "computing power, you can use cross-validation or bootstrap to evaluate\n", + "other activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "2fb5a29e", + "metadata": { + "editable": true + }, + "source": [ + "## More on activation functions, output layers\n", + "\n", + "In most cases you can use the ReLU activation function in the hidden\n", + "layers (or one of its variants).\n", + "\n", + "It is a bit faster to compute than other activation functions, and the\n", + "gradient descent optimization does in general not get stuck.\n", + "\n", + "**For the output layer:**\n", + "\n", + "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", + "\n", + "* For regression tasks, you can simply use no activation function at all." + ] + }, + { + "cell_type": "markdown", + "id": "bab79791", + "metadata": { + "editable": true + }, + "source": [ + "## Building neural networks in Tensorflow and Keras\n", + "\n", + "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", + "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", + "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", + "\n", + "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", + "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", + "NumPy arrays." + ] + }, + { + "cell_type": "markdown", + "id": "cc32bc9d", + "metadata": { + "editable": true + }, + "source": [ + "## Tensorflow\n", + "\n", + "Tensorflow is an open source library machine learning library\n", + "developed by the Google Brain team for internal use. It was released\n", + "under the Apache 2.0 open source license in November 9, 2015.\n", + "\n", + "Tensorflow is a computational framework that allows you to construct\n", + "machine learning models at different levels of abstraction, from\n", + "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", + "that Tensorflow is built upon. The higher levels of abstraction are\n", + "simpler to use, but less flexible, and our choice of implementation\n", + "should reflect the problems we are trying to solve.\n", + "\n", + "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", + "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", + "to represent your model, and then create a Tensorflow *session* to run the graph.\n", + "\n", + "In this guide we will analyze the same data as we did in our NumPy and\n", + "scikit-learn tutorial, gathered from the MNIST database of images. We\n", + "will give an introduction to the lower level Python Application\n", + "Program Interfaces (APIs), and see how we use them to build our graph.\n", + "Then we will build (effectively) the same graph in Keras, to see just\n", + "how simple solving a machine learning problem can be.\n", + "\n", + "To install tensorflow on Unix/Linux systems, use pip as" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "deb81088", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "pip3 install tensorflow" + ] + }, + { + "cell_type": "markdown", + "id": "979148b0", + "metadata": { + "editable": true + }, + "source": [ + "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", + "(current release of CPU-only TensorFlow)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "ad63b8d9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "conda create -n tf tensorflow\n", + "conda activate tf" + ] + }, + { + "cell_type": "markdown", + "id": "1417a40e", + "metadata": { + "editable": true + }, + "source": [ + "To install the current release of GPU TensorFlow" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "d56acb3a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "conda create -n tf-gpu tensorflow-gpu\n", + "conda activate tf-gpu" + ] + }, + { + "cell_type": "markdown", + "id": "6a163d27", + "metadata": { + "editable": true + }, + "source": [ + "## Using Keras\n", + "\n", + "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", + "that supports Tensorflow, CTNK and Theano as backends. \n", + "If you have Anaconda installed you may run the following command" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "9ee390a8", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "conda install keras" + ] + }, + { + "cell_type": "markdown", + "id": "528ea3d5", + "metadata": { + "editable": true + }, + "source": [ + "You can look up the [instructions here](https://keras.io/) for more information.\n", + "\n", + "We will to a large extent use **keras** in this course." + ] + }, + { + "cell_type": "markdown", + "id": "32178225", + "metadata": { + "editable": true + }, + "source": [ + "## Collect and pre-process data\n", + "\n", + "Let us look again at the MINST data set." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "e37f86e4", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import tensorflow as tf\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "06a7c3bd", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", + "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", + "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", + "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", + "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# one-hot representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "358b46c5", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "epochs = 100\n", + "batch_size = 100\n", + "n_neurons_layer1 = 100\n", + "n_neurons_layer2 = 50\n", + "n_categories = 10\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)\n", + "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", + " model = Sequential()\n", + " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(Dense(n_categories, activation='softmax'))\n", + " \n", + " sgd = optimizers.SGD(learning_rate=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "5a0445fb", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", + " eta=eta, lmbd=lmbd)\n", + " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = DNN.evaluate(X_test, Y_test)\n", + " \n", + " DNN_keras[i][j] = DNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "f301c7cf", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " DNN = DNN_keras[i][j]\n", + "\n", + " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "610c95e1", + "metadata": { + "editable": true + }, + "source": [ + "## Using Pytorch with the full MNIST data set" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "d0f3ad9a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "import torchvision\n", + "import torchvision.transforms as transforms\n", + "\n", + "# Device configuration: use GPU if available\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# MNIST dataset (downloads if not already present)\n", + "transform = transforms.Compose([\n", + " transforms.ToTensor(),\n", + " transforms.Normalize((0.5,), (0.5,)) # normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range)\n", + "])\n", + "train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)\n", + "test_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)\n", + "\n", + "train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)\n", + "\n", + "\n", + "class NeuralNet(nn.Module):\n", + " def __init__(self):\n", + " super(NeuralNet, self).__init__()\n", + " self.fc1 = nn.Linear(28*28, 100) # first hidden layer (784 -> 100)\n", + " self.fc2 = nn.Linear(100, 100) # second hidden layer (100 -> 100)\n", + " self.fc3 = nn.Linear(100, 10) # output layer (100 -> 10 classes)\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1) # flatten images into vectors of size 784\n", + " x = torch.relu(self.fc1(x)) # hidden layer 1 + ReLU activation\n", + " x = torch.relu(self.fc2(x)) # hidden layer 2 + ReLU activation\n", + " x = self.fc3(x) # output layer (logits for 10 classes)\n", + " return x\n", + "\n", + "model = NeuralNet().to(device)\n", + "\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)\n", + "\n", + "num_epochs = 10\n", + "for epoch in range(num_epochs):\n", + " model.train() # set model to training mode\n", + " running_loss = 0.0\n", + " for images, labels in train_loader:\n", + " # Move data to device (GPU if available, else CPU)\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad() # reset gradients to zero\n", + " outputs = model(images) # forward pass: compute predictions\n", + " loss = criterion(outputs, labels) # compute cross-entropy loss\n", + " loss.backward() # backpropagate to compute gradients\n", + " optimizer.step() # update weights using SGD step \n", + "\n", + " running_loss += loss.item()\n", + " # Compute average loss over all batches in this epoch\n", + " avg_loss = running_loss / len(train_loader)\n", + " print(f\"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}\")\n", + "\n", + "#Evaluation on the Test Set\n", + "\n", + "\n", + "\n", + "model.eval() # set model to evaluation mode \n", + "correct = 0\n", + "total = 0\n", + "with torch.no_grad(): # disable gradient calculation for evaluation \n", + " for images, labels in test_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + " _, predicted = torch.max(outputs, dim=1) # class with highest score\n", + " total += labels.size(0)\n", + " correct += (predicted == labels).sum().item()\n", + "\n", + "accuracy = 100 * correct / total\n", + "print(f\"Test Accuracy: {accuracy:.2f}%\")" + ] + }, + { + "cell_type": "markdown", + "id": "aad687aa", + "metadata": { + "editable": true + }, + "source": [ + "## And a similar example using Tensorflow with Keras" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "b6c4fad4", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "import tensorflow as tf\n", + "from tensorflow import keras\n", + "from tensorflow.keras import layers, regularizers\n", + "\n", + "# Check for GPU (TensorFlow will use it automatically if available)\n", + "gpus = tf.config.list_physical_devices('GPU')\n", + "print(f\"GPUs available: {gpus}\")\n", + "\n", + "# 1) Load and preprocess MNIST\n", + "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n", + "# Normalize to [0, 1]\n", + "x_train = (x_train.astype(\"float32\") / 255.0)\n", + "x_test = (x_test.astype(\"float32\") / 255.0)\n", + "\n", + "# 2) Build the model: 784 -> 100 -> 100 -> 10\n", + "l2_reg = 1e-4 # L2 regularization strength\n", + "\n", + "model = keras.Sequential([\n", + " layers.Input(shape=(28, 28)),\n", + " layers.Flatten(),\n", + " layers.Dense(100, activation=\"relu\",\n", + " kernel_regularizer=regularizers.l2(l2_reg)),\n", + " layers.Dense(100, activation=\"relu\",\n", + " kernel_regularizer=regularizers.l2(l2_reg)),\n", + " layers.Dense(10, activation=\"softmax\") # output probabilities for 10 classes\n", + "])\n", + "\n", + "# 3) Compile with SGD + weight decay via L2 regularizers\n", + "model.compile(\n", + " optimizer=keras.optimizers.SGD(learning_rate=0.01),\n", + " loss=\"sparse_categorical_crossentropy\",\n", + " metrics=[\"accuracy\"],\n", + ")\n", + "\n", + "model.summary()\n", + "\n", + "# 4) Train\n", + "history = model.fit(\n", + " x_train, y_train,\n", + " epochs=10,\n", + " batch_size=64,\n", + " validation_split=0.1, # optional: monitor validation during training\n", + " verbose=1\n", + ")\n", + "\n", + "# 5) Evaluate on test set\n", + "test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)\n", + "print(f\"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "73162fbb", + "metadata": { + "editable": true + }, + "source": [ + "## Building our own neural network code\n", + "\n", + "Here we present a flexible object oriented codebase\n", + "for a feed forward neural network, along with a demonstration of how\n", + "to use it. Before we get into the details of the neural network, we\n", + "will first present some implementations of various schedulers, cost\n", + "functions and activation functions that can be used together with the\n", + "neural network.\n", + "\n", + "The codes here were developed by Eric Reber and Gregor Kajda during spring 2023." + ] + }, + { + "cell_type": "markdown", + "id": "86f36041", + "metadata": { + "editable": true + }, + "source": [ + "### Learning rate methods\n", + "\n", + "The code below shows object oriented implementations of the Constant,\n", + "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", + "of the classes belong to the shared abstract Scheduler class, and\n", + "share the update_change() and reset() methods allowing for any of the\n", + "schedulers to be seamlessly used during the training stage, as will\n", + "later be shown in the fit() method of the neural\n", + "network. Update_change() only has one parameter, the gradient\n", + "($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted\n", + "from the weights. The reset() function takes no parameters, and resets\n", + "the desired variables. For Constant and Momentum, reset does nothing." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "bcbec449", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "\n", + "class Scheduler:\n", + " \"\"\"\n", + " Abstract class for Schedulers\n", + " \"\"\"\n", + "\n", + " def __init__(self, eta):\n", + " self.eta = eta\n", + "\n", + " # should be overwritten\n", + " def update_change(self, gradient):\n", + " raise NotImplementedError\n", + "\n", + " # overwritten if needed\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Constant(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + "\n", + " def update_change(self, gradient):\n", + " return self.eta * gradient\n", + " \n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Momentum(Scheduler):\n", + " def __init__(self, eta: float, momentum: float):\n", + " super().__init__(eta)\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " self.change = self.momentum * self.change + self.eta * gradient\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Adagrad(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " return self.eta * gradient * G_t_inverse\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class AdagradMomentum(Scheduler):\n", + " def __init__(self, eta, momentum):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class RMS_prop(Scheduler):\n", + " def __init__(self, eta, rho):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.second = 0.0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", + " return self.eta * gradient / (np.sqrt(self.second + delta))\n", + "\n", + " def reset(self):\n", + " self.second = 0.0\n", + "\n", + "\n", + "class Adam(Scheduler):\n", + " def __init__(self, eta, rho, rho2):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.rho2 = rho2\n", + " self.moment = 0\n", + " self.second = 0\n", + " self.n_epochs = 1\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", + " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", + "\n", + " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", + " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", + "\n", + " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", + "\n", + " def reset(self):\n", + " self.n_epochs += 1\n", + " self.moment = 0\n", + " self.second = 0" + ] + }, + { + "cell_type": "markdown", + "id": "961989d9", + "metadata": { + "editable": true + }, + "source": [ + "### Usage of the above learning rate schedulers\n", + "\n", + "To initalize a scheduler, simply create the object and pass in the\n", + "necessary parameters such as the learning rate and the momentum as\n", + "shown below. As the Scheduler class is an abstract class it should not\n", + "called directly, and will raise an error upon usage." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "1e9fbe0f", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" + ] + }, + { + "cell_type": "markdown", + "id": "b5adb1b4", + "metadata": { + "editable": true + }, + "source": [ + "Here is a small example for how a segment of code using schedulers\n", + "could look. Switching out the schedulers is simple." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "dc4f4d28", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "weights = np.ones((3,3))\n", + "print(f\"Before scheduler:\\n{weights=}\")\n", + "\n", + "epochs = 10\n", + "for e in range(epochs):\n", + " gradient = np.random.rand(3, 3)\n", + " change = adam_scheduler.update_change(gradient)\n", + " weights = weights - change\n", + " adam_scheduler.reset()\n", + "\n", + "print(f\"\\nAfter scheduler:\\n{weights=}\")" + ] + }, + { + "cell_type": "markdown", + "id": "8964d118", + "metadata": { + "editable": true + }, + "source": [ + "### Cost functions\n", + "\n", + "Here we discuss cost functions that can be used when creating the\n", + "neural network. Every cost function takes the target vector as its\n", + "parameter, and returns a function valued only at $x$ such that it may\n", + "easily be differentiated." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "3a8470bd", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "\n", + "def CostOLS(target):\n", + " \n", + " def func(X):\n", + " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostLogReg(target):\n", + "\n", + " def func(X):\n", + " \n", + " return -(1.0 / target.shape[0]) * np.sum(\n", + " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", + " )\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostCrossEntropy(target):\n", + " \n", + " def func(X):\n", + " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", + "\n", + " return func" + ] + }, + { + "cell_type": "markdown", + "id": "ab4daf8f", + "metadata": { + "editable": true + }, + "source": [ + "Below we give a short example of how these cost function may be used\n", + "to obtain results if you wish to test them out on your own using\n", + "AutoGrad's automatics differentiation." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "cf8922ac", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from autograd import grad\n", + "\n", + "target = np.array([[1, 2, 3]]).T\n", + "a = np.array([[4, 5, 6]]).T\n", + "\n", + "cost_func = CostCrossEntropy\n", + "cost_func_derivative = grad(cost_func(target))\n", + "\n", + "valued_at_a = cost_func_derivative(a)\n", + "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" + ] + }, + { + "cell_type": "markdown", + "id": "fab332c4", + "metadata": { + "editable": true + }, + "source": [ + "### Activation functions\n", + "\n", + "Finally, before we look at the neural network, we will look at the\n", + "activation functions which can be specified between the hidden layers\n", + "and as the output function. Each function can be valued for any given\n", + "vector or matrix X, and can be differentiated via derivate()." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "5ab56013", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import elementwise_grad\n", + "\n", + "def identity(X):\n", + " return X\n", + "\n", + "\n", + "def sigmoid(X):\n", + " try:\n", + " return 1.0 / (1 + np.exp(-X))\n", + " except FloatingPointError:\n", + " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", + "\n", + "\n", + "def softmax(X):\n", + " X = X - np.max(X, axis=-1, keepdims=True)\n", + " delta = 10e-10\n", + " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", + "\n", + "\n", + "def RELU(X):\n", + " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", + "\n", + "\n", + "def LRELU(X):\n", + " delta = 10e-4\n", + " return np.where(X > np.zeros(X.shape), X, delta * X)\n", + "\n", + "\n", + "def derivate(func):\n", + " if func.__name__ == \"RELU\":\n", + "\n", + " def func(X):\n", + " return np.where(X > 0, 1, 0)\n", + "\n", + " return func\n", + "\n", + " elif func.__name__ == \"LRELU\":\n", + "\n", + " def func(X):\n", + " delta = 10e-4\n", + " return np.where(X > 0, 1, delta)\n", + "\n", + " return func\n", + "\n", + " else:\n", + " return elementwise_grad(func)" + ] + }, + { + "cell_type": "markdown", + "id": "969612c3", + "metadata": { + "editable": true + }, + "source": [ + "Below follows a short demonstration of how to use an activation\n", + "function. The derivative of the activation function will be important\n", + "when calculating the output delta term during backpropagation. Note\n", + "that derivate() can also be used for cost functions for a more\n", + "generalized approach." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "313878c6", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "z = np.array([[4, 5, 6]]).T\n", + "print(f\"Input to activation function:\\n{z}\")\n", + "\n", + "act_func = sigmoid\n", + "a = act_func(z)\n", + "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", + "\n", + "act_func_derivative = derivate(act_func)\n", + "valued_at_z = act_func_derivative(a)\n", + "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" + ] + }, + { + "cell_type": "markdown", + "id": "095347a2", + "metadata": { + "editable": true + }, + "source": [ + "### The Neural Network\n", + "\n", + "Now that we have gotten a good understanding of the implementation of\n", + "some important components, we can take a look at an object oriented\n", + "implementation of a feed forward neural network. The feed forward\n", + "neural network has been implemented as a class named FFNN, which can\n", + "be initiated as a regressor or classifier dependant on the choice of\n", + "cost function. The FFNN can have any number of input nodes, hidden\n", + "layers with any amount of hidden nodes, and any amount of output nodes\n", + "meaning it can perform multiclass classification as well as binary\n", + "classification and regression problems. Although there is a lot of\n", + "code present, it makes for an easy to use and generalizeable interface\n", + "for creating many types of neural networks as will be demonstrated\n", + "below." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "9ea2b0b7", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import math\n", + "import autograd.numpy as np\n", + "import sys\n", + "import warnings\n", + "from autograd import grad, elementwise_grad\n", + "from random import random, seed\n", + "from copy import deepcopy, copy\n", + "from typing import Tuple, Callable\n", + "from sklearn.utils import resample\n", + "\n", + "warnings.simplefilter(\"error\")\n", + "\n", + "\n", + "class FFNN:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Feed Forward Neural Network with interface enabling flexible design of a\n", + " nerual networks architecture and the specification of activation function\n", + " in the hidden layers and output layer respectively. This model can be used\n", + " for both regression and classification problems, depending on the output function.\n", + "\n", + " Attributes:\n", + " ------------\n", + " I dimensions (tuple[int]): A list of positive integers, which specifies the\n", + " number of nodes in each of the networks layers. The first integer in the array\n", + " defines the number of nodes in the input layer, the second integer defines number\n", + " of nodes in the first hidden layer and so on until the last number, which\n", + " specifies the number of nodes in the output layer.\n", + " II hidden_func (Callable): The activation function for the hidden layers\n", + " III output_func (Callable): The activation function for the output layer\n", + " IV cost_func (Callable): Our cost function\n", + " V seed (int): Sets random seed, makes results reproducible\n", + " \"\"\"\n", + "\n", + " def __init__(\n", + " self,\n", + " dimensions: tuple[int],\n", + " hidden_func: Callable = sigmoid,\n", + " output_func: Callable = lambda x: x,\n", + " cost_func: Callable = CostOLS,\n", + " seed: int = None,\n", + " ):\n", + " self.dimensions = dimensions\n", + " self.hidden_func = hidden_func\n", + " self.output_func = output_func\n", + " self.cost_func = cost_func\n", + " self.seed = seed\n", + " self.weights = list()\n", + " self.schedulers_weight = list()\n", + " self.schedulers_bias = list()\n", + " self.a_matrices = list()\n", + " self.z_matrices = list()\n", + " self.classification = None\n", + "\n", + " self.reset_weights()\n", + " self._set_classification()\n", + "\n", + " def fit(\n", + " self,\n", + " X: np.ndarray,\n", + " t: np.ndarray,\n", + " scheduler: Scheduler,\n", + " batches: int = 1,\n", + " epochs: int = 100,\n", + " lam: float = 0,\n", + " X_val: np.ndarray = None,\n", + " t_val: np.ndarray = None,\n", + " ):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " This function performs the training the neural network by performing the feedforward and backpropagation\n", + " algorithm to update the networks weights.\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray) : training data\n", + " II t (np.ndarray) : target data\n", + " III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)\n", + " IV scheduler_args (list[int]) : list of all arguments necessary for scheduler\n", + "\n", + " Optional Parameters:\n", + " ------------\n", + " V batches (int) : number of batches the datasets are split into, default equal to 1\n", + " VI epochs (int) : number of iterations used to train the network, default equal to 100\n", + " VII lam (float) : regularization hyperparameter lambda\n", + " VIII X_val (np.ndarray) : validation set\n", + " IX t_val (np.ndarray) : validation target set\n", + "\n", + " Returns:\n", + " ------------\n", + " I scores (dict) : A dictionary containing the performance metrics of the model.\n", + " The number of the metrics depends on the parameters passed to the fit-function.\n", + "\n", + " \"\"\"\n", + "\n", + " # setup \n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " val_set = False\n", + " if X_val is not None and t_val is not None:\n", + " val_set = True\n", + "\n", + " # creating arrays for score metrics\n", + " train_errors = np.empty(epochs)\n", + " train_errors.fill(np.nan)\n", + " val_errors = np.empty(epochs)\n", + " val_errors.fill(np.nan)\n", + "\n", + " train_accs = np.empty(epochs)\n", + " train_accs.fill(np.nan)\n", + " val_accs = np.empty(epochs)\n", + " val_accs.fill(np.nan)\n", + "\n", + " self.schedulers_weight = list()\n", + " self.schedulers_bias = list()\n", + "\n", + " batch_size = X.shape[0] // batches\n", + "\n", + " X, t = resample(X, t)\n", + "\n", + " # this function returns a function valued only at X\n", + " cost_function_train = self.cost_func(t)\n", + " if val_set:\n", + " cost_function_val = self.cost_func(t_val)\n", + "\n", + " # create schedulers for each weight matrix\n", + " for i in range(len(self.weights)):\n", + " self.schedulers_weight.append(copy(scheduler))\n", + " self.schedulers_bias.append(copy(scheduler))\n", + "\n", + " print(f\"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}\")\n", + "\n", + " try:\n", + " for e in range(epochs):\n", + " for i in range(batches):\n", + " # allows for minibatch gradient descent\n", + " if i == batches - 1:\n", + " # If the for loop has reached the last batch, take all thats left\n", + " X_batch = X[i * batch_size :, :]\n", + " t_batch = t[i * batch_size :, :]\n", + " else:\n", + " X_batch = X[i * batch_size : (i + 1) * batch_size, :]\n", + " t_batch = t[i * batch_size : (i + 1) * batch_size, :]\n", + "\n", + " self._feedforward(X_batch)\n", + " self._backpropagate(X_batch, t_batch, lam)\n", + "\n", + " # reset schedulers for each epoch (some schedulers pass in this call)\n", + " for scheduler in self.schedulers_weight:\n", + " scheduler.reset()\n", + "\n", + " for scheduler in self.schedulers_bias:\n", + " scheduler.reset()\n", + "\n", + " # computing performance metrics\n", + " pred_train = self.predict(X)\n", + " train_error = cost_function_train(pred_train)\n", + "\n", + " train_errors[e] = train_error\n", + " if val_set:\n", + " \n", + " pred_val = self.predict(X_val)\n", + " val_error = cost_function_val(pred_val)\n", + " val_errors[e] = val_error\n", + "\n", + " if self.classification:\n", + " train_acc = self._accuracy(self.predict(X), t)\n", + " train_accs[e] = train_acc\n", + " if val_set:\n", + " val_acc = self._accuracy(pred_val, t_val)\n", + " val_accs[e] = val_acc\n", + "\n", + " # printing progress bar\n", + " progression = e / epochs\n", + " print_length = self._progress_bar(\n", + " progression,\n", + " train_error=train_errors[e],\n", + " train_acc=train_accs[e],\n", + " val_error=val_errors[e],\n", + " val_acc=val_accs[e],\n", + " )\n", + " except KeyboardInterrupt:\n", + " # allows for stopping training at any point and seeing the result\n", + " pass\n", + "\n", + " # visualization of training progression (similiar to tensorflow progression bar)\n", + " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", + " sys.stdout.flush()\n", + " self._progress_bar(\n", + " 1,\n", + " train_error=train_errors[e],\n", + " train_acc=train_accs[e],\n", + " val_error=val_errors[e],\n", + " val_acc=val_accs[e],\n", + " )\n", + " sys.stdout.write(\"\")\n", + "\n", + " # return performance metrics for the entire run\n", + " scores = dict()\n", + "\n", + " scores[\"train_errors\"] = train_errors\n", + "\n", + " if val_set:\n", + " scores[\"val_errors\"] = val_errors\n", + "\n", + " if self.classification:\n", + " scores[\"train_accs\"] = train_accs\n", + "\n", + " if val_set:\n", + " scores[\"val_accs\"] = val_accs\n", + "\n", + " return scores\n", + "\n", + " def predict(self, X: np.ndarray, *, threshold=0.5):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs prediction after training of the network has been finished.\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray): The design matrix, with n rows of p features each\n", + "\n", + " Optional Parameters:\n", + " ------------\n", + " II threshold (float) : sets minimal value for a prediction to be predicted as the positive class\n", + " in classification problems\n", + "\n", + " Returns:\n", + " ------------\n", + " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", + " This vector is thresholded if regression=False, meaning that classification results\n", + " in a vector of 1s and 0s, while regressions in an array of decimal numbers\n", + "\n", + " \"\"\"\n", + "\n", + " predict = self._feedforward(X)\n", + "\n", + " if self.classification:\n", + " return np.where(predict > threshold, 1, 0)\n", + " else:\n", + " return predict\n", + "\n", + " def reset_weights(self):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Resets/Reinitializes the weights in order to train the network for a new problem.\n", + "\n", + " \"\"\"\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " self.weights = list()\n", + " for i in range(len(self.dimensions) - 1):\n", + " weight_array = np.random.randn(\n", + " self.dimensions[i] + 1, self.dimensions[i + 1]\n", + " )\n", + " weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01\n", + "\n", + " self.weights.append(weight_array)\n", + "\n", + " def _feedforward(self, X: np.ndarray):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Calculates the activation of each layer starting at the input and ending at the output.\n", + " Each following activation is calculated from a weighted sum of each of the preceeding\n", + " activations (except in the case of the input layer).\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray): The design matrix, with n rows of p features each\n", + "\n", + " Returns:\n", + " ------------\n", + " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", + " \"\"\"\n", + "\n", + " # reset matrices\n", + " self.a_matrices = list()\n", + " self.z_matrices = list()\n", + "\n", + " # if X is just a vector, make it into a matrix\n", + " if len(X.shape) == 1:\n", + " X = X.reshape((1, X.shape[0]))\n", + "\n", + " # Add a coloumn of zeros as the first coloumn of the design matrix, in order\n", + " # to add bias to our data\n", + " bias = np.ones((X.shape[0], 1)) * 0.01\n", + " X = np.hstack([bias, X])\n", + "\n", + " # a^0, the nodes in the input layer (one a^0 for each row in X - where the\n", + " # exponent indicates layer number).\n", + " a = X\n", + " self.a_matrices.append(a)\n", + " self.z_matrices.append(a)\n", + "\n", + " # The feed forward algorithm\n", + " for i in range(len(self.weights)):\n", + " if i < len(self.weights) - 1:\n", + " z = a @ self.weights[i]\n", + " self.z_matrices.append(z)\n", + " a = self.hidden_func(z)\n", + " # bias column again added to the data here\n", + " bias = np.ones((a.shape[0], 1)) * 0.01\n", + " a = np.hstack([bias, a])\n", + " self.a_matrices.append(a)\n", + " else:\n", + " try:\n", + " # a^L, the nodes in our output layers\n", + " z = a @ self.weights[i]\n", + " a = self.output_func(z)\n", + " self.a_matrices.append(a)\n", + " self.z_matrices.append(z)\n", + " except Exception as OverflowError:\n", + " print(\n", + " \"OverflowError in fit() in FFNN\\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling\"\n", + " )\n", + "\n", + " # this will be a^L\n", + " return a\n", + "\n", + " def _backpropagate(self, X, t, lam):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs the backpropagation algorithm. In other words, this method\n", + " calculates the gradient of all the layers starting at the\n", + " output layer, and moving from right to left accumulates the gradient until\n", + " the input layer is reached. Each layers respective weights are updated while\n", + " the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray): The design matrix, with n rows of p features each.\n", + " II t (np.ndarray): The target vector, with n rows of p targets.\n", + " III lam (float32): regularization parameter used to punish the weights in case of overfitting\n", + "\n", + " Returns:\n", + " ------------\n", + " No return value.\n", + "\n", + " \"\"\"\n", + " out_derivative = derivate(self.output_func)\n", + " hidden_derivative = derivate(self.hidden_func)\n", + "\n", + " for i in range(len(self.weights) - 1, -1, -1):\n", + " # delta terms for output\n", + " if i == len(self.weights) - 1:\n", + " # for multi-class classification\n", + " if (\n", + " self.output_func.__name__ == \"softmax\"\n", + " ):\n", + " delta_matrix = self.a_matrices[i + 1] - t\n", + " # for single class classification\n", + " else:\n", + " cost_func_derivative = grad(self.cost_func(t))\n", + " delta_matrix = out_derivative(\n", + " self.z_matrices[i + 1]\n", + " ) * cost_func_derivative(self.a_matrices[i + 1])\n", + "\n", + " # delta terms for hidden layer\n", + " else:\n", + " delta_matrix = (\n", + " self.weights[i + 1][1:, :] @ delta_matrix.T\n", + " ).T * hidden_derivative(self.z_matrices[i + 1])\n", + "\n", + " # calculate gradient\n", + " gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix\n", + " gradient_bias = np.sum(delta_matrix, axis=0).reshape(\n", + " 1, delta_matrix.shape[1]\n", + " )\n", + "\n", + " # regularization term\n", + " gradient_weights += self.weights[i][1:, :] * lam\n", + "\n", + " # use scheduler\n", + " update_matrix = np.vstack(\n", + " [\n", + " self.schedulers_bias[i].update_change(gradient_bias),\n", + " self.schedulers_weight[i].update_change(gradient_weights),\n", + " ]\n", + " )\n", + "\n", + " # update weights and bias\n", + " self.weights[i] -= update_matrix\n", + "\n", + " def _accuracy(self, prediction: np.ndarray, target: np.ndarray):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Calculates accuracy of given prediction to target\n", + "\n", + " Parameters:\n", + " ------------\n", + " I prediction (np.ndarray): vector of predicitons output network\n", + " (1s and 0s in case of classification, and real numbers in case of regression)\n", + " II target (np.ndarray): vector of true values (What the network ideally should predict)\n", + "\n", + " Returns:\n", + " ------------\n", + " A floating point number representing the percentage of correctly classified instances.\n", + " \"\"\"\n", + " assert prediction.size == target.size\n", + " return np.average((target == prediction))\n", + " def _set_classification(self):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Decides if FFNN acts as classifier (True) og regressor (False),\n", + " sets self.classification during init()\n", + " \"\"\"\n", + " self.classification = False\n", + " if (\n", + " self.cost_func.__name__ == \"CostLogReg\"\n", + " or self.cost_func.__name__ == \"CostCrossEntropy\"\n", + " ):\n", + " self.classification = True\n", + "\n", + " def _progress_bar(self, progression, **kwargs):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Displays progress of training\n", + " \"\"\"\n", + " print_length = 40\n", + " num_equals = int(progression * print_length)\n", + " num_not = print_length - num_equals\n", + " arrow = \">\" if num_equals > 0 else \"\"\n", + " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", + " perc_print = self._format(progression * 100, decimals=5)\n", + " line = f\" {bar} {perc_print}% \"\n", + "\n", + " for key in kwargs:\n", + " if not np.isnan(kwargs[key]):\n", + " value = self._format(kwargs[key], decimals=4)\n", + " line += f\"| {key}: {value} \"\n", + " sys.stdout.write(\"\\r\" + line)\n", + " sys.stdout.flush()\n", + " return len(line)\n", + "\n", + " def _format(self, value, decimals=4):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Formats decimal numbers for progress bar\n", + " \"\"\"\n", + " if value > 0:\n", + " v = value\n", + " elif value < 0:\n", + " v = -10 * value\n", + " else:\n", + " v = 1\n", + " n = 1 + math.floor(math.log10(v))\n", + " if n >= decimals - 1:\n", + " return str(round(value))\n", + " return f\"{value:.{decimals-n-1}f}\"" + ] + }, + { + "cell_type": "markdown", + "id": "0f29bccd", + "metadata": { + "editable": true + }, + "source": [ + "Before we make a model, we will quickly generate a dataset we can use\n", + "for our linear regression problem as shown below" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "dc37b403", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "def SkrankeFunction(x, y):\n", + " return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)\n", + "\n", + "def create_X(x, y, n):\n", + " if len(x.shape) > 1:\n", + " x = np.ravel(x)\n", + " y = np.ravel(y)\n", + "\n", + " N = len(x)\n", + " l = int((n + 1) * (n + 2) / 2) # Number of elements in beta\n", + " X = np.ones((N, l))\n", + "\n", + " for i in range(1, n + 1):\n", + " q = int((i) * (i + 1) / 2)\n", + " for k in range(i + 1):\n", + " X[:, q + k] = (x ** (i - k)) * (y**k)\n", + "\n", + " return X\n", + "\n", + "step=0.5\n", + "x = np.arange(0, 1, step)\n", + "y = np.arange(0, 1, step)\n", + "x, y = np.meshgrid(x, y)\n", + "target = SkrankeFunction(x, y)\n", + "target = target.reshape(target.shape[0], 1)\n", + "\n", + "poly_degree=3\n", + "X = create_X(x, y, poly_degree)\n", + "\n", + "X_train, X_test, t_train, t_test = train_test_split(X, target)" + ] + }, + { + "cell_type": "markdown", + "id": "91790369", + "metadata": { + "editable": true + }, + "source": [ + "Now that we have our dataset ready for the regression, we can create\n", + "our regressor. Note that with the seed parameter, we can make sure our\n", + "results stay the same every time we run the neural network. For\n", + "inititialization, we simply specify the dimensions (we wish the amount\n", + "of input nodes to be equal to the datapoints, and the output to\n", + "predict one value)." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "62585c7a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "input_nodes = X_train.shape[1]\n", + "output_nodes = 1\n", + "\n", + "linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)" + ] + }, + { + "cell_type": "markdown", + "id": "69cdc171", + "metadata": { + "editable": true + }, + "source": [ + "We then fit our model with our training data using the scheduler of our choice." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "d0713298", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Constant(eta=1e-3)\n", + "scores = linear_regression.fit(X_train, t_train, scheduler)" + ] + }, + { + "cell_type": "markdown", + "id": "310f805d", + "metadata": { + "editable": true + }, + "source": [ + "Due to the progress bar we can see the MSE (train_error) throughout\n", + "the FFNN's training. Note that the fit() function has some optional\n", + "parameters with defualt arguments. For example, the regularization\n", + "hyperparameter can be left ignored if not needed, and equally the FFNN\n", + "will by default run for 100 epochs. These can easily be changed, such\n", + "as for example:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "216d1c44", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)" + ] + }, + { + "cell_type": "markdown", + "id": "ba2e5a39", + "metadata": { + "editable": true + }, + "source": [ + "We see that given more epochs to train on, the regressor reaches a lower MSE.\n", + "\n", + "Let us then switch to a binary classification. We use a binary\n", + "classification dataset, and follow a similar setup to the regression\n", + "case." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "8c5b291e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "wisconsin = load_breast_cancer()\n", + "X = wisconsin.data\n", + "target = wisconsin.target\n", + "target = target.reshape(target.shape[0], 1)\n", + "\n", + "X_train, X_val, t_train, t_val = train_test_split(X, target)\n", + "\n", + "scaler = MinMaxScaler()\n", + "scaler.fit(X_train)\n", + "X_train = scaler.transform(X_train)\n", + "X_val = scaler.transform(X_val)" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "4f6aa682", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "input_nodes = X_train.shape[1]\n", + "output_nodes = 1\n", + "\n", + "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)" + ] + }, + { + "cell_type": "markdown", + "id": "3ff7c54a", + "metadata": { + "editable": true + }, + "source": [ + "We will now make use of our validation data by passing it into our fit function as a keyword argument" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "4bbcaedd", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", + "scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" + ] + }, + { + "cell_type": "markdown", + "id": "aa4f54fe", + "metadata": { + "editable": true + }, + "source": [ + "Finally, we will create a neural network with 2 hidden layers with activation functions." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "c11be1f5", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "input_nodes = X_train.shape[1]\n", + "hidden_nodes1 = 100\n", + "hidden_nodes2 = 30\n", + "output_nodes = 1\n", + "\n", + "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", + "\n", + "neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "78482f24", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", + "scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" + ] + }, + { + "cell_type": "markdown", + "id": "678b88e7", + "metadata": { + "editable": true + }, + "source": [ + "### Multiclass classification\n", + "\n", + "Finally, we will demonstrate the use case of multiclass classification\n", + "using our FFNN with the famous MNIST dataset, which contain images of\n", + "digits between the range of 0 to 9." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "833a7321", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_digits\n", + "\n", + "def onehot(target: np.ndarray):\n", + " onehot = np.zeros((target.size, target.max() + 1))\n", + " onehot[np.arange(target.size), target] = 1\n", + " return onehot\n", + "\n", + "digits = load_digits()\n", + "\n", + "X = digits.data\n", + "target = digits.target\n", + "target = onehot(target)\n", + "\n", + "input_nodes = 64\n", + "hidden_nodes1 = 100\n", + "hidden_nodes2 = 30\n", + "output_nodes = 10\n", + "\n", + "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", + "\n", + "multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)\n", + "\n", + "multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", + "scores = multiclass.fit(X, target, scheduler, epochs=1000)" + ] + }, + { + "cell_type": "markdown", + "id": "1af2ad7b", + "metadata": { + "editable": true + }, + "source": [ + "## Testing the XOR gate and other gates\n", + "\n", + "Let us now use our code to test the XOR gate." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "752c6403", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", + "\n", + "# The XOR gate\n", + "yXOR = np.array( [[ 0], [1] ,[1], [0]])\n", + "\n", + "input_nodes = X.shape[1]\n", + "output_nodes = 1\n", + "\n", + "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)\n", + "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)\n", + "scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)" + ] + }, + { + "cell_type": "markdown", + "id": "0a7c91e3", + "metadata": { + "editable": true + }, + "source": [ + "Not bad, but the results depend strongly on the learning reate. Try different learning rates." + ] + }, + { + "cell_type": "markdown", + "id": "40ffa1fb", + "metadata": { + "editable": true + }, + "source": [ + "## Solving differential equations with Deep Learning\n", + "\n", + "The Universal Approximation Theorem states that a neural network can\n", + "approximate any function at a single hidden layer along with one input\n", + "and output layer to any given precision.\n", + "\n", + "**Book on solving differential equations with ML methods.**\n", + "\n", + "[An Introduction to Neural Network Methods for Differential Equations](https://www.springer.com/gp/book/9789401798150), by Yadav and Kumar.\n", + "\n", + "**Physics informed neural networks.**\n", + "\n", + "[Scientific Machine Learning Through Physics–Informed Neural Networks: Where we are and What’s Next](https://link.springer.com/article/10.1007/s10915-022-01939-z), by Cuomo et al\n", + "\n", + "**Thanks to Kristine Baluka Hein.**\n", + "\n", + "The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI.\n", + "A great thanks to Kristine." + ] + }, + { + "cell_type": "markdown", + "id": "191ba3eb", + "metadata": { + "editable": true + }, + "source": [ + "## Ordinary Differential Equations first\n", + "\n", + "An ordinary differential equation (ODE) is an equation involving functions having one variable.\n", + "\n", + "In general, an ordinary differential equation looks like" + ] + }, + { + "cell_type": "markdown", + "id": "a0be312a", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{ode} \\tag{1}\n", + "f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right) = 0\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "000663cf", + "metadata": { + "editable": true + }, + "source": [ + "where $g(x)$ is the function to find, and $g^{(n)}(x)$ is the $n$-th derivative of $g(x)$.\n", + "\n", + "The $f\\left(x, g(x), g'(x), g''(x), \\, \\dots \\, , g^{(n)}(x)\\right)$ is just a way to write that there is an expression involving $x$ and $g(x), \\ g'(x), \\ g''(x), \\, \\dots \\, , \\text{ and } g^{(n)}(x)$ on the left side of the equality sign in ([1](#ode)).\n", + "The highest order of derivative, that is the value of $n$, determines to the order of the equation.\n", + "The equation is referred to as a $n$-th order ODE.\n", + "Along with ([1](#ode)), some additional conditions of the function $g(x)$ are typically given\n", + "for the solution to be unique." + ] + }, + { + "cell_type": "markdown", + "id": "f5b87995", + "metadata": { + "editable": true + }, + "source": [ + "## The trial solution\n", + "\n", + "Let the trial solution $g_t(x)$ be" + ] + }, + { + "cell_type": "markdown", + "id": "a166c0b6", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\tg_t(x) = h_1(x) + h_2(x,N(x,P))\n", + "\\label{_auto1} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f1e49a2c", + "metadata": { + "editable": true + }, + "source": [ + "where $h_1(x)$ is a function that makes $g_t(x)$ satisfy a given set\n", + "of conditions, $N(x,P)$ a neural network with weights and biases\n", + "described by $P$ and $h_2(x, N(x,P))$ some expression involving the\n", + "neural network. The role of the function $h_2(x, N(x,P))$, is to\n", + "ensure that the output from $N(x,P)$ is zero when $g_t(x)$ is\n", + "evaluated at the values of $x$ where the given conditions must be\n", + "satisfied. The function $h_1(x)$ should alone make $g_t(x)$ satisfy\n", + "the conditions.\n", + "\n", + "But what about the network $N(x,P)$?\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "207d1a97", + "metadata": { + "editable": true + }, + "source": [ + "## Minimization process\n", + "\n", + "For the minimization to be defined, we need to have a cost function at hand to minimize.\n", + "\n", + "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)).\n", + "We can choose to consider the mean squared error as the cost function for an input $x$.\n", + "Since we are looking at one input, the cost function is just $f$ squared.\n", + "The cost function $c\\left(x, P \\right)$ can therefore be expressed as" + ] + }, + { + "cell_type": "markdown", + "id": "94a061a1", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C\\left(x, P\\right) = \\big(f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)\\big)^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "93244d03", + "metadata": { + "editable": true + }, + "source": [ + "If $N$ inputs are given as a vector $\\boldsymbol{x}$ with elements $x_i$ for $i = 1,\\dots,N$,\n", + "the cost function becomes" + ] + }, + { + "cell_type": "markdown", + "id": "6dc16fd4", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{cost} \\tag{3}\n", + "\tC\\left(\\boldsymbol{x}, P\\right) = \\frac{1}{N} \\sum_{i=1}^N \\big(f\\left(x_i, \\, g(x_i), \\, g'(x_i), \\, g''(x_i), \\, \\dots \\, , \\, g^{(n)}(x_i)\\right)\\big)^2\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "01f4c14a", + "metadata": { + "editable": true + }, + "source": [ + "The neural net should then find the parameters $P$ that minimizes the cost function in\n", + "([3](#cost)) for a set of $N$ training samples $x_i$." + ] + }, + { + "cell_type": "markdown", + "id": "1784066c", + "metadata": { + "editable": true + }, + "source": [ + "## Minimizing the cost function using gradient descent and automatic differentiation\n", + "\n", + "To perform the minimization using gradient descent, the gradient of $C\\left(\\boldsymbol{x}, P\\right)$ is needed.\n", + "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.\n", + "\n", + "Luckily, there exists libraries that makes the job for us through automatic differentiation.\n", + "Automatic differentiation is a method of finding the derivatives numerically with very high precision." + ] + }, + { + "cell_type": "markdown", + "id": "43e1b7bf", + "metadata": { + "editable": true + }, + "source": [ + "## Example: Exponential decay\n", + "\n", + "An exponential decay of a quantity $g(x)$ is described by the equation" + ] + }, + { + "cell_type": "markdown", + "id": "5c28e60a", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{solve_expdec} \\tag{4}\n", + " g'(x) = -\\gamma g(x)\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "cfd2e420", + "metadata": { + "editable": true + }, + "source": [ + "with $g(0) = g_0$ for some chosen initial value $g_0$.\n", + "\n", + "The analytical solution of ([4](#solve_expdec)) is" + ] + }, + { + "cell_type": "markdown", + "id": "b93aa0f8", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " g(x) = g_0 \\exp\\left(-\\gamma x\\right)\n", + "\\label{_auto2} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "093952f0", + "metadata": { + "editable": true + }, + "source": [ + "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))." + ] + }, + { + "cell_type": "markdown", + "id": "8f82fa61", + "metadata": { + "editable": true + }, + "source": [ + "## The function to solve for\n", + "\n", + "The program will use a neural network to solve" + ] + }, + { + "cell_type": "markdown", + "id": "027d9c52", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{solveode} \\tag{6}\n", + "g'(x) = -\\gamma g(x)\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c18c4ee8", + "metadata": { + "editable": true + }, + "source": [ + "where $g(0) = g_0$ with $\\gamma$ and $g_0$ being some chosen values.\n", + "\n", + "In this example, $\\gamma = 2$ and $g_0 = 10$." + ] + }, + { + "cell_type": "markdown", + "id": "a0d7fc0a", + "metadata": { + "editable": true + }, + "source": [ + "## The trial solution\n", + "To begin with, a trial solution $g_t(t)$ must be chosen. A general trial solution for ordinary differential equations could be" + ] + }, + { + "cell_type": "markdown", + "id": "73cd72f4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "g_t(x, P) = h_1(x) + h_2(x, N(x, P))\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a4d0850f", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "62f3b94f", + "metadata": { + "editable": true + }, + "source": [ + "## Setup of Network\n", + "\n", + "In this network, there are no weights and bias at the input layer, so $P = \\{ P_{\\text{hidden}}, P_{\\text{output}} \\}$.\n", + "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.\n", + "\n", + "The first column in $P_{\\text{hidden} }$ represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer.\n", + "If there are $N_{\\text{output} }$ neurons in the output layer, then $P_{\\text{output}} $ is a $N_{\\text{output} } \\times (1 + N_{\\text{hidden} })$ matrix.\n", + "\n", + "Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.\n", + "\n", + "It is given that $g(0) = g_0$. The trial solution must fulfill this condition to be a proper solution of ([6](#solveode)). A possible way to ensure that $g_t(0, P) = g_0$, is to let $F(N(x,P)) = x \\cdot N(x,P)$ and $A(x) = g_0$. This gives the following trial solution:" + ] + }, + { + "cell_type": "markdown", + "id": "f5144858", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{trial} \\tag{7}\n", + "g_t(x, P) = g_0 + x \\cdot N(x, P)\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6b441362", + "metadata": { + "editable": true + }, + "source": [ + "## Reformulating the problem\n", + "\n", + "We wish that our neural network manages to minimize a given cost function.\n", + "\n", + "A reformulation of out equation, ([6](#solveode)), must therefore be done,\n", + "such that it describes the problem a neural network can solve for.\n", + "\n", + "The neural network must find the set of weights and biases $P$ such that the trial solution in ([7](#trial)) satisfies ([6](#solveode)).\n", + "\n", + "The trial solution" + ] + }, + { + "cell_type": "markdown", + "id": "abfe2d6d", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "g_t(x, P) = g_0 + x \\cdot N(x, P)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "aabb6c7b", + "metadata": { + "editable": true + }, + "source": [ + "has been chosen such that it already solves the condition $g(0) = g_0$. What remains, is to find $P$ such that" + ] + }, + { + "cell_type": "markdown", + "id": "11fc8b1b", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{nnmin} \\tag{8}\n", + "g_t'(x, P) = - \\gamma g_t(x, P)\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "604c92b4", + "metadata": { + "editable": true + }, + "source": [ + "is fulfilled as *best as possible*." + ] + }, + { + "cell_type": "markdown", + "id": "e2cd7572", + "metadata": { + "editable": true + }, + "source": [ + "## More technicalities\n", + "\n", + "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.\n", + "This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.\n", + "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.\n", + "\n", + "This gives the following cost function our neural network must solve for:" + ] + }, + { + "cell_type": "markdown", + "id": "d916a5f6", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\min_{P}\\Big\\{ \\big(g_t'(x, P) - ( -\\gamma g_t(x, P) \\big)^2 \\Big\\}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d746e69c", + "metadata": { + "editable": true + }, + "source": [ + "(the notation $\\min_{P}\\{ f(x, P) \\}$ means that we desire to find $P$ that yields the minimum of $f(x, P)$)\n", + "\n", + "or, in terms of weights and biases for the hidden and output layer in our network:" + ] + }, + { + "cell_type": "markdown", + "id": "4c34c242", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }}\\Big\\{ \\big(g_t'(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) - ( -\\gamma g_t(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) \\big)^2 \\Big\\}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f55f3047", + "metadata": { + "editable": true + }, + "source": [ + "for an input value $x$." + ] + }, + { + "cell_type": "markdown", + "id": "485e4671", + "metadata": { + "editable": true + }, + "source": [ + "## More details\n", + "\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "5628ca35", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{min} \\tag{9}\n", + "\\min_{P}\\Big\\{\\frac{1}{N} \\sum_{i=1}^N \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2 \\Big\\}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "da2c90ea", + "metadata": { + "editable": true + }, + "source": [ + "Letting $\\boldsymbol{x}$ be a vector with elements $x_i$ and $C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2$ denote the cost function, the minimization problem that our network must solve, becomes" + ] + }, + { + "cell_type": "markdown", + "id": "d386a466", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\min_{P} C(\\boldsymbol{x}, P)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ec3d975a", + "metadata": { + "editable": true + }, + "source": [ + "In terms of $P_{\\text{hidden} }$ and $P_{\\text{output} }$, this could also be expressed as\n", + "\n", + "$$\n", + "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }} C(\\boldsymbol{x}, \\{P_{\\text{hidden} }, P_{\\text{output} }\\})\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4f0f47e7", + "metadata": { + "editable": true + }, + "source": [ + "## A possible implementation of a neural network\n", + "\n", + "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)).\n", + "\n", + "First, the neural network must feed forward the inputs.\n", + "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.\n", + "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} }$." + ] + }, + { + "cell_type": "markdown", + "id": "a757d9cf", + "metadata": { + "editable": true + }, + "source": [ + "## Technicalities\n", + "\n", + "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:" + ] + }, + { + "cell_type": "markdown", + "id": "ee093dd9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "z_{i,j}^{\\text{hidden}} &= b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_j \\\\\n", + "&=\n", + "\\begin{pmatrix}\n", + "b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n", + "\\end{pmatrix}\n", + "\\begin{pmatrix}\n", + "1 \\\\\n", + "x_j\n", + "\\end{pmatrix}\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4d3954bf", + "metadata": { + "editable": true + }, + "source": [ + "## Final technicalities I\n", + "\n", + "The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector:" + ] + }, + { + "cell_type": "markdown", + "id": "b4b36b8c", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "\\boldsymbol{z}_{i}^{\\text{hidden}} &= \\Big( b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_1 , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_2, \\ \\dots \\, , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_N\\Big) \\\\\n", + "&=\n", + "\\begin{pmatrix}\n", + " b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n", + "\\end{pmatrix}\n", + "\\begin{pmatrix}\n", + "1 & 1 & \\dots & 1 \\\\\n", + "x_1 & x_2 & \\dots & x_N\n", + "\\end{pmatrix} \\\\\n", + "&= \\boldsymbol{p}_{i, \\text{hidden}}^T X\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "36e8a1dd", + "metadata": { + "editable": true + }, + "source": [ + "## Final technicalities II\n", + "\n", + "The vector $\\boldsymbol{p}_{i, \\text{hidden}}^T$ constitutes each row in $P_{\\text{hidden} }$, which contains the weights for the neural network to minimize according to ([9](#min)).\n", + "\n", + "After having found $\\boldsymbol{z}_{i}^{\\text{hidden}} $ for every $i$-th neuron within the hidden layer, the vector will be sent to an activation function $a_i(\\boldsymbol{z})$.\n", + "\n", + "In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:" + ] + }, + { + "cell_type": "markdown", + "id": "af2e68be", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f(z) = \\frac{1}{1 + \\exp{(-z)}}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7b8922c6", + "metadata": { + "editable": true + }, + "source": [ + "It is possible to use other activations functions for the hidden layer also.\n", + "\n", + "The output $\\boldsymbol{x}_i^{\\text{hidden}}$ from each $i$-th hidden neuron is:\n", + "\n", + "$$\n", + "\\boldsymbol{x}_i^{\\text{hidden} } = f\\big( \\boldsymbol{z}_{i}^{\\text{hidden}} \\big)\n", + "$$\n", + "\n", + "The outputs $\\boldsymbol{x}_i^{\\text{hidden} } $ are then sent to the output layer.\n", + "\n", + "The output layer consists of one neuron in this case, and combines the\n", + "output from each of the neurons in the hidden layers. The output layer\n", + "combines the results from the hidden layer using some weights $w_i^{\\text{output}}$\n", + "and biases $b_i^{\\text{output}}$. In this case,\n", + "it is assumes that the number of neurons in the output layer is one." + ] + }, + { + "cell_type": "markdown", + "id": "2aa977d9", + "metadata": { + "editable": true + }, + "source": [ + "## Final technicalities III\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "48eccfa6", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "z_{1,j}^{\\text{output}} & =\n", + "\\begin{pmatrix}\n", + "b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n", + "\\end{pmatrix}\n", + "\\begin{pmatrix}\n", + "1 \\\\\n", + "\\boldsymbol{x}_j^{\\text{hidden}}\n", + "\\end{pmatrix}\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d4c2cdbf", + "metadata": { + "editable": true + }, + "source": [ + "## Final technicalities IV\n", + "\n", + "Expressing $z_{1,j}^{\\text{output}}$ as a vector gives the following way of weighting the inputs from the hidden layer:" + ] + }, + { + "cell_type": "markdown", + "id": "be26d9c9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{z}_{1}^{\\text{output}} =\n", + "\\begin{pmatrix}\n", + "b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n", + "\\end{pmatrix}\n", + "\\begin{pmatrix}\n", + "1 & 1 & \\dots & 1 \\\\\n", + "\\boldsymbol{x}_1^{\\text{hidden}} & \\boldsymbol{x}_2^{\\text{hidden}} & \\dots & \\boldsymbol{x}_N^{\\text{hidden}}\n", + "\\end{pmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f3703c9a", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "9859680c", + "metadata": { + "editable": true + }, + "source": [ + "## Back propagation\n", + "\n", + "The next step is to decide how the parameters should be changed such that they minimize the cost function.\n", + "\n", + "The chosen cost function for this problem is" + ] + }, + { + "cell_type": "markdown", + "id": "c3df269d", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "dc69023a", + "metadata": { + "editable": true + }, + "source": [ + "In order to minimize the cost function, an optimization method must be chosen.\n", + "\n", + "Here, gradient descent with a constant step size has been chosen." + ] + }, + { + "cell_type": "markdown", + "id": "d4bed3bd", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient descent\n", + "\n", + "The idea of the gradient descent algorithm is to update parameters in\n", + "a direction where the cost function decreases goes to a minimum.\n", + "\n", + "In general, the update of some parameters $\\boldsymbol{\\omega}$ given a cost\n", + "function defined by some weights $\\boldsymbol{\\omega}$, $C(\\boldsymbol{x},\n", + "\\boldsymbol{\\omega})$, goes as follows:" + ] + }, + { + "cell_type": "markdown", + "id": "ed2a4f9a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\omega}_{\\text{new} } = \\boldsymbol{\\omega} - \\lambda \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b9a4f604", + "metadata": { + "editable": true + }, + "source": [ + "for a number of iterations or until $ \\big|\\big| \\boldsymbol{\\omega}_{\\text{new} } - \\boldsymbol{\\omega} \\big|\\big|$ becomes smaller than some given tolerance.\n", + "\n", + "The value of $\\lambda$ decides how large steps the algorithm must take\n", + "in the direction of $ \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})$.\n", + "The notation $\\nabla_{\\boldsymbol{\\omega}}$ express the gradient with respect\n", + "to the elements in $\\boldsymbol{\\omega}$.\n", + "\n", + "In our case, we have to minimize the cost function $C(\\boldsymbol{x}, P)$ with\n", + "respect to the two sets of weights and biases, that is for the hidden\n", + "layer $P_{\\text{hidden} }$ and for the output layer $P_{\\text{output}\n", + "}$ .\n", + "\n", + "This means that $P_{\\text{hidden} }$ and $P_{\\text{output} }$ is updated by" + ] + }, + { + "cell_type": "markdown", + "id": "e48d507f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "P_{\\text{hidden},\\text{new}} &= P_{\\text{hidden}} - \\lambda \\nabla_{P_{\\text{hidden}}} C(\\boldsymbol{x}, P) \\\\\n", + "P_{\\text{output},\\text{new}} &= P_{\\text{output}} - \\lambda \\nabla_{P_{\\text{output}}} C(\\boldsymbol{x}, P)\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b84c5cf5", + "metadata": { + "editable": true + }, + "source": [ + "## The code for solving the ODE" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "293d0f7d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad, elementwise_grad\n", + "import autograd.numpy.random as npr\n", + "from matplotlib import pyplot as plt\n", + "\n", + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "# Assuming one input, hidden, and output layer\n", + "def neural_network(params, x):\n", + "\n", + " # Find the weights (including and biases) for the hidden and output layer.\n", + " # Assume that params is a list of parameters for each layer.\n", + " # The biases are the first element for each array in params,\n", + " # and the weights are the remaning elements in each array in params.\n", + "\n", + " w_hidden = params[0]\n", + " w_output = params[1]\n", + "\n", + " # Assumes input x being an one-dimensional array\n", + " num_values = np.size(x)\n", + " x = x.reshape(-1, num_values)\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + "\n", + " ## Hidden layer:\n", + "\n", + " # Add a row of ones to include bias\n", + " x_input = np.concatenate((np.ones((1,num_values)), x_input ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_input)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " ## Output layer:\n", + "\n", + " # Include bias:\n", + " x_hidden = np.concatenate((np.ones((1,num_values)), x_hidden ), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_hidden)\n", + " x_output = z_output\n", + "\n", + " return x_output\n", + "\n", + "# The trial solution using the deep neural network:\n", + "def g_trial(x,params, g0 = 10):\n", + " return g0 + x*neural_network(params,x)\n", + "\n", + "# The right side of the ODE:\n", + "def g(x, g_trial, gamma = 2):\n", + " return -gamma*g_trial\n", + "\n", + "# The cost function:\n", + "def cost_function(P, x):\n", + "\n", + " # Evaluate the trial function with the current parameters P\n", + " g_t = g_trial(x,P)\n", + "\n", + " # Find the derivative w.r.t x of the neural network\n", + " d_net_out = elementwise_grad(neural_network,1)(P,x)\n", + "\n", + " # Find the derivative w.r.t x of the trial function\n", + " d_g_t = elementwise_grad(g_trial,0)(x,P)\n", + "\n", + " # The right side of the ODE\n", + " func = g(x, g_t)\n", + "\n", + " err_sqr = (d_g_t - func)**2\n", + " cost_sum = np.sum(err_sqr)\n", + "\n", + " return cost_sum / np.size(err_sqr)\n", + "\n", + "# Solve the exponential decay ODE using neural network with one input, hidden, and output layer\n", + "def solve_ode_neural_network(x, num_neurons_hidden, num_iter, lmb):\n", + " ## Set up initial weights and biases\n", + "\n", + " # For the hidden layer\n", + " p0 = npr.randn(num_neurons_hidden, 2 )\n", + "\n", + " # For the output layer\n", + " p1 = npr.randn(1, num_neurons_hidden + 1 ) # +1 since bias is included\n", + "\n", + " P = [p0, p1]\n", + "\n", + " print('Initial cost: %g'%cost_function(P, x))\n", + "\n", + " ## Start finding the optimal weights using gradient descent\n", + "\n", + " # Find the Python function that represents the gradient of the cost function\n", + " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", + " cost_function_grad = grad(cost_function,0)\n", + "\n", + " # Let the update be done num_iter times\n", + " for i in range(num_iter):\n", + " # Evaluate the gradient at the current weights and biases in P.\n", + " # The cost_grad consist now of two arrays;\n", + " # one for the gradient w.r.t P_hidden and\n", + " # one for the gradient w.r.t P_output\n", + " cost_grad = cost_function_grad(P, x)\n", + "\n", + " P[0] = P[0] - lmb * cost_grad[0]\n", + " P[1] = P[1] - lmb * cost_grad[1]\n", + "\n", + " print('Final cost: %g'%cost_function(P, x))\n", + "\n", + " return P\n", + "\n", + "def g_analytic(x, gamma = 2, g0 = 10):\n", + " return g0*np.exp(-gamma*x)\n", + "\n", + "# Solve the given problem\n", + "if __name__ == '__main__':\n", + " # Set seed such that the weight are initialized\n", + " # with same weights and biases for every run.\n", + " npr.seed(15)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " N = 10\n", + " x = np.linspace(0, 1, N)\n", + "\n", + " ## Set up the initial parameters\n", + " num_hidden_neurons = 10\n", + " num_iter = 10000\n", + " lmb = 0.001\n", + "\n", + " # Use the network\n", + " P = solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " # Print the deviation from the trial solution and true solution\n", + " res = g_trial(x,P)\n", + " res_analytical = g_analytic(x)\n", + "\n", + " print('Max absolute difference: %g'%np.max(np.abs(res - res_analytical)))\n", + "\n", + " # Plot the results\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", + " plt.plot(x, res_analytical)\n", + " plt.plot(x, res[0,:])\n", + " plt.legend(['analytical','nn'])\n", + " plt.xlabel('x')\n", + " plt.ylabel('g(x)')\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "54c070e1", + "metadata": { + "editable": true + }, + "source": [ + "## The network with one input layer, specified number of hidden layers, and one output layer\n", + "\n", + "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.\n", + "\n", + "The number of neurons within each hidden layer are given as a list of integers in the program below." + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "4ab2467e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad, elementwise_grad\n", + "import autograd.numpy.random as npr\n", + "from matplotlib import pyplot as plt\n", + "\n", + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "# The neural network with one input layer and one output layer,\n", + "# but with number of hidden layers specified by the user.\n", + "def deep_neural_network(deep_params, x):\n", + " # N_hidden is the number of hidden layers\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", + " # parameters to all the hidden\n", + " # layers AND the output layer.\n", + "\n", + " # Assumes input x being an one-dimensional array\n", + " num_values = np.size(x)\n", + " x = x.reshape(-1, num_values)\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + "\n", + " # Due to multiple hidden layers, define a variable referencing to the\n", + " # output of the previous layer:\n", + " x_prev = x_input\n", + "\n", + " ## Hidden layers:\n", + "\n", + " for l in range(N_hidden):\n", + " # From the list of parameters P; find the correct weigths and bias for this layer\n", + " w_hidden = deep_params[l]\n", + "\n", + " # Add a row of ones to include bias\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_prev)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " # Update x_prev such that next layer can use the output from this layer\n", + " x_prev = x_hidden\n", + "\n", + " ## Output layer:\n", + "\n", + " # Get the weights and bias for this layer\n", + " w_output = deep_params[-1]\n", + "\n", + " # Include bias:\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_prev)\n", + " x_output = z_output\n", + "\n", + " return x_output\n", + "\n", + "# The trial solution using the deep neural network:\n", + "def g_trial_deep(x,params, g0 = 10):\n", + " return g0 + x*deep_neural_network(params, x)\n", + "\n", + "# The right side of the ODE:\n", + "def g(x, g_trial, gamma = 2):\n", + " return -gamma*g_trial\n", + "\n", + "# The same cost function as before, but calls deep_neural_network instead.\n", + "def cost_function_deep(P, x):\n", + "\n", + " # Evaluate the trial function with the current parameters P\n", + " g_t = g_trial_deep(x,P)\n", + "\n", + " # Find the derivative w.r.t x of the neural network\n", + " d_net_out = elementwise_grad(deep_neural_network,1)(P,x)\n", + "\n", + " # Find the derivative w.r.t x of the trial function\n", + " d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n", + "\n", + " # The right side of the ODE\n", + " func = g(x, g_t)\n", + "\n", + " err_sqr = (d_g_t - func)**2\n", + " cost_sum = np.sum(err_sqr)\n", + "\n", + " return cost_sum / np.size(err_sqr)\n", + "\n", + "# Solve the exponential decay ODE using neural network with one input and one output layer,\n", + "# but with specified number of hidden layers from the user.\n", + "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", + " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", + "\n", + " # The number of elements in the list num_hidden_neurons thus represents\n", + " # the number of hidden layers.\n", + "\n", + " # Find the number of hidden layers:\n", + " N_hidden = np.size(num_neurons)\n", + "\n", + " ## Set up initial weights and biases\n", + "\n", + " # Initialize the list of parameters:\n", + " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", + "\n", + " P[0] = npr.randn(num_neurons[0], 2 )\n", + " for l in range(1,N_hidden):\n", + " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", + "\n", + " # For the output layer\n", + " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", + "\n", + " print('Initial cost: %g'%cost_function_deep(P, x))\n", + "\n", + " ## Start finding the optimal weights using gradient descent\n", + "\n", + " # Find the Python function that represents the gradient of the cost function\n", + " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", + " cost_function_deep_grad = grad(cost_function_deep,0)\n", + "\n", + " # Let the update be done num_iter times\n", + " for i in range(num_iter):\n", + " # Evaluate the gradient at the current weights and biases in P.\n", + " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", + " # in the hidden layers and output layers evaluated at x.\n", + " cost_deep_grad = cost_function_deep_grad(P, x)\n", + "\n", + " for l in range(N_hidden+1):\n", + " P[l] = P[l] - lmb * cost_deep_grad[l]\n", + "\n", + " print('Final cost: %g'%cost_function_deep(P, x))\n", + "\n", + " return P\n", + "\n", + "def g_analytic(x, gamma = 2, g0 = 10):\n", + " return g0*np.exp(-gamma*x)\n", + "\n", + "# Solve the given problem\n", + "if __name__ == '__main__':\n", + " npr.seed(15)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " N = 10\n", + " x = np.linspace(0, 1, N)\n", + "\n", + " ## Set up the initial parameters\n", + " num_hidden_neurons = np.array([10,10])\n", + " num_iter = 10000\n", + " lmb = 0.001\n", + "\n", + " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " res = g_trial_deep(x,P)\n", + " res_analytical = g_analytic(x)\n", + "\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.title('Performance of a deep neural network solving an ODE compared to the analytical solution')\n", + " plt.plot(x, res_analytical)\n", + " plt.plot(x, res[0,:])\n", + " plt.legend(['analytical','dnn'])\n", + " plt.ylabel('g(x)')\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "05126a03", + "metadata": { + "editable": true + }, + "source": [ + "## Example: Population growth\n", + "\n", + "A logistic model of population growth assumes that a population converges toward an equilibrium.\n", + "The population growth can be modeled by" + ] + }, + { + "cell_type": "markdown", + "id": "7b4e9871", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{log} \\tag{10}\n", + "\tg'(t) = \\alpha g(t)(A - g(t))\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "20266e3a", + "metadata": { + "editable": true + }, + "source": [ + "where $g(t)$ is the population density at time $t$, $\\alpha > 0$ the growth rate and $A > 0$ is the maximum population number in the environment.\n", + "Also, at $t = 0$ the population has the size $g(0) = g_0$, where $g_0$ is some chosen constant.\n", + "\n", + "In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability\n", + "and high execution time (this might be more apparent in the examples solving PDEs),\n", + "using a library like TensorFlow is recommended.\n", + "Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method." + ] + }, + { + "cell_type": "markdown", + "id": "8a3f1b3d", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the problem\n", + "\n", + "Here, we will model a population $g(t)$ in an environment having carrying capacity $A$.\n", + "The population follows the model" + ] + }, + { + "cell_type": "markdown", + "id": "14dfc04b", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{solveode_population} \\tag{11}\n", + "g'(t) = \\alpha g(t)(A - g(t))\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b125d1d3", + "metadata": { + "editable": true + }, + "source": [ + "where $g(0) = g_0$.\n", + "\n", + "In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$." + ] + }, + { + "cell_type": "markdown", + "id": "226a3528", + "metadata": { + "editable": true + }, + "source": [ + "## The trial solution\n", + "\n", + "We will get a slightly different trial solution, as the boundary conditions are different\n", + "compared to the case for exponential decay.\n", + "\n", + "A possible trial solution satisfying the condition $g(0) = g_0$ could be\n", + "\n", + "$$\n", + "h_1(t) = g_0 + t \\cdot N(t,P)\n", + "$$\n", + "\n", + "with $N(t,P)$ being the output from the neural network with weights and biases for each layer collected in the set $P$.\n", + "\n", + "The analytical solution is\n", + "\n", + "$$\n", + "g(t) = \\frac{Ag_0}{g_0 + (A - g_0)\\exp(-\\alpha A t)}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "adeeb731", + "metadata": { + "editable": true + }, + "source": [ + "## The program using Autograd\n", + "\n", + "The network will be the similar as for the exponential decay example, but with some small modifications for our problem." + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "eb3ed6d1", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad, elementwise_grad\n", + "import autograd.numpy.random as npr\n", + "from matplotlib import pyplot as plt\n", + "\n", + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "# Function to get the parameters.\n", + "# Done such that one can easily change the paramaters after one's liking.\n", + "def get_parameters():\n", + " alpha = 2\n", + " A = 1\n", + " g0 = 1.2\n", + " return alpha, A, g0\n", + "\n", + "def deep_neural_network(deep_params, x):\n", + " # N_hidden is the number of hidden layers\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", + " # parameters to all the hidden\n", + " # layers AND the output layer.\n", + "\n", + " # Assumes input x being an one-dimensional array\n", + " num_values = np.size(x)\n", + " x = x.reshape(-1, num_values)\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + "\n", + " # Due to multiple hidden layers, define a variable referencing to the\n", + " # output of the previous layer:\n", + " x_prev = x_input\n", + "\n", + " ## Hidden layers:\n", + "\n", + " for l in range(N_hidden):\n", + " # From the list of parameters P; find the correct weigths and bias for this layer\n", + " w_hidden = deep_params[l]\n", + "\n", + " # Add a row of ones to include bias\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_prev)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " # Update x_prev such that next layer can use the output from this layer\n", + " x_prev = x_hidden\n", + "\n", + " ## Output layer:\n", + "\n", + " # Get the weights and bias for this layer\n", + " w_output = deep_params[-1]\n", + "\n", + " # Include bias:\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_prev)\n", + " x_output = z_output\n", + "\n", + " return x_output\n", + "\n", + "\n", + "\n", + "\n", + "def cost_function_deep(P, x):\n", + "\n", + " # Evaluate the trial function with the current parameters P\n", + " g_t = g_trial_deep(x,P)\n", + "\n", + " # Find the derivative w.r.t x of the trial function\n", + " d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n", + "\n", + " # The right side of the ODE\n", + " func = f(x, g_t)\n", + "\n", + " err_sqr = (d_g_t - func)**2\n", + " cost_sum = np.sum(err_sqr)\n", + "\n", + " return cost_sum / np.size(err_sqr)\n", + "\n", + "# The right side of the ODE:\n", + "def f(x, g_trial):\n", + " alpha,A, g0 = get_parameters()\n", + " return alpha*g_trial*(A - g_trial)\n", + "\n", + "# The trial solution using the deep neural network:\n", + "def g_trial_deep(x, params):\n", + " alpha,A, g0 = get_parameters()\n", + " return g0 + x*deep_neural_network(params,x)\n", + "\n", + "# The analytical solution:\n", + "def g_analytic(t):\n", + " alpha,A, g0 = get_parameters()\n", + " return A*g0/(g0 + (A - g0)*np.exp(-alpha*A*t))\n", + "\n", + "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", + " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", + "\n", + " # Find the number of hidden layers:\n", + " N_hidden = np.size(num_neurons)\n", + "\n", + " ## Set up initial weigths and biases\n", + "\n", + " # Initialize the list of parameters:\n", + " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", + "\n", + " P[0] = npr.randn(num_neurons[0], 2 )\n", + " for l in range(1,N_hidden):\n", + " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", + "\n", + " # For the output layer\n", + " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", + "\n", + " print('Initial cost: %g'%cost_function_deep(P, x))\n", + "\n", + " ## Start finding the optimal weigths using gradient descent\n", + "\n", + " # Find the Python function that represents the gradient of the cost function\n", + " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", + " cost_function_deep_grad = grad(cost_function_deep,0)\n", + "\n", + " # Let the update be done num_iter times\n", + " for i in range(num_iter):\n", + " # Evaluate the gradient at the current weights and biases in P.\n", + " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", + " # in the hidden layers and output layers evaluated at x.\n", + " cost_deep_grad = cost_function_deep_grad(P, x)\n", + "\n", + " for l in range(N_hidden+1):\n", + " P[l] = P[l] - lmb * cost_deep_grad[l]\n", + "\n", + " print('Final cost: %g'%cost_function_deep(P, x))\n", + "\n", + " return P\n", + "\n", + "if __name__ == '__main__':\n", + " npr.seed(4155)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " Nt = 10\n", + " T = 1\n", + " t = np.linspace(0,T, Nt)\n", + "\n", + " ## Set up the initial parameters\n", + " num_hidden_neurons = [100, 50, 25]\n", + " num_iter = 1000\n", + " lmb = 1e-3\n", + "\n", + " P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " g_dnn_ag = g_trial_deep(t,P)\n", + " g_analytical = g_analytic(t)\n", + "\n", + " # Find the maximum absolute difference between the solutons:\n", + " diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n", + " print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n", + "\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", + " plt.plot(t, g_analytical)\n", + " plt.plot(t, g_dnn_ag[0,:])\n", + " plt.legend(['analytical','nn'])\n", + " plt.xlabel('t')\n", + " plt.ylabel('g(t)')\n", + "\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "2407df1c", + "metadata": { + "editable": true + }, + "source": [ + "## Using forward Euler to solve the ODE\n", + "\n", + "A straightforward way of solving an ODE numerically, is to use Euler's method.\n", + "\n", + "Euler's method uses Taylor series to approximate the value at a function $f$ at a step $\\Delta x$ from $x$:\n", + "\n", + "$$\n", + "f(x + \\Delta x) \\approx f(x) + \\Delta x f'(x)\n", + "$$\n", + "\n", + "In our case, using Euler's method to approximate the value of $g$ at a step $\\Delta t$ from $t$ yields" + ] + }, + { + "cell_type": "markdown", + "id": "e30d9840", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + " g(t + \\Delta t) &\\approx g(t) + \\Delta t g'(t) \\\\\n", + " &= g(t) + \\Delta t \\big(\\alpha g(t)(A - g(t))\\big)\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4af6e338", + "metadata": { + "editable": true + }, + "source": [ + "along with the condition that $g(0) = g_0$.\n", + "\n", + "Let $t_i = i \\cdot \\Delta t$ where $\\Delta t = \\frac{T}{N_t-1}$ where $T$ is the final time our solver must solve for and $N_t$ the number of values for $t \\in [0, T]$ for $i = 0, \\dots, N_t-1$.\n", + "\n", + "For $i \\geq 1$, we have that" + ] + }, + { + "cell_type": "markdown", + "id": "606cf0d3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "t_i &= i\\Delta t \\\\\n", + "&= (i - 1)\\Delta t + \\Delta t \\\\\n", + "&= t_{i-1} + \\Delta t\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3275ea67", + "metadata": { + "editable": true + }, + "source": [ + "Now, if $g_i = g(t_i)$ then" + ] + }, + { + "cell_type": "markdown", + "id": "8c36efec", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\begin{aligned}\n", + " g_i &= g(t_i) \\\\\n", + " &= g(t_{i-1} + \\Delta t) \\\\\n", + " &\\approx g(t_{i-1}) + \\Delta t \\big(\\alpha g(t_{i-1})(A - g(t_{i-1}))\\big) \\\\\n", + " &= g_{i-1} + \\Delta t \\big(\\alpha g_{i-1}(A - g_{i-1})\\big)\n", + " \\end{aligned}\n", + "\\end{equation} \\label{odenum} \\tag{12}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5290cde6", + "metadata": { + "editable": true + }, + "source": [ + "for $i \\geq 1$ and $g_0 = g(t_0) = g(0) = g_0$.\n", + "\n", + "Equation ([12](#odenum)) could be implemented in the following way,\n", + "extending the program that uses the network using Autograd:" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "d5488516", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Assume that all function definitions from the example program using Autograd\n", + "# are located here.\n", + "\n", + "if __name__ == '__main__':\n", + " npr.seed(4155)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " Nt = 10\n", + " T = 1\n", + " t = np.linspace(0,T, Nt)\n", + "\n", + " ## Set up the initial parameters\n", + " num_hidden_neurons = [100,50,25]\n", + " num_iter = 1000\n", + " lmb = 1e-3\n", + "\n", + " P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " g_dnn_ag = g_trial_deep(t,P)\n", + " g_analytical = g_analytic(t)\n", + "\n", + " # Find the maximum absolute difference between the solutons:\n", + " diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n", + " print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n", + "\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", + " plt.plot(t, g_analytical)\n", + " plt.plot(t, g_dnn_ag[0,:])\n", + " plt.legend(['analytical','nn'])\n", + " plt.xlabel('t')\n", + " plt.ylabel('g(t)')\n", + "\n", + " ## Find an approximation to the funtion using forward Euler\n", + "\n", + " alpha, A, g0 = get_parameters()\n", + " dt = T/(Nt - 1)\n", + "\n", + " # Perform forward Euler to solve the ODE\n", + " g_euler = np.zeros(Nt)\n", + " g_euler[0] = g0\n", + "\n", + " for i in range(1,Nt):\n", + " g_euler[i] = g_euler[i-1] + dt*(alpha*g_euler[i-1]*(A - g_euler[i-1]))\n", + "\n", + " # Print the errors done by each method\n", + " diff1 = np.max(np.abs(g_euler - g_analytical))\n", + " diff2 = np.max(np.abs(g_dnn_ag[0,:] - g_analytical))\n", + "\n", + " print('Max absolute difference between Euler method and analytical: %g'%diff1)\n", + " print('Max absolute difference between deep neural network and analytical: %g'%diff2)\n", + "\n", + " # Plot results\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.plot(t,g_euler)\n", + " plt.plot(t,g_analytical)\n", + " plt.plot(t,g_dnn_ag[0,:])\n", + "\n", + " plt.legend(['euler','analytical','dnn'])\n", + " plt.xlabel('Time t')\n", + " plt.ylabel('g(t)')\n", + "\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "d631641d", + "metadata": { + "editable": true + }, + "source": [ + "## Example: Solving the one dimensional Poisson equation\n", + "\n", + "The Poisson equation for $g(x)$ in one dimension is" + ] + }, + { + "cell_type": "markdown", + "id": "3bd8043b", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{poisson} \\tag{13}\n", + " -g''(x) = f(x)\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "818ac1d8", + "metadata": { + "editable": true + }, + "source": [ + "where $f(x)$ is a given function for $x \\in (0,1)$.\n", + "\n", + "The conditions that $g(x)$ is chosen to fulfill, are" + ] + }, + { + "cell_type": "markdown", + "id": "894be116", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{align*}\n", + " g(0) &= 0 \\\\\n", + " g(1) &= 0\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c2fce07f", + "metadata": { + "editable": true + }, + "source": [ + "This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.\n", + "The results from the networks can then be compared to the analytical solution.\n", + "In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks." + ] + }, + { + "cell_type": "markdown", + "id": "1e2ffb5e", + "metadata": { + "editable": true + }, + "source": [ + "## The specific equation to solve for\n", + "\n", + "Here, the function $g(x)$ to solve for follows the equation" + ] + }, + { + "cell_type": "markdown", + "id": "5677eb07", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "-g''(x) = f(x),\\qquad x \\in (0,1)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "89173815", + "metadata": { + "editable": true + }, + "source": [ + "where $f(x)$ is a given function, along with the chosen conditions" + ] + }, + { + "cell_type": "markdown", + "id": "f6e81c01", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "g(0) = g(1) = 0\n", + "\\end{aligned}\\label{cond} \\tag{14}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "82b4c100", + "metadata": { + "editable": true + }, + "source": [ + "In this example, we consider the case when $f(x) = (3x + x^2)\\exp(x)$.\n", + "\n", + "For this case, a possible trial solution satisfying the conditions could be" + ] + }, + { + "cell_type": "markdown", + "id": "05574f7f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "g_t(x) = x \\cdot (1-x) \\cdot N(P,x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5c17a08c", + "metadata": { + "editable": true + }, + "source": [ + "The analytical solution for this problem is" + ] + }, + { + "cell_type": "markdown", + "id": "a0ce240a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "g(x) = x(1 - x)\\exp(x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d90da9be", + "metadata": { + "editable": true + }, + "source": [ + "## Solving the equation using Autograd" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "ffd8b552", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad, elementwise_grad\n", + "import autograd.numpy.random as npr\n", + "from matplotlib import pyplot as plt\n", + "\n", + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "def deep_neural_network(deep_params, x):\n", + " # N_hidden is the number of hidden layers\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", + " # parameters to all the hidden\n", + " # layers AND the output layer.\n", + "\n", + " # Assumes input x being an one-dimensional array\n", + " num_values = np.size(x)\n", + " x = x.reshape(-1, num_values)\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + "\n", + " # Due to multiple hidden layers, define a variable referencing to the\n", + " # output of the previous layer:\n", + " x_prev = x_input\n", + "\n", + " ## Hidden layers:\n", + "\n", + " for l in range(N_hidden):\n", + " # From the list of parameters P; find the correct weigths and bias for this layer\n", + " w_hidden = deep_params[l]\n", + "\n", + " # Add a row of ones to include bias\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_prev)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " # Update x_prev such that next layer can use the output from this layer\n", + " x_prev = x_hidden\n", + "\n", + " ## Output layer:\n", + "\n", + " # Get the weights and bias for this layer\n", + " w_output = deep_params[-1]\n", + "\n", + " # Include bias:\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_prev)\n", + " x_output = z_output\n", + "\n", + " return x_output\n", + "\n", + "\n", + "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", + " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", + "\n", + " # Find the number of hidden layers:\n", + " N_hidden = np.size(num_neurons)\n", + "\n", + " ## Set up initial weigths and biases\n", + "\n", + " # Initialize the list of parameters:\n", + " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", + "\n", + " P[0] = npr.randn(num_neurons[0], 2 )\n", + " for l in range(1,N_hidden):\n", + " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", + "\n", + " # For the output layer\n", + " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", + "\n", + " print('Initial cost: %g'%cost_function_deep(P, x))\n", + "\n", + " ## Start finding the optimal weigths using gradient descent\n", + "\n", + " # Find the Python function that represents the gradient of the cost function\n", + " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", + " cost_function_deep_grad = grad(cost_function_deep,0)\n", + "\n", + " # Let the update be done num_iter times\n", + " for i in range(num_iter):\n", + " # Evaluate the gradient at the current weights and biases in P.\n", + " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", + " # in the hidden layers and output layers evaluated at x.\n", + " cost_deep_grad = cost_function_deep_grad(P, x)\n", + "\n", + " for l in range(N_hidden+1):\n", + " P[l] = P[l] - lmb * cost_deep_grad[l]\n", + "\n", + " print('Final cost: %g'%cost_function_deep(P, x))\n", + "\n", + " return P\n", + "\n", + "## Set up the cost function specified for this Poisson equation:\n", + "\n", + "# The right side of the ODE\n", + "def f(x):\n", + " return (3*x + x**2)*np.exp(x)\n", + "\n", + "def cost_function_deep(P, x):\n", + "\n", + " # Evaluate the trial function with the current parameters P\n", + " g_t = g_trial_deep(x,P)\n", + "\n", + " # Find the derivative w.r.t x of the trial function\n", + " d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n", + "\n", + " right_side = f(x)\n", + "\n", + " err_sqr = (-d2_g_t - right_side)**2\n", + " cost_sum = np.sum(err_sqr)\n", + "\n", + " return cost_sum/np.size(err_sqr)\n", + "\n", + "# The trial solution:\n", + "def g_trial_deep(x,P):\n", + " return x*(1-x)*deep_neural_network(P,x)\n", + "\n", + "# The analytic solution;\n", + "def g_analytic(x):\n", + " return x*(1-x)*np.exp(x)\n", + "\n", + "if __name__ == '__main__':\n", + " npr.seed(4155)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " Nx = 10\n", + " x = np.linspace(0,1, Nx)\n", + "\n", + " ## Set up the initial parameters\n", + " num_hidden_neurons = [200,100]\n", + " num_iter = 1000\n", + " lmb = 1e-3\n", + "\n", + " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " g_dnn_ag = g_trial_deep(x,P)\n", + " g_analytical = g_analytic(x)\n", + "\n", + " # Find the maximum absolute difference between the solutons:\n", + " max_diff = np.max(np.abs(g_dnn_ag - g_analytical))\n", + " print(\"The max absolute difference between the solutions is: %g\"%max_diff)\n", + "\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", + " plt.plot(x, g_analytical)\n", + " plt.plot(x, g_dnn_ag[0,:])\n", + " plt.legend(['analytical','nn'])\n", + " plt.xlabel('x')\n", + " plt.ylabel('g(x)')\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "2cde42e7", + "metadata": { + "editable": true + }, + "source": [ + "## Comparing with a numerical scheme\n", + "\n", + "The Poisson equation is possible to solve using Taylor series to approximate the second derivative.\n", + "\n", + "Using Taylor series, the second derivative can be expressed as\n", + "\n", + "$$\n", + "g''(x) = \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2} + E_{\\Delta x}(x)\n", + "$$\n", + "\n", + "where $\\Delta x$ is a small step size and $E_{\\Delta x}(x)$ being the error term.\n", + "\n", + "Looking away from the error terms gives an approximation to the second derivative:" + ] + }, + { + "cell_type": "markdown", + "id": "e24a46af", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{approx} \\tag{15}\n", + "g''(x) \\approx \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2417ec7c", + "metadata": { + "editable": true + }, + "source": [ + "If $x_i = i \\Delta x = x_{i-1} + \\Delta x$ and $g_i = g(x_i)$ for $i = 1,\\dots N_x - 2$ with $N_x$ being the number of values for $x$, ([15](#approx)) becomes" + ] + }, + { + "cell_type": "markdown", + "id": "012a9c2b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "g''(x_i) &\\approx \\frac{g(x_i + \\Delta x) - 2g(x_i) + g(x_i -\\Delta x)}{\\Delta x^2} \\\\\n", + "&= \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2}\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "101bccb8", + "metadata": { + "editable": true + }, + "source": [ + "Since we know from our problem that" + ] + }, + { + "cell_type": "markdown", + "id": "280cdc54", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "-g''(x) &= f(x) \\\\\n", + "&= (3x + x^2)\\exp(x)\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "38bc9035", + "metadata": { + "editable": true + }, + "source": [ + "along with the conditions $g(0) = g(1) = 0$,\n", + "the following scheme can be used to find an approximate solution for $g(x)$ numerically:" + ] + }, + { + "cell_type": "markdown", + "id": "3925a117", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\begin{aligned}\n", + " -\\Big( \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2} \\Big) &= f(x_i) \\\\\n", + " -g_{i+1} + 2g_i - g_{i-1} &= \\Delta x^2 f(x_i)\n", + " \\end{aligned}\n", + "\\end{equation} \\label{odesys} \\tag{16}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6f86e85b", + "metadata": { + "editable": true + }, + "source": [ + "for $i = 1, \\dots, N_x - 2$ where $g_0 = g_{N_x - 1} = 0$ and $f(x_i) = (3x_i + x_i^2)\\exp(x_i)$, which is given for our specific problem.\n", + "\n", + "The equation can be rewritten into a matrix equation:" + ] + }, + { + "cell_type": "markdown", + "id": "394b14bc", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "\\begin{pmatrix}\n", + "2 & -1 & 0 & \\dots & 0 \\\\\n", + "-1 & 2 & -1 & \\dots & 0 \\\\\n", + "\\vdots & & \\ddots & & \\vdots \\\\\n", + "0 & \\dots & -1 & 2 & -1 \\\\\n", + "0 & \\dots & 0 & -1 & 2\\\\\n", + "\\end{pmatrix}\n", + "\\begin{pmatrix}\n", + "g_1 \\\\\n", + "g_2 \\\\\n", + "\\vdots \\\\\n", + "g_{N_x - 3} \\\\\n", + "g_{N_x - 2}\n", + "\\end{pmatrix}\n", + "&=\n", + "\\Delta x^2\n", + "\\begin{pmatrix}\n", + "f(x_1) \\\\\n", + "f(x_2) \\\\\n", + "\\vdots \\\\\n", + "f(x_{N_x - 3}) \\\\\n", + "f(x_{N_x - 2})\n", + "\\end{pmatrix} \\\\\n", + "\\boldsymbol{A}\\boldsymbol{g} &= \\boldsymbol{f},\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5ab07ae1", + "metadata": { + "editable": true + }, + "source": [ + "which makes it possible to solve for the vector $\\boldsymbol{g}$." + ] + }, + { + "cell_type": "markdown", + "id": "8134c34f", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the code\n", + "\n", + "We can then compare the result from this numerical scheme with the output from our network using Autograd:" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "4362f9a9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad, elementwise_grad\n", + "import autograd.numpy.random as npr\n", + "from matplotlib import pyplot as plt\n", + "\n", + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "def deep_neural_network(deep_params, x):\n", + " # N_hidden is the number of hidden layers\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", + " # parameters to all the hidden\n", + " # layers AND the output layer.\n", + "\n", + " # Assumes input x being an one-dimensional array\n", + " num_values = np.size(x)\n", + " x = x.reshape(-1, num_values)\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + "\n", + " # Due to multiple hidden layers, define a variable referencing to the\n", + " # output of the previous layer:\n", + " x_prev = x_input\n", + "\n", + " ## Hidden layers:\n", + "\n", + " for l in range(N_hidden):\n", + " # From the list of parameters P; find the correct weigths and bias for this layer\n", + " w_hidden = deep_params[l]\n", + "\n", + " # Add a row of ones to include bias\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_prev)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " # Update x_prev such that next layer can use the output from this layer\n", + " x_prev = x_hidden\n", + "\n", + " ## Output layer:\n", + "\n", + " # Get the weights and bias for this layer\n", + " w_output = deep_params[-1]\n", + "\n", + " # Include bias:\n", + " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_prev)\n", + " x_output = z_output\n", + "\n", + " return x_output\n", + "\n", + "\n", + "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", + " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", + "\n", + " # Find the number of hidden layers:\n", + " N_hidden = np.size(num_neurons)\n", + "\n", + " ## Set up initial weigths and biases\n", + "\n", + " # Initialize the list of parameters:\n", + " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", + "\n", + " P[0] = npr.randn(num_neurons[0], 2 )\n", + " for l in range(1,N_hidden):\n", + " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", + "\n", + " # For the output layer\n", + " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", + "\n", + " print('Initial cost: %g'%cost_function_deep(P, x))\n", + "\n", + " ## Start finding the optimal weigths using gradient descent\n", + "\n", + " # Find the Python function that represents the gradient of the cost function\n", + " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", + " cost_function_deep_grad = grad(cost_function_deep,0)\n", + "\n", + " # Let the update be done num_iter times\n", + " for i in range(num_iter):\n", + " # Evaluate the gradient at the current weights and biases in P.\n", + " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", + " # in the hidden layers and output layers evaluated at x.\n", + " cost_deep_grad = cost_function_deep_grad(P, x)\n", + "\n", + " for l in range(N_hidden+1):\n", + " P[l] = P[l] - lmb * cost_deep_grad[l]\n", + "\n", + " print('Final cost: %g'%cost_function_deep(P, x))\n", + "\n", + " return P\n", + "\n", + "## Set up the cost function specified for this Poisson equation:\n", + "\n", + "# The right side of the ODE\n", + "def f(x):\n", + " return (3*x + x**2)*np.exp(x)\n", + "\n", + "def cost_function_deep(P, x):\n", + "\n", + " # Evaluate the trial function with the current parameters P\n", + " g_t = g_trial_deep(x,P)\n", + "\n", + " # Find the derivative w.r.t x of the trial function\n", + " d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n", + "\n", + " right_side = f(x)\n", + "\n", + " err_sqr = (-d2_g_t - right_side)**2\n", + " cost_sum = np.sum(err_sqr)\n", + "\n", + " return cost_sum/np.size(err_sqr)\n", + "\n", + "# The trial solution:\n", + "def g_trial_deep(x,P):\n", + " return x*(1-x)*deep_neural_network(P,x)\n", + "\n", + "# The analytic solution;\n", + "def g_analytic(x):\n", + " return x*(1-x)*np.exp(x)\n", + "\n", + "if __name__ == '__main__':\n", + " npr.seed(4155)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " Nx = 10\n", + " x = np.linspace(0,1, Nx)\n", + "\n", + " ## Set up the initial parameters\n", + " num_hidden_neurons = [200,100]\n", + " num_iter = 1000\n", + " lmb = 1e-3\n", + "\n", + " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " g_dnn_ag = g_trial_deep(x,P)\n", + " g_analytical = g_analytic(x)\n", + "\n", + " # Find the maximum absolute difference between the solutons:\n", + "\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", + " plt.plot(x, g_analytical)\n", + " plt.plot(x, g_dnn_ag[0,:])\n", + " plt.legend(['analytical','nn'])\n", + " plt.xlabel('x')\n", + " plt.ylabel('g(x)')\n", + "\n", + " ## Perform the computation using the numerical scheme\n", + "\n", + " dx = 1/(Nx - 1)\n", + "\n", + " # Set up the matrix A\n", + " A = np.zeros((Nx-2,Nx-2))\n", + "\n", + " A[0,0] = 2\n", + " A[0,1] = -1\n", + "\n", + " for i in range(1,Nx-3):\n", + " A[i,i-1] = -1\n", + " A[i,i] = 2\n", + " A[i,i+1] = -1\n", + "\n", + " A[Nx - 3, Nx - 4] = -1\n", + " A[Nx - 3, Nx - 3] = 2\n", + "\n", + " # Set up the vector f\n", + " f_vec = dx**2 * f(x[1:-1])\n", + "\n", + " # Solve the equation\n", + " g_res = np.linalg.solve(A,f_vec)\n", + "\n", + " g_vec = np.zeros(Nx)\n", + " g_vec[1:-1] = g_res\n", + "\n", + " # Print the differences between each method\n", + " max_diff1 = np.max(np.abs(g_dnn_ag - g_analytical))\n", + " max_diff2 = np.max(np.abs(g_vec - g_analytical))\n", + " print(\"The max absolute difference between the analytical solution and DNN Autograd: %g\"%max_diff1)\n", + " print(\"The max absolute difference between the analytical solution and numerical scheme: %g\"%max_diff2)\n", + "\n", + " # Plot the results\n", + " plt.figure(figsize=(10,10))\n", + "\n", + " plt.plot(x,g_vec)\n", + " plt.plot(x,g_analytical)\n", + " plt.plot(x,g_dnn_ag[0,:])\n", + "\n", + " plt.legend(['numerical scheme','analytical','dnn'])\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c66dc85a", + "metadata": { + "editable": true + }, + "source": [ + "## Partial Differential Equations\n", + "\n", + "A partial differential equation (PDE) has a solution here the function\n", + "is defined by multiple variables. The equation may involve all kinds\n", + "of combinations of which variables the function is differentiated with\n", + "respect to.\n", + "\n", + "In general, a partial differential equation for a function $g(x_1,\\dots,x_N)$ with $N$ variables may be expressed as" + ] + }, + { + "cell_type": "markdown", + "id": "cf60d1fc", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{PDE} \\tag{17}\n", + " f\\left(x_1, \\, \\dots \\, , x_N, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1}, \\dots , \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_N}, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(x_1,\\dots,x_N) }{\\partial x_N^n} \\right) = 0\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "bff85f6e", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "64289867", + "metadata": { + "editable": true + }, + "source": [ + "## Type of problem\n", + "\n", + "The problem our network must solve for, is similar to the ODE case.\n", + "We must have a trial solution $g_t$ at hand.\n", + "\n", + "For instance, the trial solution could be expressed as" + ] + }, + { + "cell_type": "markdown", + "id": "75d3a4d2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{align*}\n", + " g_t(x_1,\\dots,x_N) = h_1(x_1,\\dots,x_N) + h_2(x_1,\\dots,x_N,N(x_1,\\dots,x_N,P))\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6f3e695d", + "metadata": { + "editable": true + }, + "source": [ + "where $h_1(x_1,\\dots,x_N)$ is a function that ensures $g_t(x_1,\\dots,x_N)$ satisfies some given conditions.\n", + "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.\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "da1ba3cf", + "metadata": { + "editable": true + }, + "source": [ + "## Network requirements\n", + "\n", + "The network tries then the minimize the cost function following the\n", + "same ideas as described for the ODE case, but now with more than one\n", + "variables to consider. The concept still remains the same; find a set\n", + "of parameters $P$ such that the expression $f$ in ([17](#PDE)) is as\n", + "close to zero as possible.\n", + "\n", + "As for the ODE case, the cost function is the mean squared error that\n", + "the network must try to minimize. The cost function for the network to\n", + "minimize is" + ] + }, + { + "cell_type": "markdown", + "id": "373065ff", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C\\left(x_1, \\dots, x_N, P\\right) = \\left( f\\left(x_1, \\, \\dots \\, , x_N, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1}, \\dots , \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_N}, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(x_1,\\dots,x_N) }{\\partial x_N^n} \\right) \\right)^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2281eade", + "metadata": { + "editable": true + }, + "source": [ + "## More details\n", + "\n", + "If we let $\\boldsymbol{x} = \\big( x_1, \\dots, x_N \\big)$ be an array containing the values for $x_1, \\dots, x_N$ respectively, the cost function can be reformulated into the following:" + ] + }, + { + "cell_type": "markdown", + "id": "989a8905", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C\\left(\\boldsymbol{x}, P\\right) = f\\left( \\left( \\boldsymbol{x}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}) }{\\partial x_N^n} \\right) \\right)^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b36367a0", + "metadata": { + "editable": true + }, + "source": [ + "If we also have $M$ different sets of values for $x_1, \\dots, x_N$, that is $\\boldsymbol{x}_i = \\big(x_1^{(i)}, \\dots, x_N^{(i)}\\big)$ for $i = 1,\\dots,M$ being the rows in matrix $X$, the cost function can be generalized into" + ] + }, + { + "cell_type": "markdown", + "id": "6f6f51dd", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C\\left(X, P \\right) = \\sum_{i=1}^M f\\left( \\left( \\boldsymbol{x}_i, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}_i) }{\\partial x_N^n} \\right) \\right)^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "35bd1e4a", + "metadata": { + "editable": true + }, + "source": [ + "## Example: The diffusion equation\n", + "\n", + "In one spatial dimension, the equation reads" + ] + }, + { + "cell_type": "markdown", + "id": "2b804c0a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "07f20557", + "metadata": { + "editable": true + }, + "source": [ + "where a possible choice of conditions are" + ] + }, + { + "cell_type": "markdown", + "id": "0e14c702", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{align*}\n", + "g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n", + "g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n", + "g(x,0) &= u(x),\\qquad x\\in [0,1]\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a19c5cae", + "metadata": { + "editable": true + }, + "source": [ + "with $u(x)$ being some given function." + ] + }, + { + "cell_type": "markdown", + "id": "de041a40", + "metadata": { + "editable": true + }, + "source": [ + "## Defining the problem\n", + "\n", + "For this case, we want to find $g(x,t)$ such that" + ] + }, + { + "cell_type": "markdown", + "id": "519bb7a7", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", + "\\end{equation} \\label{diffonedim} \\tag{18}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "129322ea", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "ddc7b725", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{align*}\n", + "g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n", + "g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n", + "g(x,0) &= u(x),\\qquad x\\in [0,1]\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5497b34b", + "metadata": { + "editable": true + }, + "source": [ + "with $u(x) = \\sin(\\pi x)$.\n", + "\n", + "First, let us set up the deep neural network.\n", + "The deep neural network will follow the same structure as discussed in the examples solving the ODEs.\n", + "First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions." + ] + }, + { + "cell_type": "markdown", + "id": "0b9040e4", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the network using Autograd\n", + "\n", + "The only change to do here, is to extend our network such that\n", + "functions of multiple parameters are correctly handled. In this case\n", + "we have two variables in our function to solve for, that is time $t$\n", + "and position $x$. The variables will be represented by a\n", + "one-dimensional array in the program. The program will evaluate the\n", + "network at each possible pair $(x,t)$, given an array for the desired\n", + "$x$-values and $t$-values to approximate the solution at." + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "17097802", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "def deep_neural_network(deep_params, x):\n", + " # x is now a point and a 1D numpy array; make it a column vector\n", + " num_coordinates = np.size(x,0)\n", + " x = x.reshape(num_coordinates,-1)\n", + "\n", + " num_points = np.size(x,1)\n", + "\n", + " # N_hidden is the number of hidden layers\n", + " N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + " x_prev = x_input\n", + "\n", + " ## Hidden layers:\n", + "\n", + " for l in range(N_hidden):\n", + " # From the list of parameters P; find the correct weigths and bias for this layer\n", + " w_hidden = deep_params[l]\n", + "\n", + " # Add a row of ones to include bias\n", + " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_prev)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " # Update x_prev such that next layer can use the output from this layer\n", + " x_prev = x_hidden\n", + "\n", + " ## Output layer:\n", + "\n", + " # Get the weights and bias for this layer\n", + " w_output = deep_params[-1]\n", + "\n", + " # Include bias:\n", + " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_prev)\n", + " x_output = z_output\n", + "\n", + " return x_output[0][0]" + ] + }, + { + "cell_type": "markdown", + "id": "a2178b56", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the network using Autograd; The trial solution\n", + "\n", + "The cost function must then iterate through the given arrays\n", + "containing values for $x$ and $t$, defines a point $(x,t)$ the deep\n", + "neural network and the trial solution is evaluated at, and then finds\n", + "the Jacobian of the trial solution.\n", + "\n", + "A possible trial solution for this PDE is\n", + "\n", + "$$\n", + "g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P)\n", + "$$\n", + "\n", + "with $A(x,t)$ being a function ensuring that $g_t(x,t)$ satisfies our given conditions, and $N(x,t,P)$ being the output from the deep neural network using weights and biases for each layer from $P$.\n", + "\n", + "To fulfill the conditions, $A(x,t)$ could be:\n", + "\n", + "$$\n", + "h_1(x,t) = (1-t)\\Big(u(x) - \\big((1-x)u(0) + x u(1)\\big)\\Big) = (1-t)u(x) = (1-t)\\sin(\\pi x)\n", + "$$\n", + "since $(0) = u(1) = 0$ and $u(x) = \\sin(\\pi x)$." + ] + }, + { + "cell_type": "markdown", + "id": "533f4e84", + "metadata": { + "editable": true + }, + "source": [ + "## Why the jacobian?\n", + "\n", + "The Jacobian is used because the program must find the derivative of\n", + "the trial solution with respect to $x$ and $t$.\n", + "\n", + "This gives the necessity of computing the Jacobian matrix, as we want\n", + "to evaluate the gradient with respect to $x$ and $t$ (note that the\n", + "Jacobian of a scalar-valued multivariate function is simply its\n", + "gradient).\n", + "\n", + "In Autograd, the differentiation is by default done with respect to\n", + "the first input argument of your Python function. Since the points is\n", + "an array representing $x$ and $t$, the Jacobian is calculated using\n", + "the values of $x$ and $t$.\n", + "\n", + "To find the second derivative with respect to $x$ and $t$, the\n", + "Jacobian can be found for the second time. The result is a Hessian\n", + "matrix, which is the matrix containing all the possible second order\n", + "mixed derivatives of $g(x,t)$." + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "7b494481", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Set up the trial function:\n", + "def u(x):\n", + " return np.sin(np.pi*x)\n", + "\n", + "def g_trial(point,P):\n", + " x,t = point\n", + " return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n", + "\n", + "# The right side of the ODE:\n", + "def f(point):\n", + " return 0.\n", + "\n", + "# The cost function:\n", + "def cost_function(P, x, t):\n", + " cost_sum = 0\n", + "\n", + " g_t_jacobian_func = jacobian(g_trial)\n", + " g_t_hessian_func = hessian(g_trial)\n", + "\n", + " for x_ in x:\n", + " for t_ in t:\n", + " point = np.array([x_,t_])\n", + "\n", + " g_t = g_trial(point,P)\n", + " g_t_jacobian = g_t_jacobian_func(point,P)\n", + " g_t_hessian = g_t_hessian_func(point,P)\n", + "\n", + " g_t_dt = g_t_jacobian[1]\n", + " g_t_d2x = g_t_hessian[0][0]\n", + "\n", + " func = f(point)\n", + "\n", + " err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n", + " cost_sum += err_sqr\n", + "\n", + " return cost_sum" + ] + }, + { + "cell_type": "markdown", + "id": "9f4b4939", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the network using Autograd; The full program\n", + "\n", + "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.\n", + "\n", + "The analytical solution of our problem is\n", + "\n", + "$$\n", + "g(x,t) = \\exp(-\\pi^2 t)\\sin(\\pi x)\n", + "$$\n", + "\n", + "A possible way to implement a neural network solving the PDE, is given below.\n", + "Be aware, though, that it is fairly slow for the parameters used.\n", + "A better result is possible, but requires more iterations, and thus longer time to complete.\n", + "\n", + "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.\n", + "Using TensorFlow results in a much better execution time. Try it!" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "83d6eb7d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import jacobian,hessian,grad\n", + "import autograd.numpy.random as npr\n", + "from matplotlib import cm\n", + "from matplotlib import pyplot as plt\n", + "from mpl_toolkits.mplot3d import axes3d\n", + "\n", + "## Set up the network\n", + "\n", + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "def deep_neural_network(deep_params, x):\n", + " # x is now a point and a 1D numpy array; make it a column vector\n", + " num_coordinates = np.size(x,0)\n", + " x = x.reshape(num_coordinates,-1)\n", + "\n", + " num_points = np.size(x,1)\n", + "\n", + " # N_hidden is the number of hidden layers\n", + " N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + " x_prev = x_input\n", + "\n", + " ## Hidden layers:\n", + "\n", + " for l in range(N_hidden):\n", + " # From the list of parameters P; find the correct weigths and bias for this layer\n", + " w_hidden = deep_params[l]\n", + "\n", + " # Add a row of ones to include bias\n", + " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_prev)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " # Update x_prev such that next layer can use the output from this layer\n", + " x_prev = x_hidden\n", + "\n", + " ## Output layer:\n", + "\n", + " # Get the weights and bias for this layer\n", + " w_output = deep_params[-1]\n", + "\n", + " # Include bias:\n", + " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_prev)\n", + " x_output = z_output\n", + "\n", + " return x_output[0][0]\n", + "\n", + "## Define the trial solution and cost function\n", + "def u(x):\n", + " return np.sin(np.pi*x)\n", + "\n", + "def g_trial(point,P):\n", + " x,t = point\n", + " return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n", + "\n", + "# The right side of the ODE:\n", + "def f(point):\n", + " return 0.\n", + "\n", + "# The cost function:\n", + "def cost_function(P, x, t):\n", + " cost_sum = 0\n", + "\n", + " g_t_jacobian_func = jacobian(g_trial)\n", + " g_t_hessian_func = hessian(g_trial)\n", + "\n", + " for x_ in x:\n", + " for t_ in t:\n", + " point = np.array([x_,t_])\n", + "\n", + " g_t = g_trial(point,P)\n", + " g_t_jacobian = g_t_jacobian_func(point,P)\n", + " g_t_hessian = g_t_hessian_func(point,P)\n", + "\n", + " g_t_dt = g_t_jacobian[1]\n", + " g_t_d2x = g_t_hessian[0][0]\n", + "\n", + " func = f(point)\n", + "\n", + " err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n", + " cost_sum += err_sqr\n", + "\n", + " return cost_sum /( np.size(x)*np.size(t) )\n", + "\n", + "## For comparison, define the analytical solution\n", + "def g_analytic(point):\n", + " x,t = point\n", + " return np.exp(-np.pi**2*t)*np.sin(np.pi*x)\n", + "\n", + "## Set up a function for training the network to solve for the equation\n", + "def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n", + " ## Set up initial weigths and biases\n", + " N_hidden = np.size(num_neurons)\n", + "\n", + " ## Set up initial weigths and biases\n", + "\n", + " # Initialize the list of parameters:\n", + " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", + "\n", + " P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n", + " for l in range(1,N_hidden):\n", + " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", + "\n", + " # For the output layer\n", + " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", + "\n", + " print('Initial cost: ',cost_function(P, x, t))\n", + "\n", + " cost_function_grad = grad(cost_function,0)\n", + "\n", + " # Let the update be done num_iter times\n", + " for i in range(num_iter):\n", + " cost_grad = cost_function_grad(P, x , t)\n", + "\n", + " for l in range(N_hidden+1):\n", + " P[l] = P[l] - lmb * cost_grad[l]\n", + "\n", + " print('Final cost: ',cost_function(P, x, t))\n", + "\n", + " return P\n", + "\n", + "if __name__ == '__main__':\n", + " ### Use the neural network:\n", + " npr.seed(15)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " Nx = 10; Nt = 10\n", + " x = np.linspace(0, 1, Nx)\n", + " t = np.linspace(0,1,Nt)\n", + "\n", + " ## Set up the parameters for the network\n", + " num_hidden_neurons = [100, 25]\n", + " num_iter = 250\n", + " lmb = 0.01\n", + "\n", + " P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " ## Store the results\n", + " g_dnn_ag = np.zeros((Nx, Nt))\n", + " G_analytical = np.zeros((Nx, Nt))\n", + " for i,x_ in enumerate(x):\n", + " for j, t_ in enumerate(t):\n", + " point = np.array([x_, t_])\n", + " g_dnn_ag[i,j] = g_trial(point,P)\n", + "\n", + " G_analytical[i,j] = g_analytic(point)\n", + "\n", + " # Find the map difference between the analytical and the computed solution\n", + " diff_ag = np.abs(g_dnn_ag - G_analytical)\n", + " print('Max absolute difference between the analytical solution and the network: %g'%np.max(diff_ag))\n", + "\n", + " ## Plot the solutions in two dimensions, that being in position and time\n", + "\n", + " T,X = np.meshgrid(t,x)\n", + "\n", + " fig = plt.figure(figsize=(10,10))\n", + " ax = fig.add_suplot(projection='3d')\n", + " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n", + " s = ax.plot_surface(T,X,g_dnn_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n", + " ax.set_xlabel('Time $t$')\n", + " ax.set_ylabel('Position $x$');\n", + "\n", + "\n", + " fig = plt.figure(figsize=(10,10))\n", + " ax = fig.add_suplot(projection='3d')\n", + " ax.set_title('Analytical solution')\n", + " s = ax.plot_surface(T,X,G_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n", + " ax.set_xlabel('Time $t$')\n", + " ax.set_ylabel('Position $x$');\n", + "\n", + " fig = plt.figure(figsize=(10,10))\n", + " ax = fig.add_suplot(projection='3d')\n", + " ax.set_title('Difference')\n", + " s = ax.plot_surface(T,X,diff_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n", + " ax.set_xlabel('Time $t$')\n", + " ax.set_ylabel('Position $x$');\n", + "\n", + " ## Take some slices of the 3D plots just to see the solutions at particular times\n", + " indx1 = 0\n", + " indx2 = int(Nt/2)\n", + " indx3 = Nt-1\n", + "\n", + " t1 = t[indx1]\n", + " t2 = t[indx2]\n", + " t3 = t[indx3]\n", + "\n", + " # Slice the results from the DNN\n", + " res1 = g_dnn_ag[:,indx1]\n", + " res2 = g_dnn_ag[:,indx2]\n", + " res3 = g_dnn_ag[:,indx3]\n", + "\n", + " # Slice the analytical results\n", + " res_analytical1 = G_analytical[:,indx1]\n", + " res_analytical2 = G_analytical[:,indx2]\n", + " res_analytical3 = G_analytical[:,indx3]\n", + "\n", + " # Plot the slices\n", + " plt.figure(figsize=(10,10))\n", + " plt.title(\"Computed solutions at time = %g\"%t1)\n", + " plt.plot(x, res1)\n", + " plt.plot(x,res_analytical1)\n", + " plt.legend(['dnn','analytical'])\n", + "\n", + " plt.figure(figsize=(10,10))\n", + " plt.title(\"Computed solutions at time = %g\"%t2)\n", + " plt.plot(x, res2)\n", + " plt.plot(x,res_analytical2)\n", + " plt.legend(['dnn','analytical'])\n", + "\n", + " plt.figure(figsize=(10,10))\n", + " plt.title(\"Computed solutions at time = %g\"%t3)\n", + " plt.plot(x, res3)\n", + " plt.plot(x,res_analytical3)\n", + " plt.legend(['dnn','analytical'])\n", + "\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "ada13a48", + "metadata": { + "editable": true + }, + "source": [ + "## Example: Solving the wave equation with Neural Networks\n", + "\n", + "The wave equation is" + ] + }, + { + "cell_type": "markdown", + "id": "e4727d73", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2\\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0b86d555", + "metadata": { + "editable": true + }, + "source": [ + "with $c$ being the specified wave speed.\n", + "\n", + "Here, the chosen conditions are" + ] + }, + { + "cell_type": "markdown", + "id": "216948d5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{align*}\n", + "\tg(0,t) &= 0 \\\\\n", + "\tg(1,t) &= 0 \\\\\n", + "\tg(x,0) &= u(x) \\\\\n", + "\t\\frac{\\partial g(x,t)}{\\partial t} \\Big |_{t = 0} &= v(x)\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "44c25fdc", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "98f919eb", + "metadata": { + "editable": true + }, + "source": [ + "## The problem to solve for\n", + "\n", + "The wave equation to solve for, is" + ] + }, + { + "cell_type": "markdown", + "id": "01299767", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \\label{wave} \\tag{19}\n", + "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2 \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "556587c5", + "metadata": { + "editable": true + }, + "source": [ + "where $c$ is the given wave speed.\n", + "The chosen conditions for this equation are" + ] + }, + { + "cell_type": "markdown", + "id": "c9eb4f3a", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "g(0,t) &= 0, &t \\geq 0 \\\\\n", + "g(1,t) &= 0, &t \\geq 0 \\\\\n", + "g(x,0) &= u(x), &x\\in[0,1] \\\\\n", + "\\frac{\\partial g(x,t)}{\\partial t}\\Big |_{t = 0} &= v(x), &x \\in [0,1]\n", + "\\end{aligned} \\label{condwave} \\tag{20}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "63128ef6", + "metadata": { + "editable": true + }, + "source": [ + "In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$." + ] + }, + { + "cell_type": "markdown", + "id": "ff568c81", + "metadata": { + "editable": true + }, + "source": [ + "## The trial solution\n", + "Setting up the network is done in similar matter as for the example of solving the diffusion equation.\n", + "The only things we have to change, is the trial solution such that it satisfies the conditions from ([20](#condwave)) and the cost function.\n", + "\n", + "The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution $g_t(x,t)$ is\n", + "\n", + "$$\n", + "g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P)\n", + "$$\n", + "\n", + "where\n", + "\n", + "$$\n", + "h_1(x,t) = (1-t^2)u(x) + tv(x)\n", + "$$\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "7b32c8dd", + "metadata": { + "editable": true + }, + "source": [ + "## The analytical solution\n", + "\n", + "The analytical solution for our specific problem, is\n", + "\n", + "$$\n", + "g(x,t) = \\sin(\\pi x)\\cos(\\pi t) - \\sin(\\pi x)\\sin(\\pi t)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "fc33e683", + "metadata": { + "editable": true + }, + "source": [ + "## Solving the wave equation - the full program using Autograd" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "2f923958", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import hessian,grad\n", + "import autograd.numpy.random as npr\n", + "from matplotlib import cm\n", + "from matplotlib import pyplot as plt\n", + "from mpl_toolkits.mplot3d import axes3d\n", + "\n", + "## Set up the trial function:\n", + "def u(x):\n", + " return np.sin(np.pi*x)\n", + "\n", + "def v(x):\n", + " return -np.pi*np.sin(np.pi*x)\n", + "\n", + "def h1(point):\n", + " x,t = point\n", + " return (1 - t**2)*u(x) + t*v(x)\n", + "\n", + "def g_trial(point,P):\n", + " x,t = point\n", + " return h1(point) + x*(1-x)*t**2*deep_neural_network(P,point)\n", + "\n", + "## Define the cost function\n", + "def cost_function(P, x, t):\n", + " cost_sum = 0\n", + "\n", + " g_t_hessian_func = hessian(g_trial)\n", + "\n", + " for x_ in x:\n", + " for t_ in t:\n", + " point = np.array([x_,t_])\n", + "\n", + " g_t_hessian = g_t_hessian_func(point,P)\n", + "\n", + " g_t_d2x = g_t_hessian[0][0]\n", + " g_t_d2t = g_t_hessian[1][1]\n", + "\n", + " err_sqr = ( (g_t_d2t - g_t_d2x) )**2\n", + " cost_sum += err_sqr\n", + "\n", + " return cost_sum / (np.size(t) * np.size(x))\n", + "\n", + "## The neural network\n", + "def sigmoid(z):\n", + " return 1/(1 + np.exp(-z))\n", + "\n", + "def deep_neural_network(deep_params, x):\n", + " # x is now a point and a 1D numpy array; make it a column vector\n", + " num_coordinates = np.size(x,0)\n", + " x = x.reshape(num_coordinates,-1)\n", + "\n", + " num_points = np.size(x,1)\n", + "\n", + " # N_hidden is the number of hidden layers\n", + " N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + "\n", + " # Assume that the input layer does nothing to the input x\n", + " x_input = x\n", + " x_prev = x_input\n", + "\n", + " ## Hidden layers:\n", + "\n", + " for l in range(N_hidden):\n", + " # From the list of parameters P; find the correct weigths and bias for this layer\n", + " w_hidden = deep_params[l]\n", + "\n", + " # Add a row of ones to include bias\n", + " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n", + "\n", + " z_hidden = np.matmul(w_hidden, x_prev)\n", + " x_hidden = sigmoid(z_hidden)\n", + "\n", + " # Update x_prev such that next layer can use the output from this layer\n", + " x_prev = x_hidden\n", + "\n", + " ## Output layer:\n", + "\n", + " # Get the weights and bias for this layer\n", + " w_output = deep_params[-1]\n", + "\n", + " # Include bias:\n", + " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n", + "\n", + " z_output = np.matmul(w_output, x_prev)\n", + " x_output = z_output\n", + "\n", + " return x_output[0][0]\n", + "\n", + "## The analytical solution\n", + "def g_analytic(point):\n", + " x,t = point\n", + " return np.sin(np.pi*x)*np.cos(np.pi*t) - np.sin(np.pi*x)*np.sin(np.pi*t)\n", + "\n", + "def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n", + " ## Set up initial weigths and biases\n", + " N_hidden = np.size(num_neurons)\n", + "\n", + " ## Set up initial weigths and biases\n", + "\n", + " # Initialize the list of parameters:\n", + " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", + "\n", + " P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n", + " for l in range(1,N_hidden):\n", + " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", + "\n", + " # For the output layer\n", + " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", + "\n", + " print('Initial cost: ',cost_function(P, x, t))\n", + "\n", + " cost_function_grad = grad(cost_function,0)\n", + "\n", + " # Let the update be done num_iter times\n", + " for i in range(num_iter):\n", + " cost_grad = cost_function_grad(P, x , t)\n", + "\n", + " for l in range(N_hidden+1):\n", + " P[l] = P[l] - lmb * cost_grad[l]\n", + "\n", + "\n", + " print('Final cost: ',cost_function(P, x, t))\n", + "\n", + " return P\n", + "\n", + "if __name__ == '__main__':\n", + " ### Use the neural network:\n", + " npr.seed(15)\n", + "\n", + " ## Decide the vales of arguments to the function to solve\n", + " Nx = 10; Nt = 10\n", + " x = np.linspace(0, 1, Nx)\n", + " t = np.linspace(0,1,Nt)\n", + "\n", + " ## Set up the parameters for the network\n", + " num_hidden_neurons = [50,20]\n", + " num_iter = 1000\n", + " lmb = 0.01\n", + "\n", + " P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n", + "\n", + " ## Store the results\n", + " res = np.zeros((Nx, Nt))\n", + " res_analytical = np.zeros((Nx, Nt))\n", + " for i,x_ in enumerate(x):\n", + " for j, t_ in enumerate(t):\n", + " point = np.array([x_, t_])\n", + " res[i,j] = g_trial(point,P)\n", + "\n", + " res_analytical[i,j] = g_analytic(point)\n", + "\n", + " diff = np.abs(res - res_analytical)\n", + " print(\"Max difference between analytical and solution from nn: %g\"%np.max(diff))\n", + "\n", + " ## Plot the solutions in two dimensions, that being in position and time\n", + "\n", + " T,X = np.meshgrid(t,x)\n", + "\n", + " fig = plt.figure(figsize=(10,10))\n", + " ax = fig.add_suplot(projection='3d')\n", + " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n", + " s = ax.plot_surface(T,X,res,linewidth=0,antialiased=False,cmap=cm.viridis)\n", + " ax.set_xlabel('Time $t$')\n", + " ax.set_ylabel('Position $x$');\n", + "\n", + "\n", + " fig = plt.figure(figsize=(10,10))\n", + " ax = fig.add_suplot(projection='3d')\n", + " ax.set_title('Analytical solution')\n", + " s = ax.plot_surface(T,X,res_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n", + " ax.set_xlabel('Time $t$')\n", + " ax.set_ylabel('Position $x$');\n", + "\n", + "\n", + " fig = plt.figure(figsize=(10,10))\n", + " ax = fig.add_suplot(projection='3d')\n", + " ax.set_title('Difference')\n", + " s = ax.plot_surface(T,X,diff,linewidth=0,antialiased=False,cmap=cm.viridis)\n", + " ax.set_xlabel('Time $t$')\n", + " ax.set_ylabel('Position $x$');\n", + "\n", + " ## Take some slices of the 3D plots just to see the solutions at particular times\n", + " indx1 = 0\n", + " indx2 = int(Nt/2)\n", + " indx3 = Nt-1\n", + "\n", + " t1 = t[indx1]\n", + " t2 = t[indx2]\n", + " t3 = t[indx3]\n", + "\n", + " # Slice the results from the DNN\n", + " res1 = res[:,indx1]\n", + " res2 = res[:,indx2]\n", + " res3 = res[:,indx3]\n", + "\n", + " # Slice the analytical results\n", + " res_analytical1 = res_analytical[:,indx1]\n", + " res_analytical2 = res_analytical[:,indx2]\n", + " res_analytical3 = res_analytical[:,indx3]\n", + "\n", + " # Plot the slices\n", + " plt.figure(figsize=(10,10))\n", + " plt.title(\"Computed solutions at time = %g\"%t1)\n", + " plt.plot(x, res1)\n", + " plt.plot(x,res_analytical1)\n", + " plt.legend(['dnn','analytical'])\n", + "\n", + " plt.figure(figsize=(10,10))\n", + " plt.title(\"Computed solutions at time = %g\"%t2)\n", + " plt.plot(x, res2)\n", + " plt.plot(x,res_analytical2)\n", + " plt.legend(['dnn','analytical'])\n", + "\n", + " plt.figure(figsize=(10,10))\n", + " plt.title(\"Computed solutions at time = %g\"%t3)\n", + " plt.plot(x, res3)\n", + " plt.plot(x,res_analytical3)\n", + " plt.legend(['dnn','analytical'])\n", + "\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "95dea76f", + "metadata": { + "editable": true + }, + "source": [ + "## Resources on differential equations and deep learning\n", + "\n", + "1. [Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al](https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf)\n", + "\n", + "2. [Neural networks for solving differential equations by A. Honchar](https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c)\n", + "\n", + "3. [Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener](http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf)\n", + "\n", + "4. [Introduction to Partial Differential Equations by A. Tveito, R. Winther](https://www.springer.com/us/book/9783540225515)" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/LectureNotes/_build/html/chapter1.html b/doc/LectureNotes/_build/html/chapter1.html index 97d9d2466..d8a8b2f91 100644 --- a/doc/LectureNotes/_build/html/chapter1.html +++ b/doc/LectureNotes/_build/html/chapter1.html @@ -257,6 +257,9 @@ +
  • Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations
  • +
  • Exercises week 43
  • +

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    Projects

    -
    -

    Setting up a Multi-layer perceptron model for classification

    - -

    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 -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. -

    - -

    In binary classification with two classes \( (0, 1) \) we define the -logistic/sigmoid function as the probability that a particular input -is in class \( 0 \) or \( 1 \). This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. -

    - -

    For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) -is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) -represents our activation values \( z \). We have -

    -

     
    -$$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , -$$ -

     
    - -

    and

    -

     
    -$$ -P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , -$$ -

     
    - -

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. -

    -
    - -
    -

    Defining the cost function

    - -

    Our cost function is given as (see the Logistic regression lectures)

    -

     
    -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . -$$ -

     
    - -

    This last equality means that we can interpret our cost function as a sum over the loss function -for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    \( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

    - -\( y = 1 \quad \rightarrow \quad \boldsymbol{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 \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th -output vector \( \boldsymbol{y}_i \). -The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: -

    - -

     
    -$$ -P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , -$$ -

     
    - -

    which reduces to the logistic function in the binary case. -The likelihood of this \( C \)-class classifier -is now given as: -

    - -

     
    -$$ -P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -$$ -

     
    - -

    Again we take the negative log-likelihood to define our cost function:

    - -

     
    -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. -$$ -

     
    - -

    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

    -

     
    -$$ -\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), -$$ -

     
    - -

    where we had defined the logistic (sigmoid) function

    -

     
    -$$ -p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, -$$ -

     
    - -

    and

    -

     
    -$$ -p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). -$$ -

     
    - -

    The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

    - -

    Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). -We have then -

    -

     
    -$$ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -$$ -

     
    - -

    with

    -

     
    -$$ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -$$ -

     
    - -

    where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). -Our cost function at the final layer \( l=L \) is now -

    -

     
    -$$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -$$ -

     
    - -

    where we have defined the targets \( t_i \). The derivatives of the cost function with respect to the output \( a_i^L \) are then easily calculated and we get

    -

     
    -$$ -\frac{\partial \mathcal{C}(\boldsymbol{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.

    -
    - -
    -

    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

    -

     
    -$$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -$$ -

     
    - -

    For the Softmax function we have

    -

     
    -$$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -$$ -

     
    - -

    Its derivative with respect to \( z_j^l \) gives

    -

     
    -$$ -\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 \).

    -
    - -
    -

    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
    2. - -

    3. Define model and architecture
    4. - -

    5. Choose cost function and optimizer
    6. - -

    7. Train the model
    8. - -

    9. Evaluate model performance on test data
    10. - -

    11. Adjust hyperparameters (if necessary, network architecture)
    12. -
    -
    - -
    -

    Collect and pre-process data

    - -

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

    - -

    To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

    - -

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

    - -

     
    -$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

     
    -

    - -

    and the targets would be:

    - -

     
    -$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ -

     

    - -

    Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

    - - - -
    -
    -
    -
    -
    -
    # 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
    -%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
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Train and test datasets

    - -

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    - -

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    - -

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -
    -# 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)
    -
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    -
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    -
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Define model and architecture

    - -

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    - -

     
    -$$ z = \sum_{i=1}^n w_i a_i ,$$ -

     

    - -

     
    -$$ y = f(z) ,$$ -

     

    - -

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

    - -

    The simplest activation function for a neuron is the Heaviside function:

    - -

     
    -$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

     
    -

    - -

    A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

    - -

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

    - -

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

    - -

     
    -$$ 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
    • -
    -

    -

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    - -
      -

    • Hidden layer
    • -
    -

    -

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

    - -
      -

    • Output
    • -
    -

    -

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

    - -

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    - -

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    - -

     
    -$$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

     
    -

    - -

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

    - -

     
    -$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ -

     

    - -

    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. -

    -
    - -
    -

    Weights and biases

    - -

    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. -

    - -

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

    - -

     
    -$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ -

     

    - -

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    - - -
    -
    -
    -
    -
    -
    # building our neural network
    -
    -n_inputs, n_features = X_train.shape
    -n_hidden_neurons = 50
    -n_categories = 10
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Feed-forward pass

    - -

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

    - -

     
    -$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ -

     

    - -

    this is then passed through our activation function

    - -

     
    -$$ a_{j}^{l} = f(z_{j}^{l}) .$$ -

     

    - -

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    - -

     
    -$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ -

     

    - -

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    - -

     
    -$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

     
    -

    -
    - -
    -

    Matrix multiplications

    - -

    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}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

    - -

     
    -$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ -

     

    - -

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

    - -

     
    -$$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$ -

     

    - -

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

    - -

     
    -$$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$ -

     

    - -

    This is fed to the output layer:

    - -

     
    -$$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$ -

     

    - -

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    - -

     
    -$$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$ -

     

    - - - -
    -
    -
    -
    -
    -
    # setup the feed-forward pass, subscript h = hidden layer
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    return probabilities
    -
    -probabilities = feed_forward(X_train)
    -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    -print("probabilities sum up to: " + str(probabilities[0].sum()))
    -print()
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -predictions = predict(X_train)
    -print("predictions = (n_inputs) = " + str(predictions.shape))
    -print("prediction for image 0: " + str(predictions[0]))
    -print("correct label for image 0: " + str(Y_train[0]))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Choose cost function and optimizer

    - -

    To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

     
    -$$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ -

     

    - -

     
    -$$ y = 1 \quad \rightarrow \quad \boldsymbol{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. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

    - -

    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 \( \boldsymbol{\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 -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 local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

    - -

     
    -$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ -

     

    - -

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

    - -

    A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

    - -

     
    -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

     
    -

    - -

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    - -

    This has two important benefits:

    -
      -

    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. - -

    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. -
    -

    -

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    -
    - -
    -

    Regularization

    - -

    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. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

    - -

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    - -

     
    -$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

     
    -

    - -

    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 -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -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. -

    -
    - -
    -

    Matrix multiplication

    - -

    To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

    - -

     
    -$$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ -

     

    - -

    The gradient for the output weights is calculated as

    - -

     
    -$$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ -

     

    - -

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

    - -

    The gradient with respect to the output bias is then

    - -

     
    -$$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ -

     

    - -

    The error in the hidden layer is

    - -

     
    -$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ -

     

    - -

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

    - -

    This again gives us the gradients in the hidden layer:

    - -

     
    -$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ -

     

    - -

     
    -$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ -

     

    - - - -
    -
    -
    -
    -
    -
    # to categorical turns our integer vector into a onehot representation
    -from sklearn.metrics import accuracy_score
    -
    -# one-hot in numpy
    -def to_categorical_numpy(integer_vector):
    -    n_inputs = len(integer_vector)
    -    n_categories = np.max(integer_vector) + 1
    -    onehot_vector = np.zeros((n_inputs, n_categories))
    -    onehot_vector[range(n_inputs), integer_vector] = 1
    -    
    -    return onehot_vector
    -
    -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    -
    -def feed_forward_train(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    # for backpropagation need activations in hidden and output layers
    -    return a_h, probabilities
    -
    -def backpropagation(X, Y):
    -    a_h, probabilities = feed_forward_train(X)
    -    
    -    # error in the output layer
    -    error_output = probabilities - Y
    -    # error in the hidden layer
    -    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    -    
    -    # gradients for the output layer
    -    output_weights_gradient = np.matmul(a_h.T, error_output)
    -    output_bias_gradient = np.sum(error_output, axis=0)
    -    
    -    # gradient for the hidden layer
    -    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    -    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    -
    -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -eta = 0.01
    -lmbd = 0.01
    -for i in range(1000):
    -    # calculate gradients
    -    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    -    
    -    # regularization term gradients
    -    dWo += lmbd * output_weights
    -    dWh += lmbd * hidden_weights
    -    
    -    # update weights and biases
    -    output_weights -= eta * dWo
    -    output_bias -= eta * dBo
    -    hidden_weights -= eta * dWh
    -    hidden_bias -= eta * dBh
    -
    -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Improving performance

    - -

    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. -In order to obtain a network that does something useful, we will have to do a bit more work. -

    - -

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    - -

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

    - -

    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. You can find a summary of the video here. -

    -
    - -
    -

    Full object-oriented implementation

    - -

    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. -

    - - - -
    -
    -
    -
    -
    -
    class NeuralNetwork:
    -    def __init__(
    -            self,
    -            X_data,
    -            Y_data,
    -            n_hidden_neurons=50,
    -            n_categories=10,
    -            epochs=10,
    -            batch_size=100,
    -            eta=0.1,
    -            lmbd=0.0):
    -
    -        self.X_data_full = X_data
    -        self.Y_data_full = Y_data
    -
    -        self.n_inputs = X_data.shape[0]
    -        self.n_features = X_data.shape[1]
    -        self.n_hidden_neurons = n_hidden_neurons
    -        self.n_categories = n_categories
    -
    -        self.epochs = epochs
    -        self.batch_size = batch_size
    -        self.iterations = self.n_inputs // self.batch_size
    -        self.eta = eta
    -        self.lmbd = lmbd
    -
    -        self.create_biases_and_weights()
    -
    -    def create_biases_and_weights(self):
    -        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    -        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    -
    -        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    -        self.output_bias = np.zeros(self.n_categories) + 0.01
    -
    -    def feed_forward(self):
    -        # feed-forward for training
    -        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    -        self.a_h = sigmoid(self.z_h)
    -
    -        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    -
    -        exp_term = np.exp(self.z_o)
    -        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -
    -    def feed_forward_out(self, X):
    -        # feed-forward for output
    -        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    -        a_h = sigmoid(z_h)
    -
    -        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    -        
    -        exp_term = np.exp(z_o)
    -        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -        return probabilities
    -
    -    def backpropagation(self):
    -        error_output = self.probabilities - self.Y_data
    -        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    -
    -        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    -        self.output_bias_gradient = np.sum(error_output, axis=0)
    -
    -        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    -        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -        if self.lmbd > 0.0:
    -            self.output_weights_gradient += self.lmbd * self.output_weights
    -            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    -
    -        self.output_weights -= self.eta * self.output_weights_gradient
    -        self.output_bias -= self.eta * self.output_bias_gradient
    -        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    -        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    -
    -    def predict(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return np.argmax(probabilities, axis=1)
    -
    -    def predict_probabilities(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return probabilities
    -
    -    def train(self):
    -        data_indices = np.arange(self.n_inputs)
    -
    -        for i in range(self.epochs):
    -            for j in range(self.iterations):
    -                # pick datapoints with replacement
    -                chosen_datapoints = np.random.choice(
    -                    data_indices, size=self.batch_size, replace=False
    -                )
    -
    -                # minibatch training data
    -                self.X_data = self.X_data_full[chosen_datapoints]
    -                self.Y_data = self.Y_data_full[chosen_datapoints]
    -
    -                self.feed_forward()
    -                self.backpropagation()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Evaluate model performance on test data

    - -

    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. -We measure the performance of the network using the accuracy score. -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 \( 1 \). -

    - -

     
    -$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ -

     

    - -

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    - - - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    -
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    -
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Adjust hyperparameters

    - -

    We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

    - - - -
    -
    -
    -
    -
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -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)):
    -        dnn = DNN_numpy[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    scikit-learn implementation

    - -

    scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

    - -

    scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    -        
    -        DNN_scikit[i][j] = dnn
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Visualization

    - - -
    -
    -
    -
    -
    -
    # optional
    -# 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)):
    -        dnn = DNN_scikit[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Building neural networks in Tensorflow and Keras

    @@ -2228,7 +838,7 @@ plt.show()
    -

    The Breast Cancer Data, now with Keras

    +

    Using Pytorch with the full MNIST data set

    @@ -2237,171 +847,82 @@ plt.show()
    -
    import tensorflow as tf
    -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
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
    +  
    import torch
    +import torch.nn as nn
    +import torch.optim as optim
    +import torchvision
    +import torchvision.transforms as transforms
    +
    +# Device configuration: use GPU if available
    +device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    +
    +# MNIST dataset (downloads if not already present)
    +transform = transforms.Compose([
    +    transforms.ToTensor(),
    +    transforms.Normalize((0.5,), (0.5,))  # normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range)
    +])
    +train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
    +test_dataset  = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
    +
    +train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
    +test_loader  = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
     
     
    -"""Load breast cancer dataset"""
    +class NeuralNet(nn.Module):
    +    def __init__(self):
    +        super(NeuralNet, self).__init__()
    +        self.fc1 = nn.Linear(28*28, 100)   # first hidden layer (784 -> 100)
    +        self.fc2 = nn.Linear(100, 100)    # second hidden layer (100 -> 100)
    +        self.fc3 = nn.Linear(100, 10)     # output layer (100 -> 10 classes)
    +    def forward(self, x):
    +        x = x.view(x.size(0), -1)         # flatten images into vectors of size 784
    +        x = torch.relu(self.fc1(x))       # hidden layer 1 + ReLU activation
    +        x = torch.relu(self.fc2(x))       # hidden layer 2 + ReLU activation
    +        x = self.fc3(x)                   # output layer (logits for 10 classes)
    +        return x
     
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    +model = NeuralNet().to(device)
     
     
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    +criterion = nn.CrossEntropyLoss()
    +optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
     
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    +num_epochs = 10
    +for epoch in range(num_epochs):
    +    model.train()  # set model to training mode
    +    running_loss = 0.0
    +    for images, labels in train_loader:
    +        # Move data to device (GPU if available, else CPU)
    +        images, labels = images.to(device), labels.to(device)
    +
    +        optimizer.zero_grad()            # reset gradients to zero
    +        outputs = model(images)          # forward pass: compute predictions
    +        loss = criterion(outputs, labels)  # compute cross-entropy loss
    +        loss.backward()                 # backpropagate to compute gradients
    +        optimizer.step()                # update weights using SGD step 
    +
    +        running_loss += loss.item()
    +    # Compute average loss over all batches in this epoch
    +    avg_loss = running_loss / len(train_loader)
    +    print(f"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}")
    +
    +#Evaluation on the Test Set
     
     
    -# Generate training and testing datasets
     
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    +model.eval()  # set model to evaluation mode 
    +correct = 0
    +total = 0
    +with torch.no_grad():  # disable gradient calculation for evaluation 
    +    for images, labels in test_loader:
    +        images, labels = images.to(device), labels.to(device)
    +        outputs = model(images)
    +        _, predicted = torch.max(outputs, dim=1)  # class with highest score
    +        total += labels.size(0)
    +        correct += (predicted == labels).sum().item()
     
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(learning_rate=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    -    return model
    -
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    -
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    -
    -def plot_data(x,y,data,title=None):
    -
    -    # plot results
    -    fontsize=16
    -
    -
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +accuracy = 100 * correct / total
    +print(f"Test Accuracy: {accuracy:.2f}%")
     
    @@ -2419,7 +940,81 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing&
    -

    Building a neural network code

    +

    And a similar example using Tensorflow with Keras

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +from tensorflow import keras
    +from tensorflow.keras import layers, regularizers
    +
    +# Check for GPU (TensorFlow will use it automatically if available)
    +gpus = tf.config.list_physical_devices('GPU')
    +print(f"GPUs available: {gpus}")
    +
    +# 1) Load and preprocess MNIST
    +(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
    +# Normalize to [0, 1]
    +x_train = (x_train.astype("float32") / 255.0)
    +x_test  = (x_test.astype("float32") / 255.0)
    +
    +# 2) Build the model: 784 -> 100 -> 100 -> 10
    +l2_reg = 1e-4  # L2 regularization strength
    +
    +model = keras.Sequential([
    +    layers.Input(shape=(28, 28)),
    +    layers.Flatten(),
    +    layers.Dense(100, activation="relu",
    +                 kernel_regularizer=regularizers.l2(l2_reg)),
    +    layers.Dense(100, activation="relu",
    +                 kernel_regularizer=regularizers.l2(l2_reg)),
    +    layers.Dense(10, activation="softmax")  # output probabilities for 10 classes
    +])
    +
    +# 3) Compile with SGD + weight decay via L2 regularizers
    +model.compile(
    +    optimizer=keras.optimizers.SGD(learning_rate=0.01),
    +    loss="sparse_categorical_crossentropy",
    +    metrics=["accuracy"],
    +)
    +
    +model.summary()
    +
    +# 4) Train
    +history = model.fit(
    +    x_train, y_train,
    +    epochs=10,
    +    batch_size=64,
    +    validation_split=0.1,  # optional: monitor validation during training
    +    verbose=1
    +)
    +
    +# 5) Evaluate on test set
    +test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
    +print(f"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Building our own neural network code

    Here we present a flexible object oriented codebase for a feed forward neural network, along with a demonstration of how diff --git a/doc/pub/week43/html/week43-solarized.html b/doc/pub/week43/html/week43-solarized.html index 2650fd3cb..37267c7df 100644 --- a/doc/pub/week43/html/week43-solarized.html +++ b/doc/pub/week43/html/week43-solarized.html @@ -68,15 +68,6 @@ div.toc p,a { 2, None, 'exercises-and-lab-session-week-43'), - ('Mathematics of deep learning', - 2, - None, - 'mathematics-of-deep-learning'), - ('Reminder on books with hands-on material and codes', - 2, - None, - 'reminder-on-books-with-hands-on-material-and-codes'), - ('Reading recommendations', 2, None, 'reading-recommendations'), ('Using Automatic differentiation', 2, None, @@ -85,10 +76,10 @@ div.toc p,a { 2, None, 'back-propagation-and-automatic-differentiation'), - ('Lecture Monday October 21', + ('Lecture Monday October 20', 2, None, - 'lecture-monday-october-21'), + 'lecture-monday-october-20'), ('Setting up the back propagation algorithm and algorithm for a ' 'feed forward NN, initalizations', 2, @@ -122,63 +113,6 @@ div.toc p,a { 2, None, 'more-on-activation-functions-output-layers'), - ('Setting up a Multi-layer perceptron model for classification', - 2, - None, - 'setting-up-a-multi-layer-perceptron-model-for-classification'), - ('Defining the cost function', - 2, - None, - 'defining-the-cost-function'), - ('Example: binary classification problem', - 2, - None, - 'example-binary-classification-problem'), - ('The Softmax function', 2, None, 'the-softmax-function'), - ('Developing a code for doing neural networks with back ' - 'propagation', - 2, - None, - 'developing-a-code-for-doing-neural-networks-with-back-propagation'), - ('Collect and pre-process data', - 2, - None, - 'collect-and-pre-process-data'), - ('Train and test datasets', 2, None, 'train-and-test-datasets'), - ('Define model and architecture', - 2, - None, - 'define-model-and-architecture'), - ('Layers', 2, None, 'layers'), - ('Weights and biases', 2, None, 'weights-and-biases'), - ('Feed-forward pass', 2, None, 'feed-forward-pass'), - ('Matrix multiplications', 2, None, 'matrix-multiplications'), - ('Choose cost function and optimizer', - 2, - None, - 'choose-cost-function-and-optimizer'), - ('Optimizing the cost function', - 2, - None, - 'optimizing-the-cost-function'), - ('Regularization', 2, None, 'regularization'), - ('Matrix multiplication', 2, None, 'matrix-multiplication'), - ('Improving performance', 2, None, 'improving-performance'), - ('Full object-oriented implementation', - 2, - None, - 'full-object-oriented-implementation'), - ('Evaluate model performance on test data', - 2, - None, - 'evaluate-model-performance-on-test-data'), - ('Adjust hyperparameters', 2, None, 'adjust-hyperparameters'), - ('Visualization', 2, None, 'visualization'), - ('scikit-learn implementation', - 2, - None, - 'scikit-learn-implementation'), - ('Visualization', 2, None, 'visualization'), ('Building neural networks in Tensorflow and Keras', 2, None, @@ -189,14 +123,18 @@ div.toc p,a { 2, None, 'collect-and-pre-process-data'), - ('The Breast Cancer Data, now with Keras', + ('Using Pytorch with the full MNIST data set', 2, None, - 'the-breast-cancer-data-now-with-keras'), - ('Building a neural network code', + 'using-pytorch-with-the-full-mnist-data-set'), + ('And a similar example using Tensorflow with Keras', 2, None, - 'building-a-neural-network-code'), + 'and-a-similar-example-using-tensorflow-with-keras'), + ('Building our own neural network code', + 2, + None, + 'building-our-own-neural-network-code'), ('Learning rate methods', 3, None, 'learning-rate-methods'), ('Usage of the above learning rate schedulers', 3, @@ -361,18 +299,15 @@ MathJax.Hub.Config({

    -Morten Hjorth-Jensen [1, 2] +Morten Hjorth-Jensen
    - +
    -[1] Department of Physics, University of Oslo -
    -
    -[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University +Department of Physics, University of Oslo, Norway

    -

    October 21, 2024

    +

    October 20, 2025


    @@ -380,15 +315,16 @@ MathJax.Hub.Config({

    Plans for week 43

    -Material for the lecture on Monday October 21, 2024 +Material for the lecture on Monday October 20, 2025

    -

    +
      +
    1. Reminder from last week, see also lecture notes from week 42 at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html as well as those from week 41, see see https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html.
    2. +
    3. Building our own Feed-forward Neural Network.
    4. +
    5. Coding examples using Tensorflow/Keras and Pytorch examples. The Pytorch examples are adapted from Rashcka's text, see chapters 11-13..
    6. +
    7. Start discussions on how to use neural networks for solving differential equations (ordinary and partial ones). This topic continues next week as well.
    8. +
    9. Video of lecture at https://youtu.be/Gi6mzxAT0Ew
    10. +
    11. Whiteboard notes at https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2025/FYSSTKweek43.pdf
    12. +
    @@ -397,50 +333,18 @@ MathJax.Hub.Config({
    Lab sessions on Tuesday and Wednesday

    -

      -
    • Exercise on writing your own neural network code
    • -
    • The exercises this week will be continued next week as well
    • -
    • Discussion of project 2
    • -
    +
      +
    1. Work on writing your own neural network code and discussions of project 2. If you didn't get time to do the exercises from the two last weeks, we recommend doing so as these exercises give you the basic elements of a neural network code.
    2. +
    3. The exercises this week are tailored to the optional part of project 2, and deal with studying ways to display results from classification problems
    4. +
    -









    -

    Mathematics of deep learning

    - -
    -Two recent books online -

    -

      -
    1. The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen at https://arxiv.org/abs/2105.04026, published as Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022
    2. -
    3. Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger at https://doi.org/10.48550/arXiv.2310.20360
    4. -
    -
    - - -









    -

    Reminder on books with hands-on material and codes

    -
    - -

    -

    -
    - - -









    -

    Reading recommendations

    - -
      -
    1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub site at https://github.com/rasbt/machine-learning-book. See also chapters 12 and 13 on using Pytorch to make a Neural network code.
    2. -
    3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
    4. -










    Using Automatic differentiation

    In our discussions of ordinary differential equations and neural network codes -we will also study the usage of Autograd, see for example https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from week 39 and the Autograd documentation at https://github.com/HIPS/autograd. +we will also study the usage of Autograd, see for example https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola in computing gradients for deep learning. For the documentation of Autograd and examples see the Autograd documentation at https://github.com/HIPS/autograd and the lecture slides from week 41, see https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html.











    @@ -453,11 +357,11 @@ we will also study the usage of Autograd, see for example http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf









    -

    Lecture Monday October 21

    +

    Lecture Monday October 20











    Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

    -

    This is a reminder from where we ended last week.

    +

    This is a reminder from last week.

    The architecture (our model) @@ -637,1239 +541,6 @@ gradient descent optimization does in general not get stuck.
  • 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.
  • - -

    Setting up a Multi-layer perceptron model for classification

    - -

    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 -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. -

    - -

    In binary classification with two classes \( (0, 1) \) we define the -logistic/sigmoid function as the probability that a particular input -is in class \( 0 \) or \( 1 \). This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. -

    - -

    For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) -is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) -represents our activation values \( z \). We have -

    -$$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , -$$ - -

    and

    -$$ -P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , -$$ - -

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. -

    - - -









    -

    Defining the cost function

    - -

    Our cost function is given as (see the Logistic regression lectures)

    -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . -$$ - -

    This last equality means that we can interpret our cost function as a sum over the loss function -for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    \( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

    - -\( y = 1 \quad \rightarrow \quad \boldsymbol{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 \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th -output vector \( \boldsymbol{y}_i \). -The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: -

    - -$$ -P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , -$$ - -

    which reduces to the logistic function in the binary case. -The likelihood of this \( C \)-class classifier -is now given as: -

    - -$$ -P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -$$ - -

    Again we take the negative log-likelihood to define our cost function:

    - -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. -$$ - -

    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

    -$$ -\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), -$$ - -

    where we had defined the logistic (sigmoid) function

    -$$ -p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, -$$ - -

    and

    -$$ -p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). -$$ - -

    The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

    - -

    Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). -We have then -

    -$$ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -$$ - -

    with

    -$$ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -$$ - -

    where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). -Our cost function at the final layer \( l=L \) is now -

    -$$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -$$ - -

    where we have defined the targets \( t_i \). The derivatives of the cost function with respect to the output \( a_i^L \) are then easily calculated and we get

    -$$ -\frac{\partial \mathcal{C}(\boldsymbol{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.

    - -









    -

    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

    -$$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -$$ - -

    For the Softmax function we have

    -$$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -$$ - -

    Its derivative with respect to \( z_j^l \) gives

    -$$ -\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 \).

    - - -

    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
    2. -
    3. Define model and architecture
    4. -
    5. Choose cost function and optimizer
    6. -
    7. Train the model
    8. -
    9. Evaluate model performance on test data
    10. -
    11. Adjust hyperparameters (if necessary, network architecture)
    12. -
    -









    -

    Collect and pre-process data

    - -

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

    - -

    To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

    - -

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

    - -

    $$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

    - -

    and the targets would be:

    - -

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    - -

    Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

    - - - -
    -
    -
    -
    -
    -
    # 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
    -%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
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Train and test datasets

    - -

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    - -

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    - -

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -
    -# 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)
    -
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    -
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    -
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Define model and architecture

    - -

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    - -

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    - -

    $$ y = f(z) ,$$

    - -

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

    - -

    The simplest activation function for a neuron is the Heaviside function:

    - -

    $$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

    - -

    A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

    - -

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

    - -

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

    - -

    $$ 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
    • -
    -

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    - -
      -
    • Hidden layer
    • -
    -

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

    - -
      -
    • Output
    • -
    -

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

    - -

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    - -

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    - -

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

    - -

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    - -

    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. -

    - - -

    Weights and biases

    - -

    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. -

    - -

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    - -

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    - - -
    -
    -
    -
    -
    -
    # building our neural network
    -
    -n_inputs, n_features = X_train.shape
    -n_hidden_neurons = 50
    -n_categories = 10
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Feed-forward pass

    - -

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

    - -

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    - -

    this is then passed through our activation function

    - -

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    - -

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    - -

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    - -

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    - -

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

    - - -

    Matrix multiplications

    - -

    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}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

    - -

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    - -

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

    - -

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    - -

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

    - -

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    - -

    This is fed to the output layer:

    - -

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    - -

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    - -

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    - - - -
    -
    -
    -
    -
    -
    # setup the feed-forward pass, subscript h = hidden layer
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    return probabilities
    -
    -probabilities = feed_forward(X_train)
    -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    -print("probabilities sum up to: " + str(probabilities[0].sum()))
    -print()
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -predictions = predict(X_train)
    -print("predictions = (n_inputs) = " + str(predictions.shape))
    -print("prediction for image 0: " + str(predictions[0]))
    -print("correct label for image 0: " + str(Y_train[0]))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Choose cost function and optimizer

    - -

    To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    - -

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{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. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

    - -

    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 \( \boldsymbol{\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 -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 local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

    - -

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    - -

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

    - -

    A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

    - -

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

    - -

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    - -

    This has two important benefits:

    -
      -
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. -
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. -
    -

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    - - -

    Regularization

    - -

    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. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

    - -

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    - -

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

    - -

    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 -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -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. -

    - -









    -

    Matrix multiplication

    - -

    To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

    - -

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    - -

    The gradient for the output weights is calculated as

    - -

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    - -

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

    - -

    The gradient with respect to the output bias is then

    - -

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    - -

    The error in the hidden layer is

    - -

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    - -

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

    - -

    This again gives us the gradients in the hidden layer:

    - -

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    - -

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    - - - -
    -
    -
    -
    -
    -
    # to categorical turns our integer vector into a onehot representation
    -from sklearn.metrics import accuracy_score
    -
    -# one-hot in numpy
    -def to_categorical_numpy(integer_vector):
    -    n_inputs = len(integer_vector)
    -    n_categories = np.max(integer_vector) + 1
    -    onehot_vector = np.zeros((n_inputs, n_categories))
    -    onehot_vector[range(n_inputs), integer_vector] = 1
    -    
    -    return onehot_vector
    -
    -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    -
    -def feed_forward_train(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    # for backpropagation need activations in hidden and output layers
    -    return a_h, probabilities
    -
    -def backpropagation(X, Y):
    -    a_h, probabilities = feed_forward_train(X)
    -    
    -    # error in the output layer
    -    error_output = probabilities - Y
    -    # error in the hidden layer
    -    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    -    
    -    # gradients for the output layer
    -    output_weights_gradient = np.matmul(a_h.T, error_output)
    -    output_bias_gradient = np.sum(error_output, axis=0)
    -    
    -    # gradient for the hidden layer
    -    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    -    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    -
    -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -eta = 0.01
    -lmbd = 0.01
    -for i in range(1000):
    -    # calculate gradients
    -    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    -    
    -    # regularization term gradients
    -    dWo += lmbd * output_weights
    -    dWh += lmbd * hidden_weights
    -    
    -    # update weights and biases
    -    output_weights -= eta * dWo
    -    output_bias -= eta * dBo
    -    hidden_weights -= eta * dWh
    -    hidden_bias -= eta * dBh
    -
    -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Improving performance

    - -

    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. -In order to obtain a network that does something useful, we will have to do a bit more work. -

    - -

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    - -

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

    - -

    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. You can find a summary of the video here. -

    - -









    -

    Full object-oriented implementation

    - -

    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. -

    - - - -
    -
    -
    -
    -
    -
    class NeuralNetwork:
    -    def __init__(
    -            self,
    -            X_data,
    -            Y_data,
    -            n_hidden_neurons=50,
    -            n_categories=10,
    -            epochs=10,
    -            batch_size=100,
    -            eta=0.1,
    -            lmbd=0.0):
    -
    -        self.X_data_full = X_data
    -        self.Y_data_full = Y_data
    -
    -        self.n_inputs = X_data.shape[0]
    -        self.n_features = X_data.shape[1]
    -        self.n_hidden_neurons = n_hidden_neurons
    -        self.n_categories = n_categories
    -
    -        self.epochs = epochs
    -        self.batch_size = batch_size
    -        self.iterations = self.n_inputs // self.batch_size
    -        self.eta = eta
    -        self.lmbd = lmbd
    -
    -        self.create_biases_and_weights()
    -
    -    def create_biases_and_weights(self):
    -        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    -        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    -
    -        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    -        self.output_bias = np.zeros(self.n_categories) + 0.01
    -
    -    def feed_forward(self):
    -        # feed-forward for training
    -        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    -        self.a_h = sigmoid(self.z_h)
    -
    -        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    -
    -        exp_term = np.exp(self.z_o)
    -        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -
    -    def feed_forward_out(self, X):
    -        # feed-forward for output
    -        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    -        a_h = sigmoid(z_h)
    -
    -        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    -        
    -        exp_term = np.exp(z_o)
    -        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -        return probabilities
    -
    -    def backpropagation(self):
    -        error_output = self.probabilities - self.Y_data
    -        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    -
    -        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    -        self.output_bias_gradient = np.sum(error_output, axis=0)
    -
    -        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    -        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -        if self.lmbd > 0.0:
    -            self.output_weights_gradient += self.lmbd * self.output_weights
    -            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    -
    -        self.output_weights -= self.eta * self.output_weights_gradient
    -        self.output_bias -= self.eta * self.output_bias_gradient
    -        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    -        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    -
    -    def predict(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return np.argmax(probabilities, axis=1)
    -
    -    def predict_probabilities(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return probabilities
    -
    -    def train(self):
    -        data_indices = np.arange(self.n_inputs)
    -
    -        for i in range(self.epochs):
    -            for j in range(self.iterations):
    -                # pick datapoints with replacement
    -                chosen_datapoints = np.random.choice(
    -                    data_indices, size=self.batch_size, replace=False
    -                )
    -
    -                # minibatch training data
    -                self.X_data = self.X_data_full[chosen_datapoints]
    -                self.Y_data = self.Y_data_full[chosen_datapoints]
    -
    -                self.feed_forward()
    -                self.backpropagation()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Evaluate model performance on test data

    - -

    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. -We measure the performance of the network using the accuracy score. -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 \( 1 \). -

    - -

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    - -

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    - - - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    -
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    -
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Adjust hyperparameters

    - -

    We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

    - - - -
    -
    -
    -
    -
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -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)):
    -        dnn = DNN_numpy[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    scikit-learn implementation

    - -

    scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

    - -

    scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    -        
    -        DNN_scikit[i][j] = dnn
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - -
    -
    -
    -
    -
    -
    # optional
    -# 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)):
    -        dnn = DNN_scikit[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -









    Building neural networks in Tensorflow and Keras

    @@ -2251,7 +922,7 @@ plt.show()









    -

    The Breast Cancer Data, now with Keras

    +

    Using Pytorch with the full MNIST data set

    @@ -2260,171 +931,82 @@ plt.show()
    -
    import tensorflow as tf
    -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
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
    +  
    import torch
    +import torch.nn as nn
    +import torch.optim as optim
    +import torchvision
    +import torchvision.transforms as transforms
    +
    +# Device configuration: use GPU if available
    +device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    +
    +# MNIST dataset (downloads if not already present)
    +transform = transforms.Compose([
    +    transforms.ToTensor(),
    +    transforms.Normalize((0.5,), (0.5,))  # normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range)
    +])
    +train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
    +test_dataset  = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
    +
    +train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
    +test_loader  = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
     
     
    -"""Load breast cancer dataset"""
    +class NeuralNet(nn.Module):
    +    def __init__(self):
    +        super(NeuralNet, self).__init__()
    +        self.fc1 = nn.Linear(28*28, 100)   # first hidden layer (784 -> 100)
    +        self.fc2 = nn.Linear(100, 100)    # second hidden layer (100 -> 100)
    +        self.fc3 = nn.Linear(100, 10)     # output layer (100 -> 10 classes)
    +    def forward(self, x):
    +        x = x.view(x.size(0), -1)         # flatten images into vectors of size 784
    +        x = torch.relu(self.fc1(x))       # hidden layer 1 + ReLU activation
    +        x = torch.relu(self.fc2(x))       # hidden layer 2 + ReLU activation
    +        x = self.fc3(x)                   # output layer (logits for 10 classes)
    +        return x
     
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    +model = NeuralNet().to(device)
     
     
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    +criterion = nn.CrossEntropyLoss()
    +optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
     
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    +num_epochs = 10
    +for epoch in range(num_epochs):
    +    model.train()  # set model to training mode
    +    running_loss = 0.0
    +    for images, labels in train_loader:
    +        # Move data to device (GPU if available, else CPU)
    +        images, labels = images.to(device), labels.to(device)
    +
    +        optimizer.zero_grad()            # reset gradients to zero
    +        outputs = model(images)          # forward pass: compute predictions
    +        loss = criterion(outputs, labels)  # compute cross-entropy loss
    +        loss.backward()                 # backpropagate to compute gradients
    +        optimizer.step()                # update weights using SGD step 
    +
    +        running_loss += loss.item()
    +    # Compute average loss over all batches in this epoch
    +    avg_loss = running_loss / len(train_loader)
    +    print(f"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}")
    +
    +#Evaluation on the Test Set
     
     
    -# Generate training and testing datasets
     
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    +model.eval()  # set model to evaluation mode 
    +correct = 0
    +total = 0
    +with torch.no_grad():  # disable gradient calculation for evaluation 
    +    for images, labels in test_loader:
    +        images, labels = images.to(device), labels.to(device)
    +        outputs = model(images)
    +        _, predicted = torch.max(outputs, dim=1)  # class with highest score
    +        total += labels.size(0)
    +        correct += (predicted == labels).sum().item()
     
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(learning_rate=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    -    return model
    -
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    -
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    -
    -def plot_data(x,y,data,title=None):
    -
    -    # plot results
    -    fontsize=16
    -
    -
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +accuracy = 100 * correct / total
    +print(f"Test Accuracy: {accuracy:.2f}%")
     
    @@ -2442,7 +1024,81 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing&









    -

    Building a neural network code

    +

    And a similar example using Tensorflow with Keras

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +from tensorflow import keras
    +from tensorflow.keras import layers, regularizers
    +
    +# Check for GPU (TensorFlow will use it automatically if available)
    +gpus = tf.config.list_physical_devices('GPU')
    +print(f"GPUs available: {gpus}")
    +
    +# 1) Load and preprocess MNIST
    +(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
    +# Normalize to [0, 1]
    +x_train = (x_train.astype("float32") / 255.0)
    +x_test  = (x_test.astype("float32") / 255.0)
    +
    +# 2) Build the model: 784 -> 100 -> 100 -> 10
    +l2_reg = 1e-4  # L2 regularization strength
    +
    +model = keras.Sequential([
    +    layers.Input(shape=(28, 28)),
    +    layers.Flatten(),
    +    layers.Dense(100, activation="relu",
    +                 kernel_regularizer=regularizers.l2(l2_reg)),
    +    layers.Dense(100, activation="relu",
    +                 kernel_regularizer=regularizers.l2(l2_reg)),
    +    layers.Dense(10, activation="softmax")  # output probabilities for 10 classes
    +])
    +
    +# 3) Compile with SGD + weight decay via L2 regularizers
    +model.compile(
    +    optimizer=keras.optimizers.SGD(learning_rate=0.01),
    +    loss="sparse_categorical_crossentropy",
    +    metrics=["accuracy"],
    +)
    +
    +model.summary()
    +
    +# 4) Train
    +history = model.fit(
    +    x_train, y_train,
    +    epochs=10,
    +    batch_size=64,
    +    validation_split=0.1,  # optional: monitor validation during training
    +    verbose=1
    +)
    +
    +# 5) Evaluate on test set
    +test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
    +print(f"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Building our own neural network code

    Here we present a flexible object oriented codebase for a feed forward neural network, along with a demonstration of how @@ -6462,7 +5118,7 @@ $$

    - © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week43/html/week43.html b/doc/pub/week43/html/week43.html index 9210219f9..ac8c08010 100644 --- a/doc/pub/week43/html/week43.html +++ b/doc/pub/week43/html/week43.html @@ -145,15 +145,6 @@ div.toc p,a { 2, None, 'exercises-and-lab-session-week-43'), - ('Mathematics of deep learning', - 2, - None, - 'mathematics-of-deep-learning'), - ('Reminder on books with hands-on material and codes', - 2, - None, - 'reminder-on-books-with-hands-on-material-and-codes'), - ('Reading recommendations', 2, None, 'reading-recommendations'), ('Using Automatic differentiation', 2, None, @@ -162,10 +153,10 @@ div.toc p,a { 2, None, 'back-propagation-and-automatic-differentiation'), - ('Lecture Monday October 21', + ('Lecture Monday October 20', 2, None, - 'lecture-monday-october-21'), + 'lecture-monday-october-20'), ('Setting up the back propagation algorithm and algorithm for a ' 'feed forward NN, initalizations', 2, @@ -199,63 +190,6 @@ div.toc p,a { 2, None, 'more-on-activation-functions-output-layers'), - ('Setting up a Multi-layer perceptron model for classification', - 2, - None, - 'setting-up-a-multi-layer-perceptron-model-for-classification'), - ('Defining the cost function', - 2, - None, - 'defining-the-cost-function'), - ('Example: binary classification problem', - 2, - None, - 'example-binary-classification-problem'), - ('The Softmax function', 2, None, 'the-softmax-function'), - ('Developing a code for doing neural networks with back ' - 'propagation', - 2, - None, - 'developing-a-code-for-doing-neural-networks-with-back-propagation'), - ('Collect and pre-process data', - 2, - None, - 'collect-and-pre-process-data'), - ('Train and test datasets', 2, None, 'train-and-test-datasets'), - ('Define model and architecture', - 2, - None, - 'define-model-and-architecture'), - ('Layers', 2, None, 'layers'), - ('Weights and biases', 2, None, 'weights-and-biases'), - ('Feed-forward pass', 2, None, 'feed-forward-pass'), - ('Matrix multiplications', 2, None, 'matrix-multiplications'), - ('Choose cost function and optimizer', - 2, - None, - 'choose-cost-function-and-optimizer'), - ('Optimizing the cost function', - 2, - None, - 'optimizing-the-cost-function'), - ('Regularization', 2, None, 'regularization'), - ('Matrix multiplication', 2, None, 'matrix-multiplication'), - ('Improving performance', 2, None, 'improving-performance'), - ('Full object-oriented implementation', - 2, - None, - 'full-object-oriented-implementation'), - ('Evaluate model performance on test data', - 2, - None, - 'evaluate-model-performance-on-test-data'), - ('Adjust hyperparameters', 2, None, 'adjust-hyperparameters'), - ('Visualization', 2, None, 'visualization'), - ('scikit-learn implementation', - 2, - None, - 'scikit-learn-implementation'), - ('Visualization', 2, None, 'visualization'), ('Building neural networks in Tensorflow and Keras', 2, None, @@ -266,14 +200,18 @@ div.toc p,a { 2, None, 'collect-and-pre-process-data'), - ('The Breast Cancer Data, now with Keras', + ('Using Pytorch with the full MNIST data set', 2, None, - 'the-breast-cancer-data-now-with-keras'), - ('Building a neural network code', + 'using-pytorch-with-the-full-mnist-data-set'), + ('And a similar example using Tensorflow with Keras', 2, None, - 'building-a-neural-network-code'), + 'and-a-similar-example-using-tensorflow-with-keras'), + ('Building our own neural network code', + 2, + None, + 'building-our-own-neural-network-code'), ('Learning rate methods', 3, None, 'learning-rate-methods'), ('Usage of the above learning rate schedulers', 3, @@ -438,18 +376,15 @@ MathJax.Hub.Config({
    -Morten Hjorth-Jensen [1, 2] +Morten Hjorth-Jensen
    - +
    -[1] Department of Physics, University of Oslo -
    -
    -[2] Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University +Department of Physics, University of Oslo, Norway

    -

    October 21, 2024

    +

    October 20, 2025


    @@ -457,15 +392,16 @@ MathJax.Hub.Config({

    Plans for week 43

    -Material for the lecture on Monday October 21, 2024 +Material for the lecture on Monday October 20, 2025

    -

    +
      +
    1. Reminder from last week, see also lecture notes from week 42 at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html as well as those from week 41, see see https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html.
    2. +
    3. Building our own Feed-forward Neural Network.
    4. +
    5. Coding examples using Tensorflow/Keras and Pytorch examples. The Pytorch examples are adapted from Rashcka's text, see chapters 11-13..
    6. +
    7. Start discussions on how to use neural networks for solving differential equations (ordinary and partial ones). This topic continues next week as well.
    8. +
    9. Video of lecture at https://youtu.be/Gi6mzxAT0Ew
    10. +
    11. Whiteboard notes at https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2025/FYSSTKweek43.pdf
    12. +
    @@ -474,50 +410,18 @@ MathJax.Hub.Config({
    Lab sessions on Tuesday and Wednesday

    -

      -
    • Exercise on writing your own neural network code
    • -
    • The exercises this week will be continued next week as well
    • -
    • Discussion of project 2
    • -
    +
      +
    1. Work on writing your own neural network code and discussions of project 2. If you didn't get time to do the exercises from the two last weeks, we recommend doing so as these exercises give you the basic elements of a neural network code.
    2. +
    3. The exercises this week are tailored to the optional part of project 2, and deal with studying ways to display results from classification problems
    4. +
    -









    -

    Mathematics of deep learning

    - -
    -Two recent books online -

    -

      -
    1. The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen at https://arxiv.org/abs/2105.04026, published as Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022
    2. -
    3. Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger at https://doi.org/10.48550/arXiv.2310.20360
    4. -
    -
    - - -









    -

    Reminder on books with hands-on material and codes

    -
    - -

    -

    -
    - - -









    -

    Reading recommendations

    - -
      -
    1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub site at https://github.com/rasbt/machine-learning-book. See also chapters 12 and 13 on using Pytorch to make a Neural network code.
    2. -
    3. Goodfellow et al, chapter 6 and 7 contain most of the neural network background.
    4. -










    Using Automatic differentiation

    In our discussions of ordinary differential equations and neural network codes -we will also study the usage of Autograd, see for example https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from week 39 and the Autograd documentation at https://github.com/HIPS/autograd. +we will also study the usage of Autograd, see for example https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola in computing gradients for deep learning. For the documentation of Autograd and examples see the Autograd documentation at https://github.com/HIPS/autograd and the lecture slides from week 41, see https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html.











    @@ -530,11 +434,11 @@ we will also study the usage of Autograd, see for example http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf









    -

    Lecture Monday October 21

    +

    Lecture Monday October 20











    Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations

    -

    This is a reminder from where we ended last week.

    +

    This is a reminder from last week.

    The architecture (our model) @@ -714,1239 +618,6 @@ gradient descent optimization does in general not get stuck.
  • 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.
  • - -

    Setting up a Multi-layer perceptron model for classification

    - -

    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 -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. -

    - -

    In binary classification with two classes \( (0, 1) \) we define the -logistic/sigmoid function as the probability that a particular input -is in class \( 0 \) or \( 1 \). This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. -

    - -

    For an input \( \boldsymbol{a} \) from the hidden layer, the probability that the input \( \boldsymbol{x} \) -is in class 0 or 1 is just. We let \( \theta \) represent the unknown weights and biases to be adjusted by our equations). The variable \( x \) -represents our activation values \( z \). We have -

    -$$ -P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) = \frac{1}{1 + \exp{(- \boldsymbol{x}})} , -$$ - -

    and

    -$$ -P(y = 1 \mid \boldsymbol{x}, \boldsymbol{\theta}) = 1 - P(y = 0 \mid \boldsymbol{x}, \boldsymbol{\theta}) , -$$ - -

    where \( y \in \{0, 1\} \) and \( \boldsymbol{\theta} \) represents the weights and biases -of our network. -

    - - -









    -

    Defining the cost function

    - -

    Our cost function is given as (see the Logistic regression lectures)

    -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \ln P(\mathcal{D} \mid \boldsymbol{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\boldsymbol{\theta}) . -$$ - -

    This last equality means that we can interpret our cost function as a sum over the loss function -for each point in the dataset \( \mathcal{L}_i(\boldsymbol{\theta}) \). -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    \( y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) , \) and

    - -\( y = 1 \quad \rightarrow \quad \boldsymbol{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 \( \boldsymbol{x}_i \) is the \( i \)-th input (image), \( y_{ic} \) refers to the \( c \)-th component of the \( i \)-th -output vector \( \boldsymbol{y}_i \). -The probability of \( \boldsymbol{x}_i \) being in class \( c \) will be given by the softmax function: -

    - -$$ -P(y_{ic} = 1 \mid \boldsymbol{x}_i, \boldsymbol{\theta}) = \frac{\exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\boldsymbol{a}_i^{hidden})^T \boldsymbol{w}_{c'})}} , -$$ - -

    which reduces to the logistic function in the binary case. -The likelihood of this \( C \)-class classifier -is now given as: -

    - -$$ -P(\mathcal{D} \mid \boldsymbol{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -$$ - -

    Again we take the negative log-likelihood to define our cost function:

    - -$$ -\mathcal{C}(\boldsymbol{\theta}) = - \log{P(\mathcal{D} \mid \boldsymbol{\theta})}. -$$ - -

    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

    -$$ -\mathcal{C}(\boldsymbol{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\boldsymbol{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\boldsymbol{\beta})}\right), -$$ - -

    where we had defined the logistic (sigmoid) function

    -$$ -p(y_i =1\vert x_i,\boldsymbol{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, -$$ - -

    and

    -$$ -p(y_i =0\vert x_i,\boldsymbol{\beta})=1-p(y_i =1\vert x_i,\boldsymbol{\beta}). -$$ - -

    The parameters \( \boldsymbol{\beta} \) were defined using a minimization method like gradient descent or Newton-Raphson's method.

    - -

    Now we replace \( x_i \) with the activation \( z_i^l \) for a given layer \( l \) and the outputs as \( y_i=a_i^l=f(z_i^l) \), with \( z_i^l \) now being a function of the weights \( w_{ij}^l \) and biases \( b_i^l \). -We have then -

    -$$ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -$$ - -

    with

    -$$ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -$$ - -

    where the superscript \( l-1 \) indicates that these are the outputs from layer \( l-1 \). -Our cost function at the final layer \( l=L \) is now -

    -$$ -\mathcal{C}(\boldsymbol{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -$$ - -

    where we have defined the targets \( t_i \). The derivatives of the cost function with respect to the output \( a_i^L \) are then easily calculated and we get

    -$$ -\frac{\partial \mathcal{C}(\boldsymbol{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.

    - -









    -

    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

    -$$ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -$$ - -

    For the Softmax function we have

    -$$ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -$$ - -

    Its derivative with respect to \( z_j^l \) gives

    -$$ -\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 \).

    - - -

    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
    2. -
    3. Define model and architecture
    4. -
    5. Choose cost function and optimizer
    6. -
    7. Train the model
    8. -
    9. Evaluate model performance on test data
    10. -
    11. Adjust hyperparameters (if necessary, network architecture)
    12. -
    -









    -

    Collect and pre-process data

    - -

    Here we will be using the MNIST dataset, which is readily available through the scikit-learn -package. You may also find it for example here. -The MNIST (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size \( 28\times 28 \) pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size \( 8\times 8 \) collected and processed from this database. -

    - -

    To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix \( X = (n_{inputs}, n_{features}) \). Each -row represents an input, in this case a handwritten digit, and -each column represents a feature, in this case a pixel. The -correct answers, also known as labels or targets are -represented as a 1D array of integers -\( Y = (n_{inputs}) = (5, 3, 1, 8,...) \). -

    - -

    As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: -

    - -

    $$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ -

    - -

    and the targets would be:

    - -

    $$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$

    - -

    Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. -

    - - - -
    -
    -
    -
    -
    -
    # 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
    -%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
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# flatten the image
    -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
    -n_inputs = len(inputs)
    -inputs = inputs.reshape(n_inputs, -1)
    -print("X = (n_inputs, n_features) = " + str(inputs.shape))
    -
    -
    -# choose some random images to display
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Train and test datasets

    - -

    Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.

    - -

    We will reserve \( 80 \% \) of our dataset for training and \( 20 \% \) for testing.

    - -

    It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -
    -# 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)
    -
    -# equivalently in numpy
    -def train_test_split_numpy(inputs, labels, train_size, test_size):
    -    n_inputs = len(inputs)
    -    inputs_shuffled = inputs.copy()
    -    labels_shuffled = labels.copy()
    -    
    -    np.random.shuffle(inputs_shuffled)
    -    np.random.shuffle(labels_shuffled)
    -    
    -    train_end = int(n_inputs*train_size)
    -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
    -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
    -    
    -    return X_train, X_test, Y_train, Y_test
    -
    -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)
    -
    -print("Number of training images: " + str(len(X_train)))
    -print("Number of test images: " + str(len(X_test)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Define model and architecture

    - -

    Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have

    - -

    $$ z = \sum_{i=1}^n w_i a_i ,$$

    - -

    $$ y = f(z) ,$$

    - -

    where \( f \) is the activation function, \( a_i \) represents input from neuron \( i \) in the preceding layer -and \( w_i \) is the weight to input \( i \). -The activation of the neurons in the input layer is just the features (e.g. a pixel value). -

    - -

    The simplest activation function for a neuron is the Heaviside function:

    - -

    $$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ -

    - -

    A feed-forward neural network with this activation is known as a perceptron. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to \( k \) classes (using e.g. the one-against-all strategy), -and we call these architectures multiclass perceptrons. -

    - -

    However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. -

    - -

    Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function \( \sigma(x) \): -

    - -

    $$ 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
    • -
    -

    Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons.

    - -
      -
    • Hidden layer
    • -
    -

    We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. -

    - -
      -
    • Output
    • -
    -

    If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a hard classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a soft classifier, which outputs the probability of being in class 0 or 1. -

    - -

    For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class.

    - -

    Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons \( j = 0,1,...,9 \). The activation of each output neuron \( j \) will be according to the softmax function:

    - -

    $$ P(\text{class \( j \)} \mid \text{input \( \boldsymbol{a} \)}) = \frac{\exp{(\boldsymbol{a}^T \boldsymbol{w}_j)}} -{\sum_{c=0}^{9} \exp{(\boldsymbol{a}^T \boldsymbol{w}_c)}} ,$$ -

    - -

    i.e. each neuron \( j \) outputs the probability of being in class \( j \) given an input from the hidden layer \( \boldsymbol{a} \), with \( \boldsymbol{w}_j \) the weights of neuron \( j \) to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$

    - -

    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. -

    - - -

    Weights and biases

    - -

    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. -

    - -

    Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron \( j \), \( b_j \): -

    - -

    $$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$

    - -

    The bias weights \( \boldsymbol{b} \) are often initialized to zero, but a small value like \( 0.01 \) ensures all neurons have some output which can be backpropagated in the first training cycle.

    - - -
    -
    -
    -
    -
    -
    # building our neural network
    -
    -n_inputs, n_features = X_train.shape
    -n_hidden_neurons = 50
    -n_categories = 10
    -
    -# we make the weights normally distributed using numpy.random.randn
    -
    -# weights and bias in the hidden layer
    -hidden_weights = np.random.randn(n_features, n_hidden_neurons)
    -hidden_bias = np.zeros(n_hidden_neurons) + 0.01
    -
    -# weights and bias in the output layer
    -output_weights = np.random.randn(n_hidden_neurons, n_categories)
    -output_bias = np.zeros(n_categories) + 0.01
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Feed-forward pass

    - -

    Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron \( j \) in the hidden layer \( l \): -

    - -

    $$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$

    - -

    this is then passed through our activation function

    - -

    $$ a_{j}^{l} = f(z_{j}^{l}) .$$

    - -

    We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron \( j \) in the output layer:

    - -

    $$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$

    - -

    Finally we calculate the output of neuron \( j \) in the output layer using the softmax function:

    - -

    $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ -

    - - -

    Matrix multiplications

    - -

    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}) \), -we can easily feed the network all our training data in one go by taking the matrix product -

    - -

    $$ X W^{h} = (n_{inputs}, n_{hidden}),$$

    - -

    and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer \( Z^{h} \): -

    - -

    $$ \boldsymbol{z}^{l} = \boldsymbol{X} \boldsymbol{W}^{l} + \boldsymbol{b}^{l} ,$$

    - -

    meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: -

    - -

    $$ \boldsymbol{a}^{l} = f(\boldsymbol{z}^l) .$$

    - -

    This is fed to the output layer:

    - -

    $$ \boldsymbol{z}^{L} = \boldsymbol{a}^{L} \boldsymbol{W}^{L} + \boldsymbol{b}^{L} .$$

    - -

    Finally we receive our output values for each image and each category by passing it through the softmax function:

    - -

    $$ output = softmax (\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$

    - - - -
    -
    -
    -
    -
    -
    # setup the feed-forward pass, subscript h = hidden layer
    -
    -def sigmoid(x):
    -    return 1/(1 + np.exp(-x))
    -
    -def feed_forward(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    return probabilities
    -
    -probabilities = feed_forward(X_train)
    -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape))
    -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0]))
    -print("probabilities sum up to: " + str(probabilities[0].sum()))
    -print()
    -
    -# we obtain a prediction by taking the class with the highest likelihood
    -def predict(X):
    -    probabilities = feed_forward(X)
    -    return np.argmax(probabilities, axis=1)
    -
    -predictions = predict(X_train)
    -print("predictions = (n_inputs) = " + str(predictions.shape))
    -print("prediction for image 0: " + str(predictions[0]))
    -print("correct label for image 0: " + str(Y_train[0]))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Choose cost function and optimizer

    - -

    To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the loss function, and the function -that gives the total error of our network across all samples the cost function. -A typical choice for multiclass classification is the cross-entropy loss, also known as the negative log likelihood. -

    - -

    In multiclass classification it is common to treat each integer label as a so called one-hot vector:

    - -

    $$ y = 5 \quad \rightarrow \quad \boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$

    - -

    $$ y = 1 \quad \rightarrow \quad \boldsymbol{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. -We define the cost function \( \mathcal{C} \) as a sum over the cross-entropy loss for each point \( \boldsymbol{x}_i \) in the dataset. -

    - -

    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 \( \boldsymbol{\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 -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 local minimum of the cost function. -Each parameter \( \theta \) is iteratively adjusted according to the rule -

    - -

    $$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$

    - -

    where \( \eta \) is known as the learning rate, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. -

    - -

    A simple and effective improvement is a variant called Batch Gradient Descent. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a minibatch. -If there are \( N \) data points and we have a minibatch size of \( M \), the total number of batches -is \( N/M \). -We denote each minibatch \( B_k \), with \( k = 1, 2,...,N/M \). The gradient then becomes: -

    - -

    $$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ -

    - -

    i.e. instead of averaging the loss over the entire dataset, we average over a minibatch.

    - -

    This has two important benefits:

    -
      -
    1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima.
    2. -
    3. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient.
    4. -
    -

    The various optmization methods, with codes and algorithms, are discussed in our lectures on Gradient descent approaches.

    - - -

    Regularization

    - -

    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. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces overfitting. -

    - -

    We will measure the size of the weights using the so called L2-norm, meaning our cost function becomes:

    - -

    $$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \boldsymbol{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ -

    - -

    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 -the hidden layer and \( (50 + 1)\times 10=510 \) weights to the output -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. -

    - -









    -

    Matrix multiplication

    - -

    To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with \( \boldsymbol{t} \) being our targets, -

    - -

    $$ \delta_L = \boldsymbol{t} - \boldsymbol{y} = (n_{inputs}, n_{categories}) .$$

    - -

    The gradient for the output weights is calculated as

    - -

    $$ \nabla W_{L} = \boldsymbol{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$

    - -

    where \( \boldsymbol{a} = (n_{inputs}, n_{hidden}) \). This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. -

    - -

    The gradient with respect to the output bias is then

    - -

    $$ \nabla \boldsymbol{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$

    - -

    The error in the hidden layer is

    - -

    $$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$

    - -

    where \( f'(a_{h}) \) is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol \( \circ \) denotes -the Hadamard product, meaning element-wise multiplication. -

    - -

    This again gives us the gradients in the hidden layer:

    - -

    $$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$

    - -

    $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$

    - - - -
    -
    -
    -
    -
    -
    # to categorical turns our integer vector into a onehot representation
    -from sklearn.metrics import accuracy_score
    -
    -# one-hot in numpy
    -def to_categorical_numpy(integer_vector):
    -    n_inputs = len(integer_vector)
    -    n_categories = np.max(integer_vector) + 1
    -    onehot_vector = np.zeros((n_inputs, n_categories))
    -    onehot_vector[range(n_inputs), integer_vector] = 1
    -    
    -    return onehot_vector
    -
    -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)
    -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)
    -
    -def feed_forward_train(X):
    -    # weighted sum of inputs to the hidden layer
    -    z_h = np.matmul(X, hidden_weights) + hidden_bias
    -    # activation in the hidden layer
    -    a_h = sigmoid(z_h)
    -    
    -    # weighted sum of inputs to the output layer
    -    z_o = np.matmul(a_h, output_weights) + output_bias
    -    # softmax output
    -    # axis 0 holds each input and axis 1 the probabilities of each category
    -    exp_term = np.exp(z_o)
    -    probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -    
    -    # for backpropagation need activations in hidden and output layers
    -    return a_h, probabilities
    -
    -def backpropagation(X, Y):
    -    a_h, probabilities = feed_forward_train(X)
    -    
    -    # error in the output layer
    -    error_output = probabilities - Y
    -    # error in the hidden layer
    -    error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)
    -    
    -    # gradients for the output layer
    -    output_weights_gradient = np.matmul(a_h.T, error_output)
    -    output_bias_gradient = np.sum(error_output, axis=0)
    -    
    -    # gradient for the hidden layer
    -    hidden_weights_gradient = np.matmul(X.T, error_hidden)
    -    hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -    return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient
    -
    -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -eta = 0.01
    -lmbd = 0.01
    -for i in range(1000):
    -    # calculate gradients
    -    dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)
    -    
    -    # regularization term gradients
    -    dWo += lmbd * output_weights
    -    dWh += lmbd * hidden_weights
    -    
    -    # update weights and biases
    -    output_weights -= eta * dWo
    -    output_bias -= eta * dBo
    -    hidden_weights -= eta * dWh
    -    hidden_bias -= eta * dBh
    -
    -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Improving performance

    - -

    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. -In order to obtain a network that does something useful, we will have to do a bit more work. -

    - -

    The choice of hyperparameters such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a grid-search is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates \( \eta = 10^{-6}, 10^{-5},...,10^{-1} \) with different regularization parameters \( \lambda = 10^{-6},...,10^{-0} \).

    - -

    Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an iteration, and a full training period -going through the entire dataset (\( n/M \) batches) an epoch. -

    - -

    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. You can find a summary of the video here. -

    - -









    -

    Full object-oriented implementation

    - -

    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. -

    - - - -
    -
    -
    -
    -
    -
    class NeuralNetwork:
    -    def __init__(
    -            self,
    -            X_data,
    -            Y_data,
    -            n_hidden_neurons=50,
    -            n_categories=10,
    -            epochs=10,
    -            batch_size=100,
    -            eta=0.1,
    -            lmbd=0.0):
    -
    -        self.X_data_full = X_data
    -        self.Y_data_full = Y_data
    -
    -        self.n_inputs = X_data.shape[0]
    -        self.n_features = X_data.shape[1]
    -        self.n_hidden_neurons = n_hidden_neurons
    -        self.n_categories = n_categories
    -
    -        self.epochs = epochs
    -        self.batch_size = batch_size
    -        self.iterations = self.n_inputs // self.batch_size
    -        self.eta = eta
    -        self.lmbd = lmbd
    -
    -        self.create_biases_and_weights()
    -
    -    def create_biases_and_weights(self):
    -        self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
    -        self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
    -
    -        self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
    -        self.output_bias = np.zeros(self.n_categories) + 0.01
    -
    -    def feed_forward(self):
    -        # feed-forward for training
    -        self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
    -        self.a_h = sigmoid(self.z_h)
    -
    -        self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
    -
    -        exp_term = np.exp(self.z_o)
    -        self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -
    -    def feed_forward_out(self, X):
    -        # feed-forward for output
    -        z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
    -        a_h = sigmoid(z_h)
    -
    -        z_o = np.matmul(a_h, self.output_weights) + self.output_bias
    -        
    -        exp_term = np.exp(z_o)
    -        probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
    -        return probabilities
    -
    -    def backpropagation(self):
    -        error_output = self.probabilities - self.Y_data
    -        error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
    -
    -        self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
    -        self.output_bias_gradient = np.sum(error_output, axis=0)
    -
    -        self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
    -        self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
    -
    -        if self.lmbd > 0.0:
    -            self.output_weights_gradient += self.lmbd * self.output_weights
    -            self.hidden_weights_gradient += self.lmbd * self.hidden_weights
    -
    -        self.output_weights -= self.eta * self.output_weights_gradient
    -        self.output_bias -= self.eta * self.output_bias_gradient
    -        self.hidden_weights -= self.eta * self.hidden_weights_gradient
    -        self.hidden_bias -= self.eta * self.hidden_bias_gradient
    -
    -    def predict(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return np.argmax(probabilities, axis=1)
    -
    -    def predict_probabilities(self, X):
    -        probabilities = self.feed_forward_out(X)
    -        return probabilities
    -
    -    def train(self):
    -        data_indices = np.arange(self.n_inputs)
    -
    -        for i in range(self.epochs):
    -            for j in range(self.iterations):
    -                # pick datapoints with replacement
    -                chosen_datapoints = np.random.choice(
    -                    data_indices, size=self.batch_size, replace=False
    -                )
    -
    -                # minibatch training data
    -                self.X_data = self.X_data_full[chosen_datapoints]
    -                self.Y_data = self.Y_data_full[chosen_datapoints]
    -
    -                self.feed_forward()
    -                self.backpropagation()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Evaluate model performance on test data

    - -

    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. -We measure the performance of the network using the accuracy score. -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 \( 1 \). -

    - -

    $$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$

    - -

    where \( I \) is the indicator function, \( 1 \) if \( \tilde{y}_i = y_i \) and \( 0 \) otherwise.

    - - - -
    -
    -
    -
    -
    -
    epochs = 100
    -batch_size = 100
    -
    -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                    n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -dnn.train()
    -test_predict = dnn.predict(X_test)
    -
    -# accuracy score from scikit library
    -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -
    -# equivalent in numpy
    -def accuracy_score_numpy(Y_test, Y_pred):
    -    return np.sum(Y_test == Y_pred) / len(Y_test)
    -
    -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Adjust hyperparameters

    - -

    We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around \( 98\% \) (\( 2\% \) error rate). -

    - - - -
    -
    -
    -
    -
    -
    eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -# store the models for later use
    -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -# grid search
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
    -                            n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)
    -        dnn.train()
    -        
    -        DNN_numpy[i][j] = dnn
    -        
    -        test_predict = dnn.predict(X_test)
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, you can also do this with matplotlib imshow
    -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)):
    -        dnn = DNN_numpy[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    scikit-learn implementation

    - -

    scikit-learn focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -MPLRegressor, and Multi Layer Perceptron outputting labels, -MLPClassifier. We will see how simple it is to use these classes. -

    - -

    scikit-learn implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. -

    - - - -
    -
    -
    -
    -
    -
    from sklearn.neural_network import MLPClassifier
    -# store models for later use
    -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',
    -                            alpha=lmbd, learning_rate_init=eta, max_iter=epochs)
    -        dnn.fit(X_train, Y_train)
    -        
    -        DNN_scikit[i][j] = dnn
    -        
    -        print("Learning rate  = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Accuracy score on test set: ", dnn.score(X_test, Y_test))
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualization

    - - -
    -
    -
    -
    -
    -
    # optional
    -# 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)):
    -        dnn = DNN_scikit[i][j]
    -        
    -        train_pred = dnn.predict(X_train) 
    -        test_pred = dnn.predict(X_test)
    -
    -        train_accuracy[i][j] = accuracy_score(Y_train, train_pred)
    -        test_accuracy[i][j] = accuracy_score(Y_test, test_pred)
    -
    -        
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -









    Building neural networks in Tensorflow and Keras

    @@ -2328,7 +999,7 @@ plt.show()









    -

    The Breast Cancer Data, now with Keras

    +

    Using Pytorch with the full MNIST data set

    @@ -2337,171 +1008,82 @@ plt.show()
    -
    import tensorflow as tf
    -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
    -import numpy as np
    -import matplotlib.pyplot as plt
    -import seaborn as sns
    -from sklearn.model_selection import train_test_split as splitter
    -from sklearn.datasets import load_breast_cancer
    -import pickle
    -import os 
    +  
    import torch
    +import torch.nn as nn
    +import torch.optim as optim
    +import torchvision
    +import torchvision.transforms as transforms
    +
    +# Device configuration: use GPU if available
    +device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    +
    +# MNIST dataset (downloads if not already present)
    +transform = transforms.Compose([
    +    transforms.ToTensor(),
    +    transforms.Normalize((0.5,), (0.5,))  # normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range)
    +])
    +train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
    +test_dataset  = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
    +
    +train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
    +test_loader  = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
     
     
    -"""Load breast cancer dataset"""
    +class NeuralNet(nn.Module):
    +    def __init__(self):
    +        super(NeuralNet, self).__init__()
    +        self.fc1 = nn.Linear(28*28, 100)   # first hidden layer (784 -> 100)
    +        self.fc2 = nn.Linear(100, 100)    # second hidden layer (100 -> 100)
    +        self.fc3 = nn.Linear(100, 10)     # output layer (100 -> 10 classes)
    +    def forward(self, x):
    +        x = x.view(x.size(0), -1)         # flatten images into vectors of size 784
    +        x = torch.relu(self.fc1(x))       # hidden layer 1 + ReLU activation
    +        x = torch.relu(self.fc2(x))       # hidden layer 2 + ReLU activation
    +        x = self.fc3(x)                   # output layer (logits for 10 classes)
    +        return x
     
    -np.random.seed(0)        #create same seed for random number every time
    -
    -cancer=load_breast_cancer()      #Download breast cancer dataset
    -
    -inputs=cancer.data                     #Feature matrix of 569 rows (samples) and 30 columns (parameters)
    -outputs=cancer.target                  #Label array of 569 rows (0 for benign and 1 for malignant)
    -labels=cancer.feature_names[0:30]
    -
    -print('The content of the breast cancer dataset is:')      #Print information about the datasets
    -print(labels)
    -print('-------------------------')
    -print("inputs =  " + str(inputs.shape))
    -print("outputs =  " + str(outputs.shape))
    -print("labels =  "+ str(labels.shape))
    -
    -x=inputs      #Reassign the Feature and Label matrices to other variables
    -y=outputs
    -
    -#%% 
    -
    -# Visualisation of dataset (for correlation analysis)
    -
    -plt.figure()
    -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean perimeter',fontweight='bold')
    -plt.show()
    -
    -plt.figure()
    -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    -plt.xlabel('Mean compactness',fontweight='bold')
    -plt.ylabel('Mean concavity',fontweight='bold')
    -plt.show()
    +model = NeuralNet().to(device)
     
     
    -plt.figure()
    -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean radius',fontweight='bold')
    -plt.ylabel('Mean texture',fontweight='bold')
    -plt.show()
    +criterion = nn.CrossEntropyLoss()
    +optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
     
    -plt.figure()
    -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    -plt.xlabel('Mean perimeter',fontweight='bold')
    -plt.ylabel('Mean compactness',fontweight='bold')
    -plt.show()
    +num_epochs = 10
    +for epoch in range(num_epochs):
    +    model.train()  # set model to training mode
    +    running_loss = 0.0
    +    for images, labels in train_loader:
    +        # Move data to device (GPU if available, else CPU)
    +        images, labels = images.to(device), labels.to(device)
    +
    +        optimizer.zero_grad()            # reset gradients to zero
    +        outputs = model(images)          # forward pass: compute predictions
    +        loss = criterion(outputs, labels)  # compute cross-entropy loss
    +        loss.backward()                 # backpropagate to compute gradients
    +        optimizer.step()                # update weights using SGD step 
    +
    +        running_loss += loss.item()
    +    # Compute average loss over all batches in this epoch
    +    avg_loss = running_loss / len(train_loader)
    +    print(f"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}")
    +
    +#Evaluation on the Test Set
     
     
    -# Generate training and testing datasets
     
    -#Select features relevant to classification (texture,perimeter,compactness and symmetery) 
    -#and add to input matrix
    +model.eval()  # set model to evaluation mode 
    +correct = 0
    +total = 0
    +with torch.no_grad():  # disable gradient calculation for evaluation 
    +    for images, labels in test_loader:
    +        images, labels = images.to(device), labels.to(device)
    +        outputs = model(images)
    +        _, predicted = torch.max(outputs, dim=1)  # class with highest score
    +        total += labels.size(0)
    +        correct += (predicted == labels).sum().item()
     
    -temp1=np.reshape(x[:,1],(len(x[:,1]),1))
    -temp2=np.reshape(x[:,2],(len(x[:,2]),1))
    -X=np.hstack((temp1,temp2))      
    -temp=np.reshape(x[:,5],(len(x[:,5]),1))
    -X=np.hstack((X,temp))       
    -temp=np.reshape(x[:,8],(len(x[:,8]),1))
    -X=np.hstack((X,temp))       
    -
    -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1)   #Split datasets into training and testing
    -
    -y_train=to_categorical(y_train)     #Convert labels to categorical when using categorical cross entropy
    -y_test=to_categorical(y_test)
    -
    -del temp1,temp2,temp
    -
    -# %%
    -
    -# Define tunable parameters"
    -
    -eta=np.logspace(-3,-1,3)                    #Define vector of learning rates (parameter to SGD optimiser)
    -lamda=0.01                                  #Define hyperparameter
    -n_layers=2                                  #Define number of hidden layers in the model
    -n_neuron=np.logspace(0,3,4,dtype=int)       #Define number of neurons per layer
    -epochs=100                                   #Number of reiterations over the input data
    -batch_size=100                              #Number of samples per gradient update
    -
    -# %%
    -
    -"""Define function to return Deep Neural Network model"""
    -
    -def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
    -    model=Sequential()      
    -    for i in range(n_layers):       #Run loop to add hidden layers to the model
    -        if (i==0):                  #First layer requires input dimensions
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
    -        else:                       #Subsequent layers are capable of automatic shape inferencing
    -            model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
    -    model.add(Dense(2,activation='softmax'))  #2 outputs - ordered and disordered (softmax for prob)
    -    sgd=optimizers.SGD(learning_rate=eta)
    -    model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
    -    return model
    -
    -    
    -Train_accuracy=np.zeros((len(n_neuron),len(eta)))      #Define matrices to store accuracy scores as a function
    -Test_accuracy=np.zeros((len(n_neuron),len(eta)))       #of learning rate and number of hidden neurons for 
    -
    -for i in range(len(n_neuron)):     #run loops over hidden neurons and learning rates to calculate 
    -    for j in range(len(eta)):      #accuracy scores 
    -        DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
    -        DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
    -        Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
    -        Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
    -               
    -
    -def plot_data(x,y,data,title=None):
    -
    -    # plot results
    -    fontsize=16
    -
    -
    -    fig = plt.figure()
    -    ax = fig.add_subplot(111)
    -    cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
    -    
    -    cbar=fig.colorbar(cax)
    -    cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    -    cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    -    cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
    -
    -    # put text on matrix elements
    -    for i, x_val in enumerate(np.arange(len(x))):
    -        for j, y_val in enumerate(np.arange(len(y))):
    -            c = "${0:.1f}\\%$".format( 100*data[j,i])  
    -            ax.text(x_val, y_val, c, va='center', ha='center')
    -
    -    # convert axis vaues to to string labels
    -    x=[str(i) for i in x]
    -    y=[str(i) for i in y]
    -
    -
    -    ax.set_xticklabels(['']+x)
    -    ax.set_yticklabels(['']+y)
    -
    -    ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    -    ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    -    if title is not None:
    -        ax.set_title(title)
    -
    -    plt.tight_layout()
    -
    -    plt.show()
    -    
    -plot_data(eta,n_neuron,Train_accuracy, 'training')
    -plot_data(eta,n_neuron,Test_accuracy, 'testing')
    +accuracy = 100 * correct / total
    +print(f"Test Accuracy: {accuracy:.2f}%")
     
    @@ -2519,7 +1101,81 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing&









    -

    Building a neural network code

    +

    And a similar example using Tensorflow with Keras

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +from tensorflow import keras
    +from tensorflow.keras import layers, regularizers
    +
    +# Check for GPU (TensorFlow will use it automatically if available)
    +gpus = tf.config.list_physical_devices('GPU')
    +print(f"GPUs available: {gpus}")
    +
    +# 1) Load and preprocess MNIST
    +(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
    +# Normalize to [0, 1]
    +x_train = (x_train.astype("float32") / 255.0)
    +x_test  = (x_test.astype("float32") / 255.0)
    +
    +# 2) Build the model: 784 -> 100 -> 100 -> 10
    +l2_reg = 1e-4  # L2 regularization strength
    +
    +model = keras.Sequential([
    +    layers.Input(shape=(28, 28)),
    +    layers.Flatten(),
    +    layers.Dense(100, activation="relu",
    +                 kernel_regularizer=regularizers.l2(l2_reg)),
    +    layers.Dense(100, activation="relu",
    +                 kernel_regularizer=regularizers.l2(l2_reg)),
    +    layers.Dense(10, activation="softmax")  # output probabilities for 10 classes
    +])
    +
    +# 3) Compile with SGD + weight decay via L2 regularizers
    +model.compile(
    +    optimizer=keras.optimizers.SGD(learning_rate=0.01),
    +    loss="sparse_categorical_crossentropy",
    +    metrics=["accuracy"],
    +)
    +
    +model.summary()
    +
    +# 4) Train
    +history = model.fit(
    +    x_train, y_train,
    +    epochs=10,
    +    batch_size=64,
    +    validation_split=0.1,  # optional: monitor validation during training
    +    verbose=1
    +)
    +
    +# 5) Evaluate on test set
    +test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
    +print(f"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Building our own neural network code

    Here we present a flexible object oriented codebase for a feed forward neural network, along with a demonstration of how @@ -6539,7 +5195,7 @@ $$

    - © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2025, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/week43/ipynb/.ipynb_checkpoints/week43-checkpoint.ipynb b/doc/pub/week43/ipynb/.ipynb_checkpoints/week43-checkpoint.ipynb index d9260ad4f..713df5efc 100644 --- a/doc/pub/week43/ipynb/.ipynb_checkpoints/week43-checkpoint.ipynb +++ b/doc/pub/week43/ipynb/.ipynb_checkpoints/week43-checkpoint.ipynb @@ -2,54 +2,3663 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "b10156d4", + "metadata": { + "editable": true + }, "source": [ - "\n", - "# Week 43: Solving Differential Equations with Deep Learning and Dimensionality Reduction methods\n", - "\n", - " \n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "f85baa2f", + "metadata": { + "editable": true + }, + "source": [ + "# Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway\n", "\n", -<<<<<<< HEAD - "Date: **Oct 22, 2020**\n", -======= - "Date: **Oct 23, 2020**\n", ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 + "Date: **October 20, 2025**" + ] + }, + { + "cell_type": "markdown", + "id": "543fad4a", + "metadata": { + "editable": true + }, + "source": [ + "## Plans for week 43\n", "\n", - "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "**Material for the lecture on Monday October 20, 2025.**\n", + "\n", + "1. Reminder from last week, see also lecture notes from week 42 at as well as those from week 41, see see . \n", + "\n", + "2. Building our own Feed-forward Neural Network.\n", + "\n", + "3. Coding examples using Tensorflow/Keras and Pytorch examples. The Pytorch examples are adapted from Rashcka's text, see chapters 11-13.. \n", + "\n", + "4. Start discussions on how to use neural networks for solving differential equations (ordinary and partial ones). This topic continues next week as well.\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "72acb4e9", + "metadata": { + "editable": true + }, + "source": [ + "## Exercises and lab session week 43\n", + "**Lab sessions on Tuesday and Wednesday.**\n", + "\n", + "1. Work on writing your own neural network code and discussions of project 2. If you didn't get time to do the exercises from the two last weeks, we recommend doing so as these exercises give you the basic elements of a neural network code.\n", + "\n", + "2. The exercises this week are tailored to the optional part of project 2, and deal with studying ways to display results from classification problems" + ] + }, + { + "cell_type": "markdown", + "id": "361768dc", + "metadata": { + "editable": true + }, + "source": [ + "## Using Automatic differentiation\n", + "\n", + "In our discussions of ordinary differential equations and neural network codes\n", + "we will also study the usage of Autograd, see for example in computing gradients for deep learning. For the documentation of Autograd and examples see the Autograd documentation at and the lecture slides from week 41, see ." + ] + }, + { + "cell_type": "markdown", + "id": "3e058671", + "metadata": { + "editable": true + }, + "source": [ + "## Back propagation and automatic differentiation\n", + "\n", + "For more details on the back propagation algorithm and automatic differentiation see\n", + "1. \n", + "\n", + "2. \n", + "\n", + "3. Slides 12-44 at " + ] + }, + { + "cell_type": "markdown", + "id": "8cbbf2bf", + "metadata": { + "editable": true + }, + "source": [ + "## Lecture Monday October 20" + ] + }, + { + "cell_type": "markdown", + "id": "78e2de21", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations\n", + "This is a reminder from last week.\n", + "\n", + "**The architecture (our model).**\n", + "\n", + "1. Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays)\n", + "\n", + "2. Define the number of hidden layers and hidden nodes\n", + "\n", + "3. Define activation functions for hidden layers and output layers\n", + "\n", + "4. Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates\n", + "\n", + "5. Define cost function and possible regularization terms with hyperparameters\n", + "\n", + "6. Initialize weights and biases\n", + "\n", + "7. Fix number of iterations for the feed forward part and back propagation part" + ] + }, + { + "cell_type": "markdown", + "id": "41a3dc23", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the back propagation algorithm, part 1\n", + "\n", + "Let us write this out in the form of an algorithm.\n", + "\n", + "**First**, we set up the input data $\\boldsymbol{x}$ and the activations\n", + "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", + "the pertinent outputs $\\boldsymbol{a}^1$.\n", + "\n", + "**Secondly**, we perform then the feed forward till we reach the output\n", + "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", + "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", + "$l=1,2,3,\\dots,L$.\n", + "\n", + "**Notation**: The first hidden layer has $l=1$ as label and the final output layer has $l=L$." + ] + }, + { + "cell_type": "markdown", + "id": "0e4ac2c0", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the back propagation algorithm, part 2\n", + "\n", + "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" + ] + }, + { + "cell_type": "markdown", + "id": "e9fd2f83", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j^L = \\sigma'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "16e2b900", + "metadata": { + "editable": true + }, + "source": [ + "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,1$ as" + ] + }, + { + "cell_type": "markdown", + "id": "f9f4b9d8", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "01be6441", + "metadata": { + "editable": true + }, + "source": [ + "## Setting up the Back propagation algorithm, part 3\n", + "\n", + "Finally, we update the weights and the biases using gradient descent\n", + "for each $l=L-1,L-2,\\dots,1$ (the first hidden layer) and update the weights and biases\n", + "according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "ce898b85", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4e2e7314", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b7114295", + "metadata": { + "editable": true + }, + "source": [ + "with $\\eta$ being the learning rate." + ] + }, + { + "cell_type": "markdown", + "id": "69dfa048", + "metadata": { + "editable": true + }, + "source": [ + "## Updating the gradients\n", + "\n", + "With the back propagate error for each $l=L-1,L-2,\\dots,1$ as" + ] + }, + { + "cell_type": "markdown", + "id": "6efa469c", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}\\sigma'(z_j^l),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "076e4937", + "metadata": { + "editable": true + }, + "source": [ + "we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,1$ and update the weights and biases according to the rules" + ] + }, + { + "cell_type": "markdown", + "id": "1072f5a1", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "w_{ij}^l\\leftarrow = w_{ij}^l- \\eta \\delta_j^la_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f77a7074", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f12effab", + "metadata": { + "editable": true + }, + "source": [ + "## Activation functions\n", + "\n", + "A property that characterizes a neural network, other than its\n", + "connectivity, is the choice of activation function(s). The following\n", + "restrictions are imposed on an activation function for an FFNN to\n", + "fulfill the universal approximation theorem\n", + "\n", + " * Non-constant\n", + "\n", + " * Bounded\n", + "\n", + " * Monotonically-increasing\n", + "\n", + " * Continuous" + ] + }, + { + "cell_type": "markdown", + "id": "31eb54b1", + "metadata": { + "editable": true + }, + "source": [ + "### Activation functions, examples\n", + "\n", + "Typical examples are the logistic *Sigmoid*" + ] + }, + { + "cell_type": "markdown", + "id": "7a549168", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sigma(x) = \\frac{1}{1 + e^{-x}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ce35ae73", + "metadata": { + "editable": true + }, + "source": [ + "and the *hyperbolic tangent* function" + ] + }, + { + "cell_type": "markdown", + "id": "d6cdfc89", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sigma(x) = \\tanh(x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ddd59bb0", + "metadata": { + "editable": true + }, + "source": [ + "## The RELU function family\n", + "\n", + "The ReLU activation function suffers from a problem known as the dying\n", + "ReLUs: during training, some neurons effectively die, meaning they\n", + "stop outputting anything other than 0.\n", + "\n", + "In some cases, you may find that half of your network’s neurons are\n", + "dead, especially if you used a large learning rate. During training,\n", + "if a neuron’s weights get updated such that the weighted sum of the\n", + "neuron’s inputs is negative, it will start outputting 0. When this\n", + "happen, the neuron is unlikely to come back to life since the gradient\n", + "of the ReLU function is 0 when its input is negative." + ] + }, + { + "cell_type": "markdown", + "id": "f2a78e55", + "metadata": { + "editable": true + }, + "source": [ + "## ELU function\n", + "\n", + "To solve this problem, nowadays practitioners use a variant of the\n", + "ReLU function, such as the leaky ReLU discussed above or the so-called\n", + "exponential linear unit (ELU) function" + ] + }, + { + "cell_type": "markdown", + "id": "cde73faf", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "08048672", + "metadata": { + "editable": true + }, + "source": [ + "## Which activation function should we use?\n", + "\n", + "In general it seems that the ELU activation function is better than\n", + "the leaky ReLU function (and its variants), which is better than\n", + "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", + "than the logistic function.\n", + "\n", + "If runtime performance is an issue, then you may opt for the leaky\n", + "ReLU function over the ELU function If you don’t want to tweak yet\n", + "another hyperparameter, you may just use the default $\\alpha$ of\n", + "$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and\n", + "computing power, you can use cross-validation or bootstrap to evaluate\n", + "other activation functions." + ] + }, + { + "cell_type": "markdown", + "id": "a7085280", + "metadata": { + "editable": true + }, + "source": [ + "## More on activation functions, output layers\n", + "\n", + "In most cases you can use the ReLU activation function in the hidden\n", + "layers (or one of its variants).\n", + "\n", + "It is a bit faster to compute than other activation functions, and the\n", + "gradient descent optimization does in general not get stuck.\n", + "\n", + "**For the output layer:**\n", + "\n", + "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", + "\n", + "* For regression tasks, you can simply use no activation function at all." + ] + }, + { + "cell_type": "markdown", + "id": "291e4fb2", + "metadata": { + "editable": true + }, + "source": [ + "## Building neural networks in Tensorflow and Keras\n", + "\n", + "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", + "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", + "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", + "\n", + "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", + "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", + "NumPy arrays." + ] + }, + { + "cell_type": "markdown", + "id": "a8c5f4c2", + "metadata": { + "editable": true + }, + "source": [ + "## Tensorflow\n", + "\n", + "Tensorflow is an open source library machine learning library\n", + "developed by the Google Brain team for internal use. It was released\n", + "under the Apache 2.0 open source license in November 9, 2015.\n", + "\n", + "Tensorflow is a computational framework that allows you to construct\n", + "machine learning models at different levels of abstraction, from\n", + "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", + "that Tensorflow is built upon. The higher levels of abstraction are\n", + "simpler to use, but less flexible, and our choice of implementation\n", + "should reflect the problems we are trying to solve.\n", + "\n", + "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", + "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", + "to represent your model, and then create a Tensorflow *session* to run the graph.\n", + "\n", + "In this guide we will analyze the same data as we did in our NumPy and\n", + "scikit-learn tutorial, gathered from the MNIST database of images. We\n", + "will give an introduction to the lower level Python Application\n", + "Program Interfaces (APIs), and see how we use them to build our graph.\n", + "Then we will build (effectively) the same graph in Keras, to see just\n", + "how simple solving a machine learning problem can be.\n", + "\n", + "To install tensorflow on Unix/Linux systems, use pip as" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "9a0aac03", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "pip3 install tensorflow" + ] + }, + { + "cell_type": "markdown", + "id": "ca0c7865", + "metadata": { + "editable": true + }, + "source": [ + "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", + "(current release of CPU-only TensorFlow)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "d0c581f7", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "conda create -n tf tensorflow\n", + "conda activate tf" + ] + }, + { + "cell_type": "markdown", + "id": "fe086bc9", + "metadata": { + "editable": true + }, + "source": [ + "To install the current release of GPU TensorFlow" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "f551fad9", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "conda create -n tf-gpu tensorflow-gpu\n", + "conda activate tf-gpu" + ] + }, + { + "cell_type": "markdown", + "id": "58152cef", + "metadata": { + "editable": true + }, + "source": [ + "## Using Keras\n", + "\n", + "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", + "that supports Tensorflow, CTNK and Theano as backends. \n", + "If you have Anaconda installed you may run the following command" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "579b6a4a", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "conda install keras" + ] + }, + { + "cell_type": "markdown", + "id": "5da15206", + "metadata": { + "editable": true + }, + "source": [ + "You can look up the [instructions here](https://keras.io/) for more information.\n", + "\n", + "We will to a large extent use **keras** in this course." + ] + }, + { + "cell_type": "markdown", + "id": "cc970d32", + "metadata": { + "editable": true + }, + "source": [ + "## Collect and pre-process data\n", + "\n", + "Let us look again at the MINST data set." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "a4f2c8a8", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "inputs = (n_inputs, pixel_width, pixel_height) = (1797, 8, 8)\n", + "labels = (n_inputs) = (1797,)\n", + "X = (n_inputs, n_features) = (1797, 64)\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAA7YAAADICAYAAADcOn20AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8fJSN1AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAQx0lEQVR4nO3dbWydZRkH8OuMjklYaEHMxla3ji46/KBdiItodB2oEUVXDNMYois6QgLCkKkhEGwHGDCaWIxODY510SUuJmSdZr4AdjUmxPBWEhaNjlBEzSY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2RFOT010mZ/7rRNUgtmzZUkVE9dBDD530fY4ePVq98MIL1ac+9alq+fLlx/xZRFSnnXZatW/fvmN+f9myZdXSpUvHbrvqqququXPnVk8//fQx9//KV75SRUS1Z8+eYzJ7enqO+b329vaqvb39pNb7pz/9qbrggguqiBj7WbNmTXXo0KGTfcrUqUaY//F+/OMfVxFR3XHHHa/4vtQne4BG1ijzf8cdd4yd/9Rqtermm28+6ftSv8x/4/BR5OP84Ac/iHe84x0xd+7caGpqitmzZ8fmzZvj17/+9ct+96KLLop58+aN/fcpp5wSH/3oR2Pv3r3xhz/8ISIifvSjH8WqVatiwYIFcfTo0bGfiy++OCIihoaGJl3P3r17Y+/evf913c8//3ysXr06/vrXv8a2bdviF7/4RWzatCl++ctfxoc+9KGG+1Y0Xp2s83+8zZs3R1NTU3R3d7/i+9LY7AEaWfb57+7ujoceeih++tOfxuc///n48pe/HNdee+1J35/GZv7za6Br0//dvffeGx/5yEdizZo18bnPfS7mz58fTU1N8c1vfjPuueeel/3+/PnzJ7ztwIED0draGvv3748f/vCHY/8P7PH+8pe/FFn7l770pRgeHo6nn346zjnnnIiIeOc73xnLli2LCy+8MLZt2xZr164t8ljUp8zzf3zmzp074wMf+MAJ1wgTsQdoZPUw//Pnzx9bw3vf+94488wz48Ybb4xPfvKTvkCTSZn/+qDYjvO9730vlixZEtu3b49arTZ2++HDh0/4+/v27Zvwtte+9rUREXH22WfHm9/85vjiF794wowFCxb8r8uOiIjh4eFYuHDhWKl9yVvf+taIiHjiiSeKPA71K/P8j/fd7343jhw54gtzeMXsARpZvcz/eCtWrIiIiN/+9rcNc2LPq2P+64NiO06tVotTTz31mIHet2/fhN+I9sADD8T+/fvHPorw4osvxvbt26O9vX3sn1245JJLYteuXdHe3h5nnnnmlK19wYIF8cADD8Qf//jHWLhw4djtDz74YETEy/4ZCDhe5vkfb/PmzbFgwYKxj/rAybIHaGT1Mv/jDQ4ORkTE0qVLp/2xycX814eGK7Y///nPT/jtYu9///vjkksuiXvvvTeuvvrquOyyy+KZZ56J2267Lc4555z43e9+97L7nH322XHhhRfGLbfcMvaNaL/5zW+O+brvW2+9Ne677754+9vfHtddd1288Y1vjEOHDsXIyEjs2rUrvvWtb01aOl8axv/2Gftrrrkmtm3bFu95z3vixhtvjNe//vXxxBNPxO233x7z5s2Lyy+//CRfIepZvc7/S371q1/Fnj174qabbmqor7fn5NkDNLJ6nf+enp7Yv39/vOtd74qFCxfG6Oho/OQnP4m777471qxZE+eff/5JvkLUM/PfAGb626umy0vfiDbRz1NPPVVVVVXdeeedVVtbWzVnzpzqvPPOq+6+++6qp6enOv6liojqmmuuqTZt2lS1t7dXs2fPrpYtW1Zt27btZY/97LPPVtddd121ZMmSavbs2dVZZ51VnX/++dXNN99c/f3vfz8m8/hvRFu8eHG1ePHik3qOjz76aHXppZdWra2t1Zw5c6pzzz23WrduXfX73//+Fb1W1J9GmP+qqqorr7yyqtVq1ZNPPnnS96Ex2AM0snqf/507d1bvfve7q3nz5lVNTU3V3LlzqxUrVlRf+9rXqhdeeOEVv17UF/PfOGpVVVWlyzIAAABMF//cDwAAAKkptgAAAKSm2AIAAJCaYgsAAEBqii0AAACpKbYAAACkptgCAACQWtNML6CU/v7+onm9vb1F81paWormRUT09fUVzevs7Cyax/TZvXt30bzS+2nHjh1F8yIiDh48WDRvcHCwaJ79NL0GBgaK5q1fv75o3lQove/b2tqK5jGxkZGRonmlzwdKHwNKv19HRDQ3NxfNGx4eLppnP01udHS0aN7/+x4o/XwjzOyJuGILAABAaootAAAAqSm2AAAApKbYAgAAkJpiCwAAQGqKLQAAAKkptgAAAKSm2AIAAJCaYgsAAEBqii0AAACpKbYAAACkptgCAACQmmILAABAaootAAAAqSm2AAAApKbYAgAAkJpiCwAAQGqKLQAAAKk1zdQD7969u2jeFVdcUTRv9erVRfNaWlqK5kVEdHV1Fc0bHR0tmsf0uf7664vmlZ6F7u7uonkREXfddVfRvKnYo0xsZGSkaF7p98MMduzYUTSv9PsIE/t/f623bt1aNG9wcLB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sAAABSU2wBAABITbEFAAAgNcUWAACA1P4F8SqxxH5w1EMAAAAASUVORK5CYII=", + "text/plain": [ + "
    " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%matplotlib inline\n", + "\n", + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import tensorflow as tf\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "d0c06f34", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", + "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", + "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", + "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", + "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# one-hot representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "8272ca95", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "\n", + "epochs = 100\n", + "batch_size = 100\n", + "n_neurons_layer1 = 100\n", + "n_neurons_layer2 = 50\n", + "n_categories = 10\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)\n", + "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", + " model = Sequential()\n", + " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(Dense(n_categories, activation='softmax'))\n", + " \n", + " sgd = optimizers.SGD(learning_rate=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "616613a7", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n", + "2025-10-20 13:19:24.847167: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "12/12 [==============================] - 1s 77ms/step - loss: 2.3648 - accuracy: 0.0833\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1e-05\n", + "Lambda = 1e-05\n", + "Test accuracy: 0.083\n", + "\n", + "12/12 [==============================] - 0s 16ms/step - loss: 2.5249 - accuracy: 0.1278\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1e-05\n", + "Lambda = 0.0001\n", + "Test accuracy: 0.128\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: 2.6284 - accuracy: 0.1250\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1e-05\n", + "Lambda = 0.001\n", + "Test accuracy: 0.125\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: 3.8276 - accuracy: 0.0889\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1e-05\n", + "Lambda = 0.01\n", + "Test accuracy: 0.089\n", + "\n", + "12/12 [==============================] - 0s 13ms/step - loss: 17.2502 - accuracy: 0.1056\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1e-05\n", + "Lambda = 0.1\n", + "Test accuracy: 0.106\n", + "\n", + "12/12 [==============================] - 0s 15ms/step - loss: 137.7438 - accuracy: 0.1167\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1e-05\n", + "Lambda = 1.0\n", + "Test accuracy: 0.117\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 791.1546 - accuracy: 0.1028\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1e-05\n", + "Lambda = 10.0\n", + "Test accuracy: 0.103\n", + "\n", + "12/12 [==============================] - 0s 18ms/step - loss: 2.4095 - accuracy: 0.0917\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.0001\n", + "Lambda = 1e-05\n", + "Test accuracy: 0.092\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "12/12 [==============================] - 0s 13ms/step - loss: 2.4702 - accuracy: 0.1167\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.0001\n", + "Lambda = 0.0001\n", + "Test accuracy: 0.117\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.4999 - accuracy: 0.0917\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.0001\n", + "Lambda = 0.001\n", + "Test accuracy: 0.092\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: 3.8617 - accuracy: 0.0889\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.0001\n", + "Lambda = 0.01\n", + "Test accuracy: 0.089\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: 15.9813 - accuracy: 0.1139\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.0001\n", + "Lambda = 0.1\n", + "Test accuracy: 0.114\n", + "\n", + "12/12 [==============================] - 0s 13ms/step - loss: 81.3855 - accuracy: 0.0889\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.0001\n", + "Lambda = 1.0\n", + "Test accuracy: 0.089\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: 6.0620 - accuracy: 0.1139\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.0001\n", + "Lambda = 10.0\n", + "Test accuracy: 0.114\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 2.2036 - accuracy: 0.3917\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.001\n", + "Lambda = 1e-05\n", + "Test accuracy: 0.392\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.1645 - accuracy: 0.3694\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.001\n", + "Lambda = 0.0001\n", + "Test accuracy: 0.369\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 2.3489 - accuracy: 0.3333\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.001\n", + "Lambda = 0.001\n", + "Test accuracy: 0.333\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 3.5798 - accuracy: 0.2611\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.001\n", + "Lambda = 0.01\n", + "Test accuracy: 0.261\n", + "\n", + "12/12 [==============================] - 0s 15ms/step - loss: 10.2003 - accuracy: 0.4333\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.001\n", + "Lambda = 0.1\n", + "Test accuracy: 0.433\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 2.6594 - accuracy: 0.0889\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.001\n", + "Lambda = 1.0\n", + "Test accuracy: 0.089\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.3030 - accuracy: 0.1167\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.001\n", + "Lambda = 10.0\n", + "Test accuracy: 0.117\n", + "\n", + "12/12 [==============================] - 0s 12ms/step - loss: 1.0555 - accuracy: 0.8694\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.01\n", + "Lambda = 1e-05\n", + "Test accuracy: 0.869\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 1.1238 - accuracy: 0.8583\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.01\n", + "Lambda = 0.0001\n", + "Test accuracy: 0.858\n", + "\n", + "12/12 [==============================] - 0s 15ms/step - loss: 1.2342 - accuracy: 0.8806\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.01\n", + "Lambda = 0.001\n", + "Test accuracy: 0.881\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 2.1114 - accuracy: 0.8833\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.01\n", + "Lambda = 0.01\n", + "Test accuracy: 0.883\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.2776 - accuracy: 0.5139\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.01\n", + "Lambda = 0.1\n", + "Test accuracy: 0.514\n", + "\n", + "12/12 [==============================] - 0s 15ms/step - loss: 2.3079 - accuracy: 0.0778\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.01\n", + "Lambda = 1.0\n", + "Test accuracy: 0.078\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 2.3081 - accuracy: 0.0778\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.01\n", + "Lambda = 10.0\n", + "Test accuracy: 0.078\n", + "\n", + "12/12 [==============================] - 0s 16ms/step - loss: 0.1069 - accuracy: 0.9722\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.1\n", + "Lambda = 1e-05\n", + "Test accuracy: 0.972\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 0.1282 - accuracy: 0.9667\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.1\n", + "Lambda = 0.0001\n", + "Test accuracy: 0.967\n", + "\n", + "12/12 [==============================] - 0s 13ms/step - loss: 0.2611 - accuracy: 0.9694\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.1\n", + "Lambda = 0.001\n", + "Test accuracy: 0.969\n", + "\n", + "12/12 [==============================] - 0s 15ms/step - loss: 0.4928 - accuracy: 0.9639\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.1\n", + "Lambda = 0.01\n", + "Test accuracy: 0.964\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 1.6045 - accuracy: 0.6222\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.1\n", + "Lambda = 0.1\n", + "Test accuracy: 0.622\n", + "\n", + "12/12 [==============================] - 0s 16ms/step - loss: 2.3218 - accuracy: 0.0861\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.1\n", + "Lambda = 1.0\n", + "Test accuracy: 0.086\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: 1597.5353 - accuracy: 0.0444\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 0.1\n", + "Lambda = 10.0\n", + "Test accuracy: 0.044\n", + "\n", + "12/12 [==============================] - 0s 12ms/step - loss: 0.0781 - accuracy: 0.9806\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1.0\n", + "Lambda = 1e-05\n", + "Test accuracy: 0.981\n", + "\n", + "12/12 [==============================] - 0s 15ms/step - loss: 0.0868 - accuracy: 0.9861\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1.0\n", + "Lambda = 0.0001\n", + "Test accuracy: 0.986\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 0.4859 - accuracy: 0.9222\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1.0\n", + "Lambda = 0.001\n", + "Test accuracy: 0.922\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: 2.9575 - accuracy: 0.1583\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1.0\n", + "Lambda = 0.01\n", + "Test accuracy: 0.158\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: 2.5299 - accuracy: 0.0889\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1.0\n", + "Lambda = 0.1\n", + "Test accuracy: 0.089\n", + "\n", + "12/12 [==============================] - 0s 12ms/step - loss: 371.5039 - accuracy: 0.1139\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1.0\n", + "Lambda = 1.0\n", + "Test accuracy: 0.114\n", + "\n", + "12/12 [==============================] - 0s 17ms/step - loss: nan - accuracy: 0.0778\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 1.0\n", + "Lambda = 10.0\n", + "Test accuracy: 0.078\n", + "\n", + "12/12 [==============================] - 0s 11ms/step - loss: 4.4885 - accuracy: 0.1056\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 10.0\n", + "Lambda = 1e-05\n", + "Test accuracy: 0.106\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.4071 - accuracy: 0.1250\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 10.0\n", + "Lambda = 0.0001\n", + "Test accuracy: 0.125\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.4936 - accuracy: 0.1167\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 10.0\n", + "Lambda = 0.001\n", + "Test accuracy: 0.117\n", + "\n", + "12/12 [==============================] - 0s 13ms/step - loss: 2.4569 - accuracy: 0.0861\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 10.0\n", + "Lambda = 0.01\n", + "Test accuracy: 0.086\n", + "\n", + "12/12 [==============================] - 0s 16ms/step - loss: 959.3554 - accuracy: 0.1167\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 10.0\n", + "Lambda = 0.1\n", + "Test accuracy: 0.117\n", + "\n", + "12/12 [==============================] - 0s 14ms/step - loss: nan - accuracy: 0.0778\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Learning rate = 10.0\n", + "Lambda = 1.0\n", + "Test accuracy: 0.078\n", + "\n", + "12/12 [==============================] - 0s 13ms/step - loss: nan - accuracy: 0.0778\n", + "Learning rate = 10.0\n", + "Lambda = 10.0\n", + "Test accuracy: 0.078\n", + "\n" + ] + } + ], + "source": [ + "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", + " eta=eta, lmbd=lmbd)\n", + " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = DNN.evaluate(X_test, Y_test)\n", + " \n", + " DNN_keras[i][j] = DNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "f57a7b70", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "45/45 [==============================] - 1s 15ms/step - loss: 2.3829 - accuracy: 0.0995\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.3648 - accuracy: 0.0833\n", + "45/45 [==============================] - 1s 14ms/step - loss: 2.5299 - accuracy: 0.0946\n", + "12/12 [==============================] - 0s 15ms/step - loss: 2.5249 - accuracy: 0.1278\n", + "45/45 [==============================] - 1s 14ms/step - loss: 2.5953 - accuracy: 0.1427\n", + "12/12 [==============================] - 0s 12ms/step - loss: 2.6284 - accuracy: 0.1250\n", + "45/45 [==============================] - 1s 17ms/step - loss: 3.8118 - accuracy: 0.0995\n", + "12/12 [==============================] - 0s 16ms/step - loss: 3.8276 - accuracy: 0.0889\n", + "45/45 [==============================] - 1s 15ms/step - loss: 17.2903 - accuracy: 0.0905\n", + "12/12 [==============================] - 0s 15ms/step - loss: 17.2502 - accuracy: 0.1056\n", + "45/45 [==============================] - 1s 15ms/step - loss: 137.7373 - accuracy: 0.0932\n", + "12/12 [==============================] - 0s 14ms/step - loss: 137.7438 - accuracy: 0.1167\n", + "45/45 [==============================] - 1s 16ms/step - loss: 791.1535 - accuracy: 0.0960\n", + "12/12 [==============================] - 0s 15ms/step - loss: 791.1546 - accuracy: 0.1028\n", + "45/45 [==============================] - 1s 14ms/step - loss: 2.3828 - accuracy: 0.1016\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.4095 - accuracy: 0.0917\n", + "45/45 [==============================] - 1s 13ms/step - loss: 2.5109 - accuracy: 0.0939\n", + "12/12 [==============================] - 0s 13ms/step - loss: 2.4702 - accuracy: 0.1167\n", + "45/45 [==============================] - 1s 13ms/step - loss: 2.5195 - accuracy: 0.0647\n", + "12/12 [==============================] - 0s 15ms/step - loss: 2.4999 - accuracy: 0.0917\n", + "45/45 [==============================] - 1s 14ms/step - loss: 3.8371 - accuracy: 0.1044\n", + "12/12 [==============================] - 0s 13ms/step - loss: 3.8617 - accuracy: 0.0889\n", + "45/45 [==============================] - 1s 15ms/step - loss: 15.9897 - accuracy: 0.0953\n", + "12/12 [==============================] - 0s 17ms/step - loss: 15.9813 - accuracy: 0.1139\n", + "45/45 [==============================] - 1s 17ms/step - loss: 81.3778 - accuracy: 0.1037\n", + "12/12 [==============================] - 0s 16ms/step - loss: 81.3855 - accuracy: 0.0889\n", + "45/45 [==============================] - 1s 15ms/step - loss: 6.0581 - accuracy: 0.0967\n", + "12/12 [==============================] - 0s 14ms/step - loss: 6.0620 - accuracy: 0.1139\n", + "45/45 [==============================] - 1s 16ms/step - loss: 2.1808 - accuracy: 0.4509\n", + "12/12 [==============================] - 0s 16ms/step - loss: 2.2036 - accuracy: 0.3917\n", + "45/45 [==============================] - 1s 14ms/step - loss: 2.1643 - accuracy: 0.3800\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.1645 - accuracy: 0.3694\n", + "45/45 [==============================] - 1s 15ms/step - loss: 2.3447 - accuracy: 0.3834\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.3489 - accuracy: 0.3333\n", + "45/45 [==============================] - 1s 13ms/step - loss: 3.5658 - accuracy: 0.2902\n", + "12/12 [==============================] - 0s 13ms/step - loss: 3.5798 - accuracy: 0.2611\n", + "45/45 [==============================] - 1s 13ms/step - loss: 10.1893 - accuracy: 0.4621\n", + "12/12 [==============================] - 0s 12ms/step - loss: 10.2003 - accuracy: 0.4333\n", + "45/45 [==============================] - 1s 14ms/step - loss: 2.6642 - accuracy: 0.1044\n", + "12/12 [==============================] - 0s 13ms/step - loss: 2.6594 - accuracy: 0.0889\n", + "45/45 [==============================] - 1s 15ms/step - loss: 2.3056 - accuracy: 0.0939\n", + "12/12 [==============================] - 0s 15ms/step - loss: 2.3030 - accuracy: 0.1167\n", + "45/45 [==============================] - 1s 15ms/step - loss: 1.0158 - accuracy: 0.8970\n", + "12/12 [==============================] - 0s 15ms/step - loss: 1.0555 - accuracy: 0.8694\n", + "45/45 [==============================] - 1s 16ms/step - loss: 1.0723 - accuracy: 0.8824\n", + "12/12 [==============================] - 0s 16ms/step - loss: 1.1238 - accuracy: 0.8583\n", + "45/45 [==============================] - 1s 16ms/step - loss: 1.1955 - accuracy: 0.8866\n", + "12/12 [==============================] - 0s 18ms/step - loss: 1.2342 - accuracy: 0.8806\n", + "45/45 [==============================] - 1s 17ms/step - loss: 2.0627 - accuracy: 0.9088\n", + "12/12 [==============================] - 0s 12ms/step - loss: 2.1114 - accuracy: 0.8833\n", + "45/45 [==============================] - 1s 13ms/step - loss: 2.2699 - accuracy: 0.5560\n", + "12/12 [==============================] - 0s 14ms/step - loss: 2.2776 - accuracy: 0.5139\n", + "45/45 [==============================] - 1s 11ms/step - loss: 2.3020 - accuracy: 0.1044\n", + "12/12 [==============================] - 0s 11ms/step - loss: 2.3079 - accuracy: 0.0778\n", + "45/45 [==============================] - 1s 12ms/step - loss: 2.3020 - accuracy: 0.1044\n", + "12/12 [==============================] - 0s 13ms/step - loss: 2.3081 - accuracy: 0.0778\n", + "45/45 [==============================] - 1s 14ms/step - loss: 0.0471 - accuracy: 0.9986\n", + "12/12 [==============================] - 0s 14ms/step - loss: 0.1069 - accuracy: 0.9722\n", + "45/45 [==============================] - 1s 15ms/step - loss: 0.0652 - accuracy: 0.9986\n", + "12/12 [==============================] - 0s 14ms/step - loss: 0.1282 - accuracy: 0.9667\n", + "45/45 [==============================] - 1s 25ms/step - loss: 0.2069 - accuracy: 0.9979\n", + "12/12 [==============================] - 0s 14ms/step - loss: 0.2611 - accuracy: 0.9694\n", + "45/45 [==============================] - 1s 14ms/step - loss: 0.4478 - accuracy: 0.9812\n", + "12/12 [==============================] - 0s 14ms/step - loss: 0.4928 - accuracy: 0.9639\n", + "45/45 [==============================] - 1s 16ms/step - loss: 1.5912 - accuracy: 0.6430\n", + "12/12 [==============================] - 0s 15ms/step - loss: 1.6045 - accuracy: 0.6222\n", + "45/45 [==============================] - 1s 15ms/step - loss: 2.3066 - accuracy: 0.0995\n", + "12/12 [==============================] - 0s 16ms/step - loss: 2.3218 - accuracy: 0.0861\n", + "45/45 [==============================] - 1s 14ms/step - loss: 1597.5291 - accuracy: 0.0640\n", + "12/12 [==============================] - 0s 15ms/step - loss: 1597.5353 - accuracy: 0.0444\n", + "45/45 [==============================] - 1s 14ms/step - loss: 0.0054 - accuracy: 1.0000\n", + "12/12 [==============================] - 0s 15ms/step - loss: 0.0781 - accuracy: 0.9806\n", + "45/45 [==============================] - 1s 16ms/step - loss: 0.0267 - accuracy: 1.0000\n", + "12/12 [==============================] - 0s 17ms/step - loss: 0.0868 - accuracy: 0.9861\n", + "45/45 [==============================] - 1s 16ms/step - loss: 0.4085 - accuracy: 0.9631\n", + "12/12 [==============================] - 0s 15ms/step - loss: 0.4859 - accuracy: 0.9222\n", + "45/45 [==============================] - 1s 15ms/step - loss: 2.8874 - accuracy: 0.1628\n", + "12/12 [==============================] - 0s 15ms/step - loss: 2.9575 - accuracy: 0.1583\n", + "45/45 [==============================] - 1s 15ms/step - loss: 2.5044 - accuracy: 0.1037\n", + "12/12 [==============================] - 0s 15ms/step - loss: 2.5299 - accuracy: 0.0889\n", + "45/45 [==============================] - 1s 16ms/step - loss: 372.5927 - accuracy: 0.0967\n", + "12/12 [==============================] - 0s 15ms/step - loss: 371.5039 - accuracy: 0.1139\n", + "45/45 [==============================] - 1s 16ms/step - loss: nan - accuracy: 0.1044\n", + "12/12 [==============================] - 0s 15ms/step - loss: nan - accuracy: 0.0778\n", + "45/45 [==============================] - 1s 13ms/step - loss: 4.4143 - accuracy: 0.0995\n", + "12/12 [==============================] - 0s 13ms/step - loss: 4.4885 - accuracy: 0.1056\n", + "45/45 [==============================] - 1s 13ms/step - loss: 2.4027 - accuracy: 0.0953\n", + "12/12 [==============================] - 0s 13ms/step - loss: 2.4071 - accuracy: 0.1250\n", + "45/45 [==============================] - 1s 14ms/step - loss: 2.4921 - accuracy: 0.0939\n", + "12/12 [==============================] - 0s 17ms/step - loss: 2.4936 - accuracy: 0.1167\n", + "45/45 [==============================] - 1s 14ms/step - loss: 2.4047 - accuracy: 0.0995\n", + "12/12 [==============================] - 0s 12ms/step - loss: 2.4569 - accuracy: 0.0861\n", + "45/45 [==============================] - 1s 15ms/step - loss: 962.0815 - accuracy: 0.0939\n", + "12/12 [==============================] - 0s 16ms/step - loss: 959.3554 - accuracy: 0.1167\n", + "45/45 [==============================] - 1s 16ms/step - loss: nan - accuracy: 0.1044\n", + "12/12 [==============================] - 0s 15ms/step - loss: nan - accuracy: 0.0778\n", + "45/45 [==============================] - 1s 15ms/step - loss: nan - accuracy: 0.1044\n", + "12/12 [==============================] - 0s 16ms/step - loss: nan - accuracy: 0.0778\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAyAAAANbCAYAAAC6lftqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8fJSN1AAAACXBIWXMAAA9hAAAPYQGoP6dpAACs+0lEQVR4nOzdd3xTVR/H8W+6KS0bWqDsadl7b1AU2aggSxHcIijT9QCiqIAoAooIiIOhLFmCDAUBmbKX7NVCWaV0t0meP9IWQ1sIGG5K+3k/L14+ubknOfdHOMnvnt8912S1Wq0CAAAAAAO4uboDAAAAALIOEhAAAAAAhiEBAQAAAGAYEhAAAAAAhiEBAQAAAGAYEhAAAAAAhiEBAQAAAGAYEhAAAAAAhiEBAQAAAGAYEhAAD6Rhw4apXLlyt/3TvHnz//QeCxcuVLly5XTu3Ln72ua/Onv2rMqXL6/atWsrNjbWsPcFAOBemKxWq9XVnQCAu3XmzBldvXo15fGUKVN08OBBTZo0KWWbl5eXgoOD7/k9rl69qjNnzig4OFheXl73rc1/NWHCBK1atUrnzp3T+++/r44dOxryvgAA3AsSEACZwrBhw7Rt2zatW7fO1V0xlMViUfPmzdWhQwcdPHhQ169f17x581zdLQAA0kUJFoBMbevWrSpXrpzmzp2rZs2aqX79+tq4caMk6eeff1anTp1UtWpVVa5cWe3bt9eKFStS2t5aTjVs2DA988wzWrBggR555BFVrFhR7dq10/r16/9TG0natWuXunfvrqpVq6pp06aaNWuWnnnmGQ0bNuy2x7dx40aFhoaqWbNmateunXbv3q3Dhw+n2u/KlSt66623VL9+fVWrVk3du3fXzp07U55PSEjQ5MmT1bJlS1WuXFlt2rTRggULUp7v2bOnevbsmWZst27dmnLswcHB+vnnn9WwYUM1btxYR48eldls1tdff63HH39clStXVtWqVdW1a1f99ddfdq+3f/9+9e3bVzVq1FDdunU1cOBAhYaGKjExUQ0bNtSbb76Z6rgeffRRDR8+/LYxAgBkLCQgALKECRMmaOjQoRo6dKiqVq2qH3/8Ue+9955atGihqVOnauzYsfL09NTgwYMVEhKS7uvs379f06dPV//+/TV58mR5eHiof//+un79+j23OX78uJ555hlJ0qeffqrXXntNX3/9tV2CkJ4FCxaoRIkSqlKlilq1aqUcOXJozpw5dvtER0era9eu2rx5s958801NmjRJ2bNnV9++fXX8+HFJ0tChQ/X111+rS5cumjp1qpo0aaK33npLixcvvmMf/s1sNuurr77S6NGjNWDAAJUuXVrjxo3T5MmT9dRTT+mbb77RqFGjdO3aNb3++uuKjo6WJB0+fFjdunVTTEyMPvroI40aNUoHDx5Unz59ZLVa1aFDB61Zs0aRkZEp77Vnzx6dOHFCnTp1uqs+AgBcy8PVHQAAI3Tt2lWtW7dOeXz27Fn16dNHr7zySsq2oKAgderUSX///bcKFSqU5uvcuHFDCxcuVNGiRSVJvr6+6tGjh7Zs2aJHHnnkntpMnTpVfn5++uabb5QtWzZJUsmSJdW1a9fbHlN4eLjWrVun1157TZLk7e2tNm3aaMmSJRoyZIiyZ88uSVq0aJHOnj2rxYsXq3z58pKkmjVrqkOHDtq+fbssFouWL1+ut99+W7169ZIk1atXTyEhIdq6das6dOhw237c6sUXX1TTpk1THoeFhWngwIF2Myg+Pj567bXXdOTIEVWrVk1TpkxRzpw5NWPGDHl7e0uSAgMDNWDAAB05ckSdO3fWtGnTtGrVKnXu3DnluIoWLaqaNWveVf8AAK5FAgIgSyhXrpzd4+TSphs3bujUqVM6depUSklQQkJCuq+TJ0+elERCsv1IlqSYmJh7brNlyxY1adIkJfmQpGrVqqlw4cK3PaYlS5YoMTFRzZs3V0REhCTpkUce0Zw5c7R06dKUBGbHjh0KCgpKST4kW7Ly66+/SlLKjEmrVq3sXv+zzz677funp2zZsnaPx48fL8l2gf7p06d18uTJlGt1kmO9c+dONWnSJCX5kKTKlSvbXdNTo0YN/fLLL+rcubPi4+O1YsUK9e7dWyaT6Z76CQBwDRIQAFlC3rx57R6fOXNG7733nrZs2SIPDw+VLFkyJUm53doc/04SJKX8+LVYLPfc5urVq6n6J0n58+dP9zUl2zUXFotFbdq0SfXc3LlzUxKQ8PDwNF8/WXh4uKTUMbpXt77Ovn37NHLkSO3bt08+Pj4qXbp0SnKVHOs79VGSunTporfeekshISHas2ePIiIiWPELAB5AJCAAshyLxaLnn39enp6e+umnnxQcHCwPDw8dO3ZMS5YsMbw/gYGBunLlSqrtV65cUYkSJdJsc/DgQR06dEivvvqqateubffcunXr9O2332rPnj2qUqWK/P3907wvya5du+Tn56ccOXJIsiVCybMzknTixAldvXo1pcTJbDbbtU++fuN2IiMj1bdvX5UrV07Lli1TqVKl5ObmpvXr12vVqlUp+/n7+9stq5xs/fr1Kl++vAICAtS6dWuNHj1aq1at0q5du1SvXr10S+UAABkXF6EDyHKuXbumkydPqkuXLqpcubI8PGznYjZs2CDp9rMZ90OtWrW0YcMGxcXFpWw7dOjQbW9mOH/+fHl5eemZZ55RnTp17P4899xzcnd319y5cyXZrvc4e/asjhw5ktI+Pj5er732mn766SfVqFFDkrRmzRq795gwYYLef/99SZKfn58uXLhg9/zff/99x2M7ceKEwsPD1atXL5UpU0ZubravnVtjXbNmTf3555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iOBAQAsqmSJUtKkn755ReTIwEAwHEkIACQTS1YsECSdOjQIZMjAQDAcSQgAJANbdmyRZ999pny5MmjgwcPmh0OAAAOIwEBgGzmxo0bGjZsmJo1a6b27dvrypUrunDhgtlhAQDgEBIQAMhmxowZo+TkZI0bN05hYWGSKMMCAGQfJCAAkI2sXbtWq1ev1nvvvafHHnssPQHhQnQAQHZBAgIA2cTFixc1atQotWvXTk2aNJEkFS1aVLlz5+Y6EABAtkECAgDZxMiRI5UnTx4NGTLErr1ChQqUYAEAsg0SEADIBj7//HNt2rRJEydOVEBAgN3PwsLCdPr0acXGxpoUHQAAjrNYrVar2UEAAAAAyBlYAQEAAABgGBIQAAAAAIYhAQEAAABgGBIQAAAAAIYhAQEAAABgGBIQAAAAAIYhAQEAAABgGBIQAAAAAIYhAQEAAABgGBIQAAAAAIYhAQEAAABgGBIQAAAAAIb5f8LSe3ogZVkKAAAAAElFTkSuQmCC", + "text/plain": [ + "
    " + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAyAAAANbCAYAAAC6lftqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8fJSN1AAAACXBIWXMAAA9hAAAPYQGoP6dpAADPoUlEQVR4nOzdd3gU1dvG8e+mAwkdEhIIvUU6offeBJEiICBKEUSaIKDA7xUpdsSCKCoIiEgvIr0qvffeSSAkoQXSk919/9gQXJJA0GQTkvtzXVy6M3N2Zp6cnMwz58wZg9lsNiMiIiIiImIDdml9ACIiIiIiknkoAREREREREZtRAiIiIiIiIjajBERERERERGxGCYiIiIiIiNiMEhAREREREbEZJSAiIiIiImIzSkBERERERMRmlICIiKQivetVRETEmkNaH4CIiC299957LF++/InbeHl5sWXLlv+8r8WLF3Px4kXee++9p267ZMkSxo4dS7169fj555//875FRETSK4NZt+dEJBO5du0ad+7cif88ffp0Tp06xb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REbEYJiIiIiIiI2IyGYImIiIiIJMPz+NK/9Eg9ICIiIiIiYjNKQERERERExGY0BEtEREREJBmMZt27TwmKooiIiIiI2IwSEBERERERsRkNwRIRERERSQaT7t2nCEVRRERERERsRgmIiIiIiIjYjIZgiYiIiIgkg15EmDLUAyIiIiIiIjajBERERERERGxGQ7BERERERJJBLyJMGYqiiIiIiIjYjBIQERERERGxGQ3BEhERERFJBpNmwUoR6gERERERERGbUQIiIiIiIiI2oyFYIiIiIiLJYNS9+xShKIqIiIiIiM0oAREREREREZvRECwRERERkWTQiwhThqIoIiIiIiI2owRERERERERsRkOwRERERESSwaR79ylCURQREREREZtRAiIiIiIiIjajIVgiIiIiIslgNBvS+hAyBPWAiIiIiIiIzSgBERERERERm9EQLBERERGRZDDq3n2KUBRFRERERMRmlICIiIiIiIjNKAERERERERGb0TMgIiIiIiLJYDLr3n1KUBRFRERERMRmlICIiIiIiIjNaAiWiIiIiEgyaBrelKEoioiIiIiIzSgBERERERERm9EQLBERERGRZDCaDWl9CBmCekBERERERMRmlICIiIiIiIjNaAiWiIiIiEgymHTvPkVkrgTEXpUmVcUa0/oIMjxzRERaH4LIf2Nvn9ZHkOGpnUhdBheXtD4EkeeershFRERERMRmMlcPiIiIiIjIv2Q06959SlAURURERETEZpSAiIiIiIiIzWgIloiIiIhIMpjQiwhTgnpARERERETEZpSAiIiIiIiIzWgIloiIiIhIMmgWrJShKIqIiIiIiM0oAREREREREZvRECwRERERkWQw6t59ilAURURERETEZpSAiIiIiIiIzWgIloiIiIhIMpjMehFhSlAPiIiIiIiI2IwSEBERERERsRkNwRIRERERSQbNgpUyFEUREREREbEZJSAiIiIiImIzGoIlIiIiIpIMJrPu3acERVFERERERGxGCYiIiIiIiNiMhmCJiIiIiCSDEb2IMCWoB0RERERERGxGCYiIiIiIiNiMhmCJiIiIiCSDZsFKGYqiiIiIiIjYjBIQERERERGxGQ3BEhERERFJBs2ClTLUAyIiIiIiIjajBERERERERGxGQ7BERERERJJBs2ClD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AyC1slICKpJa0v3jIDWyUgmZXqcOpTAvLsnrcEJM2HYD3k7u6Ou3vClxeJiIiIiEjGkW4SEBERERGR9MxkTvP5mzIERVFERERERGxGCYiIiIiIiNiMhmCJiIiIiCSDEb2IMCWoB0RERERERGxGCYiIiIiIiNiMhmCJiIiIiCSDyawhWClBPSAiIiIiImIzSkBERERERMRmNARLRERERCQZ9CLClKEoioiIiIiIzSgBERERERERm9EQLBERERGRZDDpRYQpQj0gIiIiIiJiM0pARERERETEZjQES0REREQkGYx6EWGKUA+IiIiIiIjYjBIQERERERGxGQ3BEhERERFJBr2IMGUoiiIiIiIiYjNKQERERERExGY0BEtEREREJBlMmgUrRagHREREREREbEYJiIiIiIiI2IyGYImIiIiIJIMJDcFKCeoBERERERERm1ECIiIiIiIiNqMhWCIiIiIiyaBZsFKGekBERERERMRmlICIiIiIiIjNaAiWiIiIiEgymMy6d58SFEUREREREbEZJSAiIiIiImIzGoIlIiIiIpIMmgUrZagHREREREREbEYJiIiIiIiI2IyGYImIiIiIJIMJDcFKCeoBERERERERm1ECIiIiIiIiNqMhWCIiIiIiyaBZsFKGekBERERERMRmlICIiIiIiIjNaAiWiIiIiEgyaAhWylAPiIiIiIiI2IwSEBERERERsRkNwRIRERERSQYNwUoZ6gERERERERGbUQIiIiIiIiI2k6mGYN14rWxaH0KGZhed1keQ8TmGm9P6EDK0rMHGtD6EDC+4Yqb6s5MmvH84ndaHkLEZNAQnM9MQrJShHhAREREREbEZJSAiIiIiImIz6gsXEREREUkGExqClRLUAyIiIiIiIjajBERERERERGxGQ7BERERERJJBs2ClDPWAiIiIiIiIzSgBERERERERm9EQLBERERGRZNAQrJShHhAREREREbEZJSAiIiIiImIzGoIlIiIiIpIMGoKVMtQDIiIiIiIiNqMEREREREREbEZDsEREREREkkFDsFKGekBERERERMRmlICIiIiIiIjNaAiWiIiIiEgymDUEK0WoB0RERERERGxGCYiIiIiIiNiMhmCJiIiIiCSDCQ3BSgnqAREREREREZtRAiIiIiIiIjaj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CIiIiIiYjNKQERERERExGY0BEtEREREJDk0C1aKUA+IiIiIiIjYjBIQERERERGxGQ3BEhERERFJDg3BShHqAREREREREZtRAiIiIiIiIjajIVgiIiIiIslh1osIU4J6QERERERExGaUgIiIiIiIiM1oCJaIiIiISDKYNQtWilAPiIiIiIiI2IwSEBERERERsRkNwRIRERERSQ4NwUoR6gERERERERGbUQIiIiIiIiI2oyFYIiIiIiLJoRcRpgj1gIiIiIiIiM0oAREREREREZvRECwRERERkWQwaBasFKEeEBERERERsRklICIiIiIiYjMagiUiIiIikhwagpUi1AMiIiIiIiI2owRERERERERsRkOwRERERESSQy8iTBHqAREREREREZtRAiIiIiIiIjajIVgiIiIiIsmhWbBShHpARERERETEZpSAiIiIiIiIzWgIloiIiIhIcmgIVopQD4iIiIiIiNiMEhAREREREbEZDcESEREREUkODcFKEeoBERERERERm1ECIiIiIiIiNqMhWCIiIiIiyWE2pPURZAjqAREREREREZtRAiIiIiIiIjajIVgiIiIiIslg0CxYKUI9ICIiIiIiYjNKQERERERExGY0BEtEREREJDk0BCtFqAdERERERERsRj0gNnL2gJGNc2MI8jORLbuBGq0daPCKAwZD4vNJG41mti+N5cCGWO7fNpPXy0DDzo5UaGD5kd0NNPHZG5FJ7q9qU3s6DXdOlXNJjy4ciGHLr5EE+xnJlt1A1dbO1O3snGR8TUYzu5ZGcXhjNA9um8jtaUfdV1woV9/JartbfkY2zorgyvFY7B0MFC7nQPM+LuQqYG+L00pXTh8wsWaOicBrZlxzQO3WdjTpYvfEOrx1iYm9603cvw15vaBpF3sqN7C+73F8l4kN840E+UP2XFC1iR1Nu9jh4Ji55lo/dcDM6jkmbl4D1xxQp7WBZl0MT4zvliVm9qw3E3Ib8nlBsy4GqjwW32O7zKybb4qPb7Umlu/NbPEFqF+4CCNq1aZE7jzciYhg/vGjfH9gf5LbF8uVi02vvZFg+cU7d2j26+wEy12dnFjTvSdf79nN0tOnUvLQ06WqTcrR638d8C5dgJBbD1jzyzYWfrnmiWUav1KTLs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IiIiIiIiI2oyFYIiIiIiLJoVmwUoR6QERERERExGaUgIiIiIiIiM1oCJaIiIiISDLoRYQpQz0gIiIiIiJiM0pARERERETEZjQES0REREQkOTQEK0WoB0RERERERGxGCYiIiIiIiNiMhmCJiIiIiCSDZsFKGeoBERERERERm1ECIiIiIiIiNqMhWCIiIiIiyaEhWClCPSAiIiIiImIzSkBERERERMRmNARLRERERCQ5NAQrRagHREREREREbEYJiIiIiIiI2IyGYImIiIiIJINeRJgy1AMiIiIiIiI2owRERERERERsRgmIiIiIiIjYjBIQERERERGxGSUgIiIiIiJiM5oFS0REREQkOTQLVopQD4iIiIiIiNiMEhAREREREbEZDcESEREREUkGvYgwZagHREREREREbEYJiIiIiIiI2IyGYImIiIiIJIeGYKWITJWAtMp6L60PIUOLMRvT+hAyPHuDIa0PIUOLMZvS+hAyPIeCYWl9CBmfvX1aH0GGZrx3L60PQeS5pyFYIiIiIiJiM5mqB0RERERE5F/TEKwUoR4QERERERGxGSUgIiIiIiJiMxqCJSIiIiKSDHoRYcpQD4iIiIiIiNiMEhAREREREbEZDcESEREREUkODcFKEeoBERERERERm1ECIiIiIiIiNqMhWCIiIiIiyaBZsFKGekBERERERMRmlICIiIiIiIjNaAiWiIiIiEhyaAhWilAPiIiIiIiI2IwSEBERERERsRkNwRIRERERSQ4NwUoR6gERERERERGbUQIiIiIiIiI2oyFYIiIiIiLJoBcRpgz1gIiIiIiIiM0oAREREREREZvRECwRERERkeTQEKwUoR4QERERERGxGSUgIiIiIiJiMxqCJSIiIiKSHBqClSLUAyIiIiIiIjajBERERERERGxGQ7BERERERJJBLyJMGeoBERERERERm1ECIiIiIiIiNqMhWCIiIiIiyaEhWClCPSAiIiIiImIzSkBERERERDIpk8nEN998Q7169ahYsSK9e/fm6tWrySq7atUqSpcujb+//zPtUwmIiIiIiEgyGMzp899/MX36dBYsWMCkSZNYuHAhBoOBfv36ER0d/cRy169f58MPP/xX+1QCIiIiIiKSCUVHRzNr1iwGDx5MgwYNKFOm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zJghSTp58qSTRwIAQMqRgABAGrRz504tXLhQ2bNn14kTJ5w9HAAAUowEBADSmNDQUA0ZMkQNGzbUW2+9pdu3b+vGjRvOHhYAAClCAgIAacyIESMUExOjUaNGyc/PTxJlWACAtIMEBADSkA0bNmjNmjUaPXq0cubMmZiAcCI6ACCtIAEBgDTi5s2bGjZsmN588009//zzkqRChQopW7ZsnAcCAEgzSEAAII0YOnSosmfPrsGDB9u0ly1blhIsAECaQQICAGnA0qVLtWPHDo0ZM0aZMmWyeczPz0+XL19WWFiYk0YHAEDKmSwWi8XZgwAAAACQPrACAgAAAMAwJCAAAAAADEMCAgAAAMAwJCAAAAAADEMCAgAAAMAwJCAAAAAADEMCAgAAAMAwJCAAAAAADEMCAgAAAMAwJCAAAAAADEMCAgAAAMAwJCAAAAAADPP/IFx0KvjTz7wAAAAASUVORK5CYII=", + "text/plain": [ + "
    " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " DNN = DNN_keras[i][j]\n", + "\n", + " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a61b50a8", + "metadata": { + "editable": true + }, + "source": [ + "## Using Pytorch with the full MNIST data set" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "d220a7ad", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "import torchvision\n", + "import torchvision.transforms as transforms\n", + "\n", + "# Device configuration: use GPU if available\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# MNIST dataset (downloads if not already present)\n", + "transform = transforms.Compose([\n", + " transforms.ToTensor(),\n", + " transforms.Normalize((0.5,), (0.5,)) # normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range)\n", + "])\n", + "train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)\n", + "test_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)\n", + "\n", + "train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)\n", + "\n", + "\n", + "class NeuralNet(nn.Module):\n", + " def __init__(self):\n", + " super(NeuralNet, self).__init__()\n", + " self.fc1 = nn.Linear(28*28, 100) # first hidden layer (784 -> 100)\n", + " self.fc2 = nn.Linear(100, 100) # second hidden layer (100 -> 100)\n", + " self.fc3 = nn.Linear(100, 10) # output layer (100 -> 10 classes)\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1) # flatten images into vectors of size 784\n", + " x = torch.relu(self.fc1(x)) # hidden layer 1 + ReLU activation\n", + " x = torch.relu(self.fc2(x)) # hidden layer 2 + ReLU activation\n", + " x = self.fc3(x) # output layer (logits for 10 classes)\n", + " return x\n", + "\n", + "model = NeuralNet().to(device)\n", + "\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)\n", + "\n", + "num_epochs = 10\n", + "for epoch in range(num_epochs):\n", + " model.train() # set model to training mode\n", + " running_loss = 0.0\n", + " for images, labels in train_loader:\n", + " # Move data to device (GPU if available, else CPU)\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad() # reset gradients to zero\n", + " outputs = model(images) # forward pass: compute predictions\n", + " loss = criterion(outputs, labels) # compute cross-entropy loss\n", + " loss.backward() # backpropagate to compute gradients\n", + " optimizer.step() # update weights using SGD step \n", + "\n", + " running_loss += loss.item()\n", + " # Compute average loss over all batches in this epoch\n", + " avg_loss = running_loss / len(train_loader)\n", + " print(f\"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}\")\n", + "\n", + "#Evaluation on the Test Set\n", "\n", "\n", "\n", + "model.eval() # set model to evaluation mode \n", + "correct = 0\n", + "total = 0\n", + "with torch.no_grad(): # disable gradient calculation for evaluation \n", + " for images, labels in test_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + " _, predicted = torch.max(outputs, dim=1) # class with highest score\n", + " total += labels.size(0)\n", + " correct += (predicted == labels).sum().item()\n", "\n", -<<<<<<< HEAD - "* Thursday: Wrapping up Recurrent Neural Networks and solving differential equations. \n", + "accuracy = 100 * correct / total\n", + "print(f\"Test Accuracy: {accuracy:.2f}%\")" + ] + }, + { + "cell_type": "markdown", + "id": "d87d7514", + "metadata": { + "editable": true + }, + "source": [ + "## And a similar example using Tensorflow with Keras" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "c6df6115", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "GPUs available: [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING:absl:At this time, the v2.11+ optimizer `tf.keras.optimizers.SGD` runs slowly on M1/M2 Macs, please use the legacy Keras optimizer instead, located at `tf.keras.optimizers.legacy.SGD`.\n", + "WARNING:absl:There is a known slowdown when using v2.11+ Keras optimizers on M1/M2 Macs. Falling back to the legacy Keras optimizer, i.e., `tf.keras.optimizers.legacy.SGD`.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Model: \"sequential_49\"\n", + "_________________________________________________________________\n", + " Layer (type) Output Shape Param # \n", + "=================================================================\n", + " flatten (Flatten) (None, 784) 0 \n", + " \n", + " dense_147 (Dense) (None, 100) 78500 \n", + " \n", + " dense_148 (Dense) (None, 100) 10100 \n", + " \n", + " dense_149 (Dense) (None, 10) 1010 \n", + " \n", + "=================================================================\n", + "Total params: 89,610\n", + "Trainable params: 89,610\n", + "Non-trainable params: 0\n", + "_________________________________________________________________\n" + ] + }, + { + "data": { + "text/plain": [ + "'\\n# 4) Train\\nhistory = model.fit(\\n x_train, y_train,\\n epochs=10,\\n batch_size=64,\\n validation_split=0.1, # optional: monitor validation during training\\n verbose=1\\n)\\n\\n# 5) Evaluate on test set\\ntest_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)\\nprint(f\"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}\")\\n'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ "\n", - "* Friday: Principal Component Analysis and Dimensionality Reduction\n", -======= - "* Thursday: Wrapping up Recurrent Neural Networks and solving differential equations. [Video of Lecture October 22](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureOctober22.mp4?vrtx=view-as-webpage)\n", + "import tensorflow as tf\n", + "from tensorflow import keras\n", + "from tensorflow.keras import layers, regularizers\n", "\n", - "* Friday: Principal Component Analysis and Dimensionality Reduction. [Video of Lecture October 23](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureOctober23.mp4?vrtx=view-as-webpage)\n", ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 + "# Check for GPU (TensorFlow will use it automatically if available)\n", + "gpus = tf.config.list_physical_devices('GPU')\n", + "print(f\"GPUs available: {gpus}\")\n", "\n", - "We will also study the usage of [Autograd](https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola) in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from [week 40](https://compphysics.github.io/MachineLearning/doc/pub/week40/html/week40.html) and the [Autograd doucmentation](https://github.com/HIPS/autograd).\n", + "# 1) Load and preprocess MNIST\n", + "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n", + "# Normalize to [0, 1]\n", + "x_train = (x_train.astype(\"float32\") / 255.0)\n", + "x_test = (x_test.astype(\"float32\") / 255.0)\n", "\n", - "## Recurrent Neural Networks\n", + "# 2) Build the model: 784 -> 100 -> 100 -> 10\n", + "l2_reg = 1e-4 # L2 regularization strength\n", "\n", - "[Overview video](https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini).\n", - "See also lecture on Thursday October 22 and examples from [week 42](https://compphysics.github.io/MachineLearning/doc/pub/week42/html/week42.html).\n", + "model = keras.Sequential([\n", + " layers.Input(shape=(28, 28)),\n", + " layers.Flatten(),\n", + " layers.Dense(100, activation=\"relu\",\n", + " kernel_regularizer=regularizers.l2(l2_reg)),\n", + " layers.Dense(100, activation=\"relu\",\n", + " kernel_regularizer=regularizers.l2(l2_reg)),\n", + " layers.Dense(10, activation=\"softmax\") # output probabilities for 10 classes\n", + "])\n", "\n", - "[IN5400 at UiO Lecture](https://www.uio.no/studier/emner/matnat/ifi/IN5400/v20/material/week10/in5400_2020_week10_recurrent_neural_network.pdf)\n", + "# 3) Compile with SGD + weight decay via L2 regularizers\n", + "model.compile(\n", + " optimizer=keras.optimizers.SGD(learning_rate=0.01),\n", + " loss=\"sparse_categorical_crossentropy\",\n", + " metrics=[\"accuracy\"],\n", + ")\n", "\n", - "[CS231 at Stanford Lecture](https://www.youtube.com/watch?v=6niqTuYFZLQ&list=PLzUTmXVwsnXod6WNdg57Yc3zFx_f-RYsq&index=10&ab_channel=StanfordUniversitySchoolofEngineering)\n", + "model.summary()\n", + "\"\"\"\n", + "# 4) Train\n", + "history = model.fit(\n", + " x_train, y_train,\n", + " epochs=10,\n", + " batch_size=64,\n", + " validation_split=0.1, # optional: monitor validation during training\n", + " verbose=1\n", + ")\n", "\n", - "## Solving ODEs with Deep Learning\n", + "# 5) Evaluate on test set\n", + "test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)\n", + "print(f\"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}\")\n", + "\"\"\"" + ] + }, + { + "cell_type": "markdown", + "id": "5fd4d319", + "metadata": { + "editable": true + }, + "source": [ + "## Building our own neural network code\n", + "\n", + "Here we present a flexible object oriented codebase\n", + "for a feed forward neural network, along with a demonstration of how\n", + "to use it. Before we get into the details of the neural network, we\n", + "will first present some implementations of various schedulers, cost\n", + "functions and activation functions that can be used together with the\n", + "neural network.\n", + "\n", + "The codes here were developed by Eric Reber and Gregor Kajda during spring 2023." + ] + }, + { + "cell_type": "markdown", + "id": "64134feb", + "metadata": { + "editable": true + }, + "source": [ + "### Learning rate methods\n", + "\n", + "The code below shows object oriented implementations of the Constant,\n", + "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", + "of the classes belong to the shared abstract Scheduler class, and\n", + "share the update_change() and reset() methods allowing for any of the\n", + "schedulers to be seamlessly used during the training stage, as will\n", + "later be shown in the fit() method of the neural\n", + "network. Update_change() only has one parameter, the gradient\n", + "($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted\n", + "from the weights. The reset() function takes no parameters, and resets\n", + "the desired variables. For Constant and Momentum, reset does nothing." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "643f7a82", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "\n", + "class Scheduler:\n", + " \"\"\"\n", + " Abstract class for Schedulers\n", + " \"\"\"\n", + "\n", + " def __init__(self, eta):\n", + " self.eta = eta\n", + "\n", + " # should be overwritten\n", + " def update_change(self, gradient):\n", + " raise NotImplementedError\n", + "\n", + " # overwritten if needed\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Constant(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + "\n", + " def update_change(self, gradient):\n", + " return self.eta * gradient\n", + " \n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Momentum(Scheduler):\n", + " def __init__(self, eta: float, momentum: float):\n", + " super().__init__(eta)\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " self.change = self.momentum * self.change + self.eta * gradient\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Adagrad(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " return self.eta * gradient * G_t_inverse\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class AdagradMomentum(Scheduler):\n", + " def __init__(self, eta, momentum):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class RMS_prop(Scheduler):\n", + " def __init__(self, eta, rho):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.second = 0.0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", + " return self.eta * gradient / (np.sqrt(self.second + delta))\n", + "\n", + " def reset(self):\n", + " self.second = 0.0\n", + "\n", + "\n", + "class Adam(Scheduler):\n", + " def __init__(self, eta, rho, rho2):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.rho2 = rho2\n", + " self.moment = 0\n", + " self.second = 0\n", + " self.n_epochs = 1\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", + " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", + "\n", + " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", + " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", + "\n", + " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", + "\n", + " def reset(self):\n", + " self.n_epochs += 1\n", + " self.moment = 0\n", + " self.second = 0" + ] + }, + { + "cell_type": "markdown", + "id": "dfa32b7e", + "metadata": { + "editable": true + }, + "source": [ + "### Usage of the above learning rate schedulers\n", + "\n", + "To initalize a scheduler, simply create the object and pass in the\n", + "necessary parameters such as the learning rate and the momentum as\n", + "shown below. As the Scheduler class is an abstract class it should not\n", + "called directly, and will raise an error upon usage." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "4b88b24e", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" + ] + }, + { + "cell_type": "markdown", + "id": "2eea0e52", + "metadata": { + "editable": true + }, + "source": [ + "Here is a small example for how a segment of code using schedulers\n", + "could look. Switching out the schedulers is simple." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "090bee3c", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Before scheduler:\n", + "weights=array([[1., 1., 1.],\n", + " [1., 1., 1.],\n", + " [1., 1., 1.]])\n", + "\n", + "After scheduler:\n", + "weights=array([[0.993993 , 0.99403075, 0.99399314],\n", + " [0.99399303, 0.99399301, 0.993993 ],\n", + " [0.993993 , 0.99399301, 0.993993 ]])\n" + ] + } + ], + "source": [ + "weights = np.ones((3,3))\n", + "print(f\"Before scheduler:\\n{weights=}\")\n", + "\n", + "epochs = 10\n", + "for e in range(epochs):\n", + " gradient = np.random.rand(3, 3)\n", + " change = adam_scheduler.update_change(gradient)\n", + " weights = weights - change\n", + " adam_scheduler.reset()\n", + "\n", + "print(f\"\\nAfter scheduler:\\n{weights=}\")" + ] + }, + { + "cell_type": "markdown", + "id": "e0eee286", + "metadata": { + "editable": true + }, + "source": [ + "### Cost functions\n", + "\n", + "Here we discuss cost functions that can be used when creating the\n", + "neural network. Every cost function takes the target vector as its\n", + "parameter, and returns a function valued only at $x$ such that it may\n", + "easily be differentiated." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "191224bb", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "\n", + "def CostOLS(target):\n", + " \n", + " def func(X):\n", + " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostLogReg(target):\n", + "\n", + " def func(X):\n", + " \n", + " return -(1.0 / target.shape[0]) * np.sum(\n", + " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", + " )\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostCrossEntropy(target):\n", + " \n", + " def func(X):\n", + " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", + "\n", + " return func" + ] + }, + { + "cell_type": "markdown", + "id": "7f4a0238", + "metadata": { + "editable": true + }, + "source": [ + "Below we give a short example of how these cost function may be used\n", + "to obtain results if you wish to test them out on your own using\n", + "AutoGrad's automatics differentiation." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "d822b656", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Derivative of cost function CostCrossEntropy valued at a:\n", + "[[-0.08333333]\n", + " [-0.13333333]\n", + " [-0.16666667]]\n" + ] + } + ], + "source": [ + "from autograd import grad\n", + "\n", + "target = np.array([[1, 2, 3]]).T\n", + "a = np.array([[4, 5, 6]]).T\n", + "\n", + "cost_func = CostCrossEntropy\n", + "cost_func_derivative = grad(cost_func(target))\n", + "\n", + "valued_at_a = cost_func_derivative(a)\n", + "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" + ] + }, + { + "cell_type": "markdown", + "id": "7ff32a3b", + "metadata": { + "editable": true + }, + "source": [ + "### Activation functions\n", + "\n", + "Finally, before we look at the neural network, we will look at the\n", + "activation functions which can be specified between the hidden layers\n", + "and as the output function. Each function can be valued for any given\n", + "vector or matrix X, and can be differentiated via derivate()." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "90045474", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import elementwise_grad\n", + "\n", + "def identity(X):\n", + " return X\n", + "\n", + "\n", + "def sigmoid(X):\n", + " try:\n", + " return 1.0 / (1 + np.exp(-X))\n", + " except FloatingPointError:\n", + " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", + "\n", + "\n", + "def softmax(X):\n", + " X = X - np.max(X, axis=-1, keepdims=True)\n", + " delta = 10e-10\n", + " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", + "\n", + "\n", + "def RELU(X):\n", + " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", + "\n", + "\n", + "def LRELU(X):\n", + " delta = 10e-4\n", + " return np.where(X > np.zeros(X.shape), X, delta * X)\n", + "\n", + "\n", + "def derivate(func):\n", + " if func.__name__ == \"RELU\":\n", + "\n", + " def func(X):\n", + " return np.where(X > 0, 1, 0)\n", + "\n", + " return func\n", + "\n", + " elif func.__name__ == \"LRELU\":\n", + "\n", + " def func(X):\n", + " delta = 10e-4\n", + " return np.where(X > 0, 1, delta)\n", + "\n", + " return func\n", + "\n", + " else:\n", + " return elementwise_grad(func)" + ] + }, + { + "cell_type": "markdown", + "id": "eec681dc", + "metadata": { + "editable": true + }, + "source": [ + "Below follows a short demonstration of how to use an activation\n", + "function. The derivative of the activation function will be important\n", + "when calculating the output delta term during backpropagation. Note\n", + "that derivate() can also be used for cost functions for a more\n", + "generalized approach." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "a36d4506", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Input to activation function:\n", + "[[4]\n", + " [5]\n", + " [6]]\n", + "\n", + "Output from sigmoid activation function:\n", + "[[0.98201379]\n", + " [0.99330715]\n", + " [0.99752738]]\n", + "\n", + "Derivative of sigmoid activation function valued at z:\n", + "[[0.19824029]\n", + " [0.19721923]\n", + " [0.19683648]]\n" + ] + } + ], + "source": [ + "z = np.array([[4, 5, 6]]).T\n", + "print(f\"Input to activation function:\\n{z}\")\n", + "\n", + "act_func = sigmoid\n", + "a = act_func(z)\n", + "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", + "\n", + "act_func_derivative = derivate(act_func)\n", + "valued_at_z = act_func_derivative(a)\n", + "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" + ] + }, + { + "cell_type": "markdown", + "id": "d2358581", + "metadata": { + "editable": true + }, + "source": [ + "### The Neural Network\n", + "\n", + "Now that we have gotten a good understanding of the implementation of\n", + "some important components, we can take a look at an object oriented\n", + "implementation of a feed forward neural network. The feed forward\n", + "neural network has been implemented as a class named FFNN, which can\n", + "be initiated as a regressor or classifier dependant on the choice of\n", + "cost function. The FFNN can have any number of input nodes, hidden\n", + "layers with any amount of hidden nodes, and any amount of output nodes\n", + "meaning it can perform multiclass classification as well as binary\n", + "classification and regression problems. Although there is a lot of\n", + "code present, it makes for an easy to use and generalizeable interface\n", + "for creating many types of neural networks as will be demonstrated\n", + "below." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "9dd0b112", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "import math\n", + "import autograd.numpy as np\n", + "import sys\n", + "import warnings\n", + "from autograd import grad, elementwise_grad\n", + "from random import random, seed\n", + "from copy import deepcopy, copy\n", + "from typing import Tuple, Callable\n", + "from sklearn.utils import resample\n", + "\n", + "warnings.simplefilter(\"error\")\n", + "\n", + "\n", + "class FFNN:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Feed Forward Neural Network with interface enabling flexible design of a\n", + " nerual networks architecture and the specification of activation function\n", + " in the hidden layers and output layer respectively. This model can be used\n", + " for both regression and classification problems, depending on the output function.\n", + "\n", + " Attributes:\n", + " ------------\n", + " I dimensions (tuple[int]): A list of positive integers, which specifies the\n", + " number of nodes in each of the networks layers. The first integer in the array\n", + " defines the number of nodes in the input layer, the second integer defines number\n", + " of nodes in the first hidden layer and so on until the last number, which\n", + " specifies the number of nodes in the output layer.\n", + " II hidden_func (Callable): The activation function for the hidden layers\n", + " III output_func (Callable): The activation function for the output layer\n", + " IV cost_func (Callable): Our cost function\n", + " V seed (int): Sets random seed, makes results reproducible\n", + " \"\"\"\n", + "\n", + " def __init__(\n", + " self,\n", + " dimensions: tuple[int],\n", + " hidden_func: Callable = sigmoid,\n", + " output_func: Callable = lambda x: x,\n", + " cost_func: Callable = CostOLS,\n", + " seed: int = None,\n", + " ):\n", + " self.dimensions = dimensions\n", + " self.hidden_func = hidden_func\n", + " self.output_func = output_func\n", + " self.cost_func = cost_func\n", + " self.seed = seed\n", + " self.weights = list()\n", + " self.schedulers_weight = list()\n", + " self.schedulers_bias = list()\n", + " self.a_matrices = list()\n", + " self.z_matrices = list()\n", + " self.classification = None\n", + "\n", + " self.reset_weights()\n", + " self._set_classification()\n", + "\n", + " def fit(\n", + " self,\n", + " X: np.ndarray,\n", + " t: np.ndarray,\n", + " scheduler: Scheduler,\n", + " batches: int = 1,\n", + " epochs: int = 100,\n", + " lam: float = 0,\n", + " X_val: np.ndarray = None,\n", + " t_val: np.ndarray = None,\n", + " ):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " This function performs the training the neural network by performing the feedforward and backpropagation\n", + " algorithm to update the networks weights.\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray) : training data\n", + " II t (np.ndarray) : target data\n", + " III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)\n", + " IV scheduler_args (list[int]) : list of all arguments necessary for scheduler\n", + "\n", + " Optional Parameters:\n", + " ------------\n", + " V batches (int) : number of batches the datasets are split into, default equal to 1\n", + " VI epochs (int) : number of iterations used to train the network, default equal to 100\n", + " VII lam (float) : regularization hyperparameter lambda\n", + " VIII X_val (np.ndarray) : validation set\n", + " IX t_val (np.ndarray) : validation target set\n", + "\n", + " Returns:\n", + " ------------\n", + " I scores (dict) : A dictionary containing the performance metrics of the model.\n", + " The number of the metrics depends on the parameters passed to the fit-function.\n", + "\n", + " \"\"\"\n", + "\n", + " # setup \n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " val_set = False\n", + " if X_val is not None and t_val is not None:\n", + " val_set = True\n", + "\n", + " # creating arrays for score metrics\n", + " train_errors = np.empty(epochs)\n", + " train_errors.fill(np.nan)\n", + " val_errors = np.empty(epochs)\n", + " val_errors.fill(np.nan)\n", + "\n", + " train_accs = np.empty(epochs)\n", + " train_accs.fill(np.nan)\n", + " val_accs = np.empty(epochs)\n", + " val_accs.fill(np.nan)\n", + "\n", + " self.schedulers_weight = list()\n", + " self.schedulers_bias = list()\n", + "\n", + " batch_size = X.shape[0] // batches\n", + "\n", + " X, t = resample(X, t)\n", + "\n", + " # this function returns a function valued only at X\n", + " cost_function_train = self.cost_func(t)\n", + " if val_set:\n", + " cost_function_val = self.cost_func(t_val)\n", + "\n", + " # create schedulers for each weight matrix\n", + " for i in range(len(self.weights)):\n", + " self.schedulers_weight.append(copy(scheduler))\n", + " self.schedulers_bias.append(copy(scheduler))\n", + "\n", + " print(f\"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}\")\n", + "\n", + " try:\n", + " for e in range(epochs):\n", + " for i in range(batches):\n", + " # allows for minibatch gradient descent\n", + " if i == batches - 1:\n", + " # If the for loop has reached the last batch, take all thats left\n", + " X_batch = X[i * batch_size :, :]\n", + " t_batch = t[i * batch_size :, :]\n", + " else:\n", + " X_batch = X[i * batch_size : (i + 1) * batch_size, :]\n", + " t_batch = t[i * batch_size : (i + 1) * batch_size, :]\n", + "\n", + " self._feedforward(X_batch)\n", + " self._backpropagate(X_batch, t_batch, lam)\n", + "\n", + " # reset schedulers for each epoch (some schedulers pass in this call)\n", + " for scheduler in self.schedulers_weight:\n", + " scheduler.reset()\n", + "\n", + " for scheduler in self.schedulers_bias:\n", + " scheduler.reset()\n", + "\n", + " # computing performance metrics\n", + " pred_train = self.predict(X)\n", + " train_error = cost_function_train(pred_train)\n", + "\n", + " train_errors[e] = train_error\n", + " if val_set:\n", + " \n", + " pred_val = self.predict(X_val)\n", + " val_error = cost_function_val(pred_val)\n", + " val_errors[e] = val_error\n", + "\n", + " if self.classification:\n", + " train_acc = self._accuracy(self.predict(X), t)\n", + " train_accs[e] = train_acc\n", + " if val_set:\n", + " val_acc = self._accuracy(pred_val, t_val)\n", + " val_accs[e] = val_acc\n", + "\n", + " # printing progress bar\n", + " progression = e / epochs\n", + " print_length = self._progress_bar(\n", + " progression,\n", + " train_error=train_errors[e],\n", + " train_acc=train_accs[e],\n", + " val_error=val_errors[e],\n", + " val_acc=val_accs[e],\n", + " )\n", + " except KeyboardInterrupt:\n", + " # allows for stopping training at any point and seeing the result\n", + " pass\n", + "\n", + " # visualization of training progression (similiar to tensorflow progression bar)\n", + " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", + " sys.stdout.flush()\n", + " self._progress_bar(\n", + " 1,\n", + " train_error=train_errors[e],\n", + " train_acc=train_accs[e],\n", + " val_error=val_errors[e],\n", + " val_acc=val_accs[e],\n", + " )\n", + " sys.stdout.write(\"\")\n", + "\n", + " # return performance metrics for the entire run\n", + " scores = dict()\n", + "\n", + " scores[\"train_errors\"] = train_errors\n", + "\n", + " if val_set:\n", + " scores[\"val_errors\"] = val_errors\n", + "\n", + " if self.classification:\n", + " scores[\"train_accs\"] = train_accs\n", + "\n", + " if val_set:\n", + " scores[\"val_accs\"] = val_accs\n", + "\n", + " return scores\n", + "\n", + " def predict(self, X: np.ndarray, *, threshold=0.5):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs prediction after training of the network has been finished.\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray): The design matrix, with n rows of p features each\n", + "\n", + " Optional Parameters:\n", + " ------------\n", + " II threshold (float) : sets minimal value for a prediction to be predicted as the positive class\n", + " in classification problems\n", + "\n", + " Returns:\n", + " ------------\n", + " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", + " This vector is thresholded if regression=False, meaning that classification results\n", + " in a vector of 1s and 0s, while regressions in an array of decimal numbers\n", + "\n", + " \"\"\"\n", + "\n", + " predict = self._feedforward(X)\n", + "\n", + " if self.classification:\n", + " return np.where(predict > threshold, 1, 0)\n", + " else:\n", + " return predict\n", + "\n", + " def reset_weights(self):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Resets/Reinitializes the weights in order to train the network for a new problem.\n", + "\n", + " \"\"\"\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " self.weights = list()\n", + " for i in range(len(self.dimensions) - 1):\n", + " weight_array = np.random.randn(\n", + " self.dimensions[i] + 1, self.dimensions[i + 1]\n", + " )\n", + " weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01\n", + "\n", + " self.weights.append(weight_array)\n", + "\n", + " def _feedforward(self, X: np.ndarray):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Calculates the activation of each layer starting at the input and ending at the output.\n", + " Each following activation is calculated from a weighted sum of each of the preceeding\n", + " activations (except in the case of the input layer).\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray): The design matrix, with n rows of p features each\n", + "\n", + " Returns:\n", + " ------------\n", + " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", + " \"\"\"\n", + "\n", + " # reset matrices\n", + " self.a_matrices = list()\n", + " self.z_matrices = list()\n", + "\n", + " # if X is just a vector, make it into a matrix\n", + " if len(X.shape) == 1:\n", + " X = X.reshape((1, X.shape[0]))\n", + "\n", + " # Add a coloumn of zeros as the first coloumn of the design matrix, in order\n", + " # to add bias to our data\n", + " bias = np.ones((X.shape[0], 1)) * 0.01\n", + " X = np.hstack([bias, X])\n", + "\n", + " # a^0, the nodes in the input layer (one a^0 for each row in X - where the\n", + " # exponent indicates layer number).\n", + " a = X\n", + " self.a_matrices.append(a)\n", + " self.z_matrices.append(a)\n", + "\n", + " # The feed forward algorithm\n", + " for i in range(len(self.weights)):\n", + " if i < len(self.weights) - 1:\n", + " z = a @ self.weights[i]\n", + " self.z_matrices.append(z)\n", + " a = self.hidden_func(z)\n", + " # bias column again added to the data here\n", + " bias = np.ones((a.shape[0], 1)) * 0.01\n", + " a = np.hstack([bias, a])\n", + " self.a_matrices.append(a)\n", + " else:\n", + " try:\n", + " # a^L, the nodes in our output layers\n", + " z = a @ self.weights[i]\n", + " a = self.output_func(z)\n", + " self.a_matrices.append(a)\n", + " self.z_matrices.append(z)\n", + " except Exception as OverflowError:\n", + " print(\n", + " \"OverflowError in fit() in FFNN\\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling\"\n", + " )\n", + "\n", + " # this will be a^L\n", + " return a\n", + "\n", + " def _backpropagate(self, X, t, lam):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs the backpropagation algorithm. In other words, this method\n", + " calculates the gradient of all the layers starting at the\n", + " output layer, and moving from right to left accumulates the gradient until\n", + " the input layer is reached. Each layers respective weights are updated while\n", + " the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray): The design matrix, with n rows of p features each.\n", + " II t (np.ndarray): The target vector, with n rows of p targets.\n", + " III lam (float32): regularization parameter used to punish the weights in case of overfitting\n", + "\n", + " Returns:\n", + " ------------\n", + " No return value.\n", + "\n", + " \"\"\"\n", + " out_derivative = derivate(self.output_func)\n", + " hidden_derivative = derivate(self.hidden_func)\n", + "\n", + " for i in range(len(self.weights) - 1, -1, -1):\n", + " # delta terms for output\n", + " if i == len(self.weights) - 1:\n", + " # for multi-class classification\n", + " if (\n", + " self.output_func.__name__ == \"softmax\"\n", + " ):\n", + " delta_matrix = self.a_matrices[i + 1] - t\n", + " # for single class classification\n", + " else:\n", + " cost_func_derivative = grad(self.cost_func(t))\n", + " delta_matrix = out_derivative(\n", + " self.z_matrices[i + 1]\n", + " ) * cost_func_derivative(self.a_matrices[i + 1])\n", + "\n", + " # delta terms for hidden layer\n", + " else:\n", + " delta_matrix = (\n", + " self.weights[i + 1][1:, :] @ delta_matrix.T\n", + " ).T * hidden_derivative(self.z_matrices[i + 1])\n", + "\n", + " # calculate gradient\n", + " gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix\n", + " gradient_bias = np.sum(delta_matrix, axis=0).reshape(\n", + " 1, delta_matrix.shape[1]\n", + " )\n", + "\n", + " # regularization term\n", + " gradient_weights += self.weights[i][1:, :] * lam\n", + "\n", + " # use scheduler\n", + " update_matrix = np.vstack(\n", + " [\n", + " self.schedulers_bias[i].update_change(gradient_bias),\n", + " self.schedulers_weight[i].update_change(gradient_weights),\n", + " ]\n", + " )\n", + "\n", + " # update weights and bias\n", + " self.weights[i] -= update_matrix\n", + "\n", + " def _accuracy(self, prediction: np.ndarray, target: np.ndarray):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Calculates accuracy of given prediction to target\n", + "\n", + " Parameters:\n", + " ------------\n", + " I prediction (np.ndarray): vector of predicitons output network\n", + " (1s and 0s in case of classification, and real numbers in case of regression)\n", + " II target (np.ndarray): vector of true values (What the network ideally should predict)\n", + "\n", + " Returns:\n", + " ------------\n", + " A floating point number representing the percentage of correctly classified instances.\n", + " \"\"\"\n", + " assert prediction.size == target.size\n", + " return np.average((target == prediction))\n", + " def _set_classification(self):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Decides if FFNN acts as classifier (True) og regressor (False),\n", + " sets self.classification during init()\n", + " \"\"\"\n", + " self.classification = False\n", + " if (\n", + " self.cost_func.__name__ == \"CostLogReg\"\n", + " or self.cost_func.__name__ == \"CostCrossEntropy\"\n", + " ):\n", + " self.classification = True\n", + "\n", + " def _progress_bar(self, progression, **kwargs):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Displays progress of training\n", + " \"\"\"\n", + " print_length = 40\n", + " num_equals = int(progression * print_length)\n", + " num_not = print_length - num_equals\n", + " arrow = \">\" if num_equals > 0 else \"\"\n", + " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", + " perc_print = self._format(progression * 100, decimals=5)\n", + " line = f\" {bar} {perc_print}% \"\n", + "\n", + " for key in kwargs:\n", + " if not np.isnan(kwargs[key]):\n", + " value = self._format(kwargs[key], decimals=4)\n", + " line += f\"| {key}: {value} \"\n", + " sys.stdout.write(\"\\r\" + line)\n", + " sys.stdout.flush()\n", + " return len(line)\n", + "\n", + " def _format(self, value, decimals=4):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Formats decimal numbers for progress bar\n", + " \"\"\"\n", + " if value > 0:\n", + " v = value\n", + " elif value < 0:\n", + " v = -10 * value\n", + " else:\n", + " v = 1\n", + " n = 1 + math.floor(math.log10(v))\n", + " if n >= decimals - 1:\n", + " return str(round(value))\n", + " return f\"{value:.{decimals-n-1}f}\"" + ] + }, + { + "cell_type": "markdown", + "id": "b5aaa66b", + "metadata": { + "editable": true + }, + "source": [ + "Before we make a model, we will quickly generate a dataset we can use\n", + "for our linear regression problem as shown below" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "35f13536", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "def SkrankeFunction(x, y):\n", + " return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)\n", + "\n", + "def create_X(x, y, n):\n", + " if len(x.shape) > 1:\n", + " x = np.ravel(x)\n", + " y = np.ravel(y)\n", + "\n", + " N = len(x)\n", + " l = int((n + 1) * (n + 2) / 2) # Number of elements in beta\n", + " X = np.ones((N, l))\n", + "\n", + " for i in range(1, n + 1):\n", + " q = int((i) * (i + 1) / 2)\n", + " for k in range(i + 1):\n", + " X[:, q + k] = (x ** (i - k)) * (y**k)\n", + "\n", + " return X\n", + "\n", + "step=0.5\n", + "x = np.arange(0, 1, step)\n", + "y = np.arange(0, 1, step)\n", + "x, y = np.meshgrid(x, y)\n", + "target = SkrankeFunction(x, y)\n", + "target = target.reshape(target.shape[0], 1)\n", + "\n", + "poly_degree=3\n", + "X = create_X(x, y, poly_degree)\n", + "\n", + "X_train, X_test, t_train, t_test = train_test_split(X, target)" + ] + }, + { + "cell_type": "markdown", + "id": "12780998", + "metadata": { + "editable": true + }, + "source": [ + "Now that we have our dataset ready for the regression, we can create\n", + "our regressor. Note that with the seed parameter, we can make sure our\n", + "results stay the same every time we run the neural network. For\n", + "inititialization, we simply specify the dimensions (we wish the amount\n", + "of input nodes to be equal to the datapoints, and the output to\n", + "predict one value)." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "3de4263c", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "input_nodes = X_train.shape[1]\n", + "output_nodes = 1\n", + "\n", + "linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)" + ] + }, + { + "cell_type": "markdown", + "id": "e3ca1fb5", + "metadata": { + "editable": true + }, + "source": [ + "We then fit our model with our training data using the scheduler of our choice." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "714229a9", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Constant: Eta=0.001, Lambda=0\n", + " [=======================================>] 100.0% | train_error: 10.9 " + ] + } + ], + "source": [ + "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Constant(eta=1e-3)\n", + "scores = linear_regression.fit(X_train, t_train, scheduler)" + ] + }, + { + "cell_type": "markdown", + "id": "2240c6b8", + "metadata": { + "editable": true + }, + "source": [ + "Due to the progress bar we can see the MSE (train_error) throughout\n", + "the FFNN's training. Note that the fit() function has some optional\n", + "parameters with defualt arguments. For example, the regularization\n", + "hyperparameter can be left ignored if not needed, and equally the FFNN\n", + "will by default run for 100 epochs. These can easily be changed, such\n", + "as for example:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "96f9f1ab", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Constant: Eta=0.001, Lambda=0.0001\n", + " [=======================================>] 100.0% | train_error: 1.00 " + ] + } + ], + "source": [ + "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)" + ] + }, + { + "cell_type": "markdown", + "id": "21af3f64", + "metadata": { + "editable": true + }, + "source": [ + "We see that given more epochs to train on, the regressor reaches a lower MSE.\n", + "\n", + "Let us then switch to a binary classification. We use a binary\n", + "classification dataset, and follow a similar setup to the regression\n", + "case." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "98f0055d", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "wisconsin = load_breast_cancer()\n", + "X = wisconsin.data\n", + "target = wisconsin.target\n", + "target = target.reshape(target.shape[0], 1)\n", + "\n", + "X_train, X_val, t_train, t_val = train_test_split(X, target)\n", + "\n", + "scaler = MinMaxScaler()\n", + "scaler.fit(X_train)\n", + "X_train = scaler.transform(X_train)\n", + "X_val = scaler.transform(X_val)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "fbd2675f", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "input_nodes = X_train.shape[1]\n", + "output_nodes = 1\n", + "\n", + "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)" + ] + }, + { + "cell_type": "markdown", + "id": "64ed3461", + "metadata": { + "editable": true + }, + "source": [ + "We will now make use of our validation data by passing it into our fit function as a keyword argument" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "1cdc9d23", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Adam: Eta=0.001, Lambda=0\n", + " [=======================================>] 100.0% | train_error: 3.21 | train_acc: 0.845 | val_error: 3.77 | val_acc: 0.818 " + ] + } + ], + "source": [ + "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", + "scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" + ] + }, + { + "cell_type": "markdown", + "id": "13e2f881", + "metadata": { + "editable": true + }, + "source": [ + "Finally, we will create a neural network with 2 hidden layers with activation functions." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "c28f2181", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [], + "source": [ + "input_nodes = X_train.shape[1]\n", + "hidden_nodes1 = 100\n", + "hidden_nodes2 = 30\n", + "output_nodes = 1\n", + "\n", + "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", + "\n", + "neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "3150b724", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Adam: Eta=0.0001, Lambda=0\n", + " [=======================================>] 100.0% | train_error: 0.0973 | train_acc: 0.995 | val_error: 1.74 | val_acc: 0.916 " + ] + } + ], + "source": [ + "neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", + "scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" + ] + }, + { + "cell_type": "markdown", + "id": "17aebab2", + "metadata": { + "editable": true + }, + "source": [ + "### Multiclass classification\n", + "\n", + "Finally, we will demonstrate the use case of multiclass classification\n", + "using our FFNN with the famous MNIST dataset, which contain images of\n", + "digits between the range of 0 to 9." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "997c5001", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Adam: Eta=0.0001, Lambda=0\n", + " [=======================================>] 100.0% | train_error: 0.175 | train_acc: 0.983 " + ] + } + ], + "source": [ + "from sklearn.datasets import load_digits\n", + "\n", + "def onehot(target: np.ndarray):\n", + " onehot = np.zeros((target.size, target.max() + 1))\n", + " onehot[np.arange(target.size), target] = 1\n", + " return onehot\n", + "\n", + "digits = load_digits()\n", + "\n", + "X = digits.data\n", + "target = digits.target\n", + "target = onehot(target)\n", + "\n", + "input_nodes = 64\n", + "hidden_nodes1 = 100\n", + "hidden_nodes2 = 30\n", + "output_nodes = 10\n", + "\n", + "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", + "\n", + "multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)\n", + "\n", + "multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "\n", + "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", + "scores = multiclass.fit(X, target, scheduler, epochs=1000)" + ] + }, + { + "cell_type": "markdown", + "id": "43d805bc", + "metadata": { + "editable": true + }, + "source": [ + "## Testing the XOR gate and other gates\n", + "\n", + "Let us now use our code to test the XOR gate." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "4bbaf697", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Adam: Eta=0.001, Lambda=0\n", + " [=======================================>] 100.0% | train_error: 10.4 | train_acc: 0.500 " + ] + } + ], + "source": [ + "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", + "\n", + "# The XOR gate\n", + "yXOR = np.array( [[ 0], [1] ,[1], [0]])\n", + "\n", + "input_nodes = X.shape[1]\n", + "output_nodes = 1\n", + "\n", + "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)\n", + "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", + "scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", + "scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)" + ] + }, + { + "cell_type": "markdown", + "id": "31e852a7", + "metadata": { + "editable": true + }, + "source": [ + "Not bad, but the results depend strongly on the learning reate. Try different learning rates." + ] + }, + { + "cell_type": "markdown", + "id": "9792c0c3", + "metadata": { + "editable": true + }, + "source": [ + "## Solving differential equations with Deep Learning\n", "\n", "The Universal Approximation Theorem states that a neural network can\n", "approximate any function at a single hidden layer along with one input\n", - "and output layer to any given precision. \n", + "and output layer to any given precision.\n", "\n", + "**Book on solving differential equations with ML methods.**\n", "\n", - "## Ordinary Differential Equations\n", + "[An Introduction to Neural Network Methods for Differential Equations](https://www.springer.com/gp/book/9789401798150), by Yadav and Kumar.\n", + "\n", + "**Physics informed neural networks.**\n", + "\n", + "[Scientific Machine Learning Through Physics–Informed Neural Networks: Where we are and What’s Next](https://link.springer.com/article/10.1007/s10915-022-01939-z), by Cuomo et al\n", + "\n", + "**Thanks to Kristine Baluka Hein.**\n", + "\n", + "The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI.\n", + "A great thanks to Kristine." + ] + }, + { + "cell_type": "markdown", + "id": "9214a407", + "metadata": { + "editable": true + }, + "source": [ + "## Ordinary Differential Equations first\n", "\n", "An ordinary differential equation (ODE) is an equation involving functions having one variable.\n", "\n", @@ -58,7 +3667,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "40a78c33", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -72,7 +3684,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "42dae561", + "metadata": { + "editable": true + }, "source": [ "where $g(x)$ is the function to find, and $g^{(n)}(x)$ is the $n$-th derivative of $g(x)$.\n", "\n", @@ -80,8 +3695,16 @@ "The highest order of derivative, that is the value of $n$, determines to the order of the equation.\n", "The equation is referred to as a $n$-th order ODE.\n", "Along with ([1](#ode)), some additional conditions of the function $g(x)$ are typically given\n", - "for the solution to be unique.\n", - "\n", + "for the solution to be unique." + ] + }, + { + "cell_type": "markdown", + "id": "b4bf5f2e", + "metadata": { + "editable": true + }, + "source": [ "## The trial solution\n", "\n", "Let the trial solution $g_t(x)$ be" @@ -89,7 +3712,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1f4f3eba", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -104,7 +3730,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d799a47c", + "metadata": { + "editable": true + }, "source": [ "where $h_1(x)$ is a function that makes $g_t(x)$ satisfy a given set\n", "of conditions, $N(x,P)$ a neural network with weights and biases\n", @@ -117,10 +3746,16 @@ "\n", "But what about the network $N(x,P)$?\n", "\n", - "\n", - "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.\n", - "\n", - "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "abb02959", + "metadata": { + "editable": true + }, + "source": [ "## Minimization process\n", "\n", "For the minimization to be defined, we need to have a cost function at hand to minimize.\n", @@ -133,7 +3768,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6468ecf8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C\\left(x, P\\right) = \\big(f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)\\big)^2\n", @@ -142,7 +3780,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e7441b12", + "metadata": { + "editable": true + }, "source": [ "If $N$ inputs are given as a vector $\\boldsymbol{x}$ with elements $x_i$ for $i = 1,\\dots,N$,\n", "the cost function becomes" @@ -150,7 +3791,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0ffd1c29", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -164,20 +3808,38 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e55c8d3e", + "metadata": { + "editable": true + }, "source": [ "The neural net should then find the parameters $P$ that minimizes the cost function in\n", - "([3](#cost)) for a set of $N$ training samples $x_i$.\n", - "\n", + "([3](#cost)) for a set of $N$ training samples $x_i$." + ] + }, + { + "cell_type": "markdown", + "id": "8a940e88", + "metadata": { + "editable": true + }, + "source": [ "## Minimizing the cost function using gradient descent and automatic differentiation\n", "\n", "To perform the minimization using gradient descent, the gradient of $C\\left(\\boldsymbol{x}, P\\right)$ is needed.\n", "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.\n", "\n", "Luckily, there exists libraries that makes the job for us through automatic differentiation.\n", - "Automatic differentiation is a method of finding the derivatives numerically with very high precision.\n", - "\n", - "\n", + "Automatic differentiation is a method of finding the derivatives numerically with very high precision." + ] + }, + { + "cell_type": "markdown", + "id": "547613c0", + "metadata": { + "editable": true + }, + "source": [ "## Example: Exponential decay\n", "\n", "An exponential decay of a quantity $g(x)$ is described by the equation" @@ -185,7 +3847,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "826651d6", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -199,7 +3864,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "870b960b", + "metadata": { + "editable": true + }, "source": [ "with $g(0) = g_0$ for some chosen initial value $g_0$.\n", "\n", @@ -208,7 +3876,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5a8fd1e3", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -223,11 +3894,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "55b4f286", + "metadata": { + "editable": true + }, + "source": [ + "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))." + ] + }, + { + "cell_type": "markdown", + "id": "7e4f689b", + "metadata": { + "editable": true + }, "source": [ - "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)).\n", - "\n", - "\n", "## The function to solve for\n", "\n", "The program will use a neural network to solve" @@ -235,7 +3916,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "01e8e999", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -249,19 +3933,33 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7ccea9f1", + "metadata": { + "editable": true + }, "source": [ "where $g(0) = g_0$ with $\\gamma$ and $g_0$ being some chosen values.\n", "\n", - "In this example, $\\gamma = 2$ and $g_0 = 10$.\n", - "\n", + "In this example, $\\gamma = 2$ and $g_0 = 10$." + ] + }, + { + "cell_type": "markdown", + "id": "47fde776", + "metadata": { + "editable": true + }, + "source": [ "## The trial solution\n", "To begin with, a trial solution $g_t(t)$ must be chosen. A general trial solution for ordinary differential equations could be" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f7a8f626", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_t(x, P) = h_1(x) + h_2(x, N(x, P))\n", @@ -270,10 +3968,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "66551df0", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "c354ef4e", + "metadata": { + "editable": true + }, "source": [ - "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.\n", - "\n", "## Setup of Network\n", "\n", "In this network, there are no weights and bias at the input layer, so $P = \\{ P_{\\text{hidden}}, P_{\\text{output}} \\}$.\n", @@ -289,7 +3998,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a574c0b7", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -303,7 +4015,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "22f440c8", + "metadata": { + "editable": true + }, "source": [ "## Reformulating the problem\n", "\n", @@ -319,7 +4034,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0ff80a83", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_t(x, P) = g_0 + x \\cdot N(x, P)\n", @@ -328,14 +4046,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6829edab", + "metadata": { + "editable": true + }, "source": [ "has been chosen such that it already solves the condition $g(0) = g_0$. What remains, is to find $P$ such that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "381c61e2", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -349,10 +4073,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ac36a03d", + "metadata": { + "editable": true + }, + "source": [ + "is fulfilled as *best as possible*." + ] + }, + { + "cell_type": "markdown", + "id": "2899becc", + "metadata": { + "editable": true + }, "source": [ - "is fulfilled as *best as possible*.\n", - "\n", "## More technicalities\n", "\n", "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.\n", @@ -364,7 +4099,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d52c8124", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\min_{P}\\Big\\{ \\big(g_t'(x, P) - ( -\\gamma g_t(x, P) \\big)^2 \\Big\\}\n", @@ -373,7 +4111,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3f8f684e", + "metadata": { + "editable": true + }, "source": [ "(the notation $\\min_{P}\\{ f(x, P) \\}$ means that we desire to find $P$ that yields the minimum of $f(x, P)$)\n", "\n", @@ -382,7 +4123,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "92cc16c9", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }}\\Big\\{ \\big(g_t'(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) - ( -\\gamma g_t(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) \\big)^2 \\Big\\}\n", @@ -391,10 +4135,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "628e0dfc", + "metadata": { + "editable": true + }, + "source": [ + "for an input value $x$." + ] + }, + { + "cell_type": "markdown", + "id": "e54b4c6e", + "metadata": { + "editable": true + }, "source": [ - "for an input value $x$.\n", - "\n", "## More details\n", "\n", "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" @@ -402,7 +4157,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "80dc48dd", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -416,14 +4174,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e57a1d70", + "metadata": { + "editable": true + }, "source": [ "Letting $\\boldsymbol{x}$ be a vector with elements $x_i$ and $C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2$ denote the cost function, the minimization problem that our network must solve, becomes" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8ad67e57", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\min_{P} C(\\boldsymbol{x}, P)\n", @@ -432,22 +4196,41 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4eed66ce", + "metadata": { + "editable": true + }, "source": [ "In terms of $P_{\\text{hidden} }$ and $P_{\\text{output} }$, this could also be expressed as\n", "\n", "$$\n", "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }} C(\\boldsymbol{x}, \\{P_{\\text{hidden} }, P_{\\text{output} }\\})\n", - "$$\n", - "\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9d652c56", + "metadata": { + "editable": true + }, + "source": [ "## A possible implementation of a neural network\n", "\n", "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)).\n", "\n", "First, the neural network must feed forward the inputs.\n", "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.\n", - "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} }$.\n", - "\n", + "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} }$." + ] + }, + { + "cell_type": "markdown", + "id": "9a5a1ad7", + "metadata": { + "editable": true + }, + "source": [ "## Technicalities\n", "\n", "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:" @@ -455,7 +4238,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ed15e067", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -474,7 +4260,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "827ac223", + "metadata": { + "editable": true + }, "source": [ "## Final technicalities I\n", "\n", @@ -483,7 +4272,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a0a7b13f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -503,7 +4295,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0879010a", + "metadata": { + "editable": true + }, "source": [ "## Final technicalities II\n", "\n", @@ -516,7 +4311,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "66ac91b3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(z) = \\frac{1}{1 + \\exp{(-z)}}\n", @@ -525,7 +4323,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "470c74b5", + "metadata": { + "editable": true + }, "source": [ "It is possible to use other activations functions for the hidden layer also.\n", "\n", @@ -541,17 +4342,27 @@ "output from each of the neurons in the hidden layers. The output layer\n", "combines the results from the hidden layer using some weights $w_i^{\\text{output}}$\n", "and biases $b_i^{\\text{output}}$. In this case,\n", - "it is assumes that the number of neurons in the output layer is one.\n", - "\n", + "it is assumes that the number of neurons in the output layer is one." + ] + }, + { + "cell_type": "markdown", + "id": "bf5e6967", + "metadata": { + "editable": true + }, + "source": [ "## Final technicalities III\n", "\n", - "\n", "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." ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "766b88f8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -569,7 +4380,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5c114139", + "metadata": { + "editable": true + }, "source": [ "## Final technicalities IV\n", "\n", @@ -578,7 +4392,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "45596281", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{z}_{1}^{\\text{output}} =\n", @@ -594,10 +4411,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2c1378fb", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "66a732e1", + "metadata": { + "editable": true + }, "source": [ - "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.\n", - "\n", "## Back propagation\n", "\n", "The next step is to decide how the parameters should be changed such that they minimize the cost function.\n", @@ -607,7 +4435,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fdf81225", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2\n", @@ -616,12 +4447,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9bb52111", + "metadata": { + "editable": true + }, "source": [ "In order to minimize the cost function, an optimization method must be chosen.\n", "\n", - "Here, gradient descent with a constant step size has been chosen.\n", - "\n", + "Here, gradient descent with a constant step size has been chosen." + ] + }, + { + "cell_type": "markdown", + "id": "f3e495b4", + "metadata": { + "editable": true + }, + "source": [ "## Gradient descent\n", "\n", "The idea of the gradient descent algorithm is to update parameters in\n", @@ -634,7 +4476,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "adc904df", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\omega}_{\\text{new} } = \\boldsymbol{\\omega} - \\lambda \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})\n", @@ -643,7 +4488,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2d01b1b5", + "metadata": { + "editable": true + }, "source": [ "for a number of iterations or until $ \\big|\\big| \\boldsymbol{\\omega}_{\\text{new} } - \\boldsymbol{\\omega} \\big|\\big|$ becomes smaller than some given tolerance.\n", "\n", @@ -662,7 +4510,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5077f4f7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -674,45 +4525,27 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fb01e943", + "metadata": { + "editable": true + }, "source": [ "## The code for solving the ODE" ] }, { "cell_type": "code", - "execution_count": 1, - "metadata": {}, -<<<<<<< HEAD - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Initial cost: 367.01\n", - "Final cost: 0.0666807\n", - "Max absolute difference: 0.0437499\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAl4AAAJcCAYAAAAo6aqNAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+j8jraAAAgAElEQVR4nOzdd3gU5d7G8e9vk5BQQg89NAsgCAiICBZsx4aCIiqCqEfsvRzsx97LsRdAREURRFFRLIiCohTpvShFOqGEGiDlef+YwTfGNCDJ7G7uz3VxkexsuWf22dl7n53dmHMOERERESl+oaADiIiIiJQWKl4iIiIiJUTFS0RERKSEqHiJiIiIlBAVLxEREZESouIlIiIiUkJUvEqImdU0s5/MbLuZPR90nqCZWVkzG2VmW83s46Dz5MfMLjezCUHnOBhm1tnMVhXzbYwzs76FON/xZraoOLNIeCvsWCnC21tuZqeW1O0diIPZz5hZfTPbYWYxB5mhyO+Xg9n2RbVe4UbFKx/+gEnz7/j1ZvaOmVU4wKu7GtgIVHTO3VGEMSPVBUBNoJpzrkfQYYJgZg3NzJlZbNBZSpJz7mfnXJOgcxSGmXUxsylmttPMNpnZB2ZWL9vyy80s099H7DCzZf5+4vB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OOCDCRipeIiIiUsG7dutG2bVuaN29O//79AahQoQL33XcfrVq1okOHDqxfvx6AUaNGccwxx3DUUUdx6qmn/nX6Ptu3b6dRo0akp6cDsG3bNho2bMjHH3/M1KlT6dWrF61btyYtLY3OnTv/9ScIv/nmG9q0aUOrVq045ZRTAJgyZQodO3bkqKOOomPHjixatKjI111fJyEiIlIKPTxqHvPXbCvS6zyiTkUePKd5gecbNGgQVatWJS0tjaOPPpru3buzc+dOOnTowOOPP06/fv0YMGAA999/P8cddxyTJk3CzBg4cCDPPPMMzz///F/XlZiYSOfOnfnqq6/o1q0bH330Ed27d6dHjx689tprPPfcc7Rr1+5vt5+SksJVV13FTz/9RKNGjdi8eTMATZs25aeffiI2Npbvv/+ee++9l08++aRIt5GKl4iIiJSol19+mZEjRwKwcuVKlixZQpkyZf46jqpt27aMGTMG8L577KKLLmLt2rXs3bs31+/M6tu3L8888wzdunXjnXfeYcCAAfne/qRJkzjhhBP+uq6qVasCsHXrVi677DKWLFmCmf01i1aUVLxERERKocLMTBWHcePG8f333zNx4kTKlStH586d2b17N3FxcX99PUNMTAwZGRkA3HTTTdx+++2ce+65jBs3joceeugf19mpUyeWL1/O+PHjyczMpEWLFvlmcM7l+lUQDzzwACeddBIjR45k+fLldO7c+aDXNycd4yUiIiIlZuvWrVSpUoVy5cqxcOFCJk2aVOD569atC8C7776b5/n69OlDz549ueKKK/46LTExke3bt//jvMceeyzjx49n2bJlAH+91Zj9tgYPHrxf61VYKl4iIiJSYs444wwyMjJo2bIlDzzwAB06dMj3/A899BA9evTg+OOPp3r16nmer1evXmzZsoWePXv+ddrll1/Otdde+9fB9fskJSXRv39/zj//fFq1asVFF10EQL9+/bjnnnvo1KkTmZmZB7mmuTPnXLFccVFq166d2/cpBBERETkwCxYsoFmzZkHHKBYjRozg888/5/333y/R281tm5rZNOdcu9zOr2O8REREJKLddNNNfP3114wePTroKAVS8RIREZGI9sorrwQdodB0jJeIiIhICSm24mVmg8xsg5nNzXZaVTMbY2Z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FTkSuQmCC\n", - "text/plain": [ - "
    " - ] - }, - "metadata": { - "needs_background": "light" - }, - "output_type": "display_data" + "execution_count": 31, + "id": "6347e101", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false } - ], -======= + }, "outputs": [], ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 "source": [ - "%matplotlib inline\n", - "\n", "import autograd.numpy as np\n", "from autograd import grad, elementwise_grad\n", "import autograd.numpy.random as npr\n", @@ -861,7 +4694,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "59e5acda", + "metadata": { + "editable": true + }, "source": [ "## The network with one input layer, specified number of hidden layers, and one output layer\n", "\n", @@ -872,34 +4708,16 @@ }, { "cell_type": "code", - "execution_count": 2, - "metadata": {}, -<<<<<<< HEAD - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Initial cost: 324.246\n", - "Final cost: 0.119936\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAl4AAAJOCAYAAABm9wkdAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+j8jraAAAgAElEQVR4nOzddZxU9f7H8ddng126G5QUKUHAQkUUW1AEsUDQa16v9bO7rl692IEFEoKCimIgBgaKIJ1KiISkdG+w8f39cQ7ecd2E3Tkzs+/n47EPmH6fMyfe8z1nZ805h4iIiIiUvLigA4iIiIiUFipeIiIiImGi4iUiIiISJipeIiIiImGi4iUiIiISJipeIiIiImGi4hXCzGqb2Q9mttvMngk6T9DMrKyZfWpmO83s/RJ4/lVmdmpxP2+0MLNGZubMLCHoLAfDn4ZmJfj8D5vZqELed4+ZNSmpLBLZirKsFNPrDTezx8L1egfiYLczZvaLmXU9yAzF/r4c7Lwvjuk6UFFfvPydd6q/wd1oZsPMrMIBPt01w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25/p0K14HAYX/8fnyPf+3t8do39nbn/fVVLxKUdX62rmEEA4CzgceS2KudFaZ35XvAPuHECaEEGaHEC5PWrr0VZm5PAIcBqwEFgC3RlFUnpx4+hKxPddnJuObpJDwBf/3+etpVOYY7TuV/nmHEE6ionj1rNJEgsrNZRDwyyiKyipeyKuKVWYmmUA34BSgDjA1hDAtiqJFVR0ujVVmLqcD84CTgUOAsSGEyVEUbanqcPpSsT3Xp1vxWg60/I/PD6biFcjeHqN9p1I/7xBCF+BJ4MwoitYnKVs6q8xcugMv7SldTYCzQgilURS9mZyIaaeyf7/WRVG0HdgeQpgEHAFYvKpOZebSD7g3qthctDiEsBToCMxITkR9gdie69PtVONMoH0IoW0IIRu4BHjrc8e8BVy+5x0PxwCboygqSnbQNPK1MwkhtAJeBy7zlXvSfO1coihqG0VRmyiK2gCvAjdauqpUZf5+DQOODyFkhhBygO8BHyU5Z7qpzFyWUbEKSQihGdABWJLUlPq82J7r02rFK4qi0hDCAGAMFe9EeSqKog9CCNfvefwxKt6ddRawGNhBxSsVVZFKzuQ3QGNg8J7VldIoxjvLp4NKzkVJVJmZRFH0UQhhNJAHlANPRlH0hW+n175Ryd+VPwLPhBAWUHGK65dRFK2LLXQaCCG8CJwINAkhLAd+C2RB/M/13jJIkiQpSdLtVKMkSVJsLF6SJElJYvGSJElKEouXJElSkli8JEmSksTiJUmSlCQWL0mSpCT5Pyp4NFAwy6g5AAAAAElFTkSuQmCC\n", - "text/plain": [ - "
    " - ] - }, - "metadata": { - "needs_background": "light" - }, - "output_type": "display_data" + "execution_count": 32, + "id": "f1a60516", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false } - ], -======= + }, "outputs": [], ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 "source": [ "import autograd.numpy as np\n", "from autograd import grad, elementwise_grad\n", @@ -913,8 +4731,8 @@ "# but with number of hidden layers specified by the user.\n", "def deep_neural_network(deep_params, x):\n", " # N_hidden is the number of hidden layers\n", - "\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consists of\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", " # parameters to all the hidden\n", " # layers AND the output layer.\n", "\n", @@ -1063,7 +4881,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "807a375c", + "metadata": { + "editable": true + }, "source": [ "## Example: Population growth\n", "\n", @@ -1073,7 +4894,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d35839bb", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1087,7 +4911,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2991d1fe", + "metadata": { + "editable": true + }, "source": [ "where $g(t)$ is the population density at time $t$, $\\alpha > 0$ the growth rate and $A > 0$ is the maximum population number in the environment.\n", "Also, at $t = 0$ the population has the size $g(0) = g_0$, where $g_0$ is some chosen constant.\n", @@ -1095,8 +4922,16 @@ "In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability\n", "and high execution time (this might be more apparent in the examples solving PDEs),\n", "using a library like TensorFlow is recommended.\n", - "Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method.\n", - "\n", + "Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method." + ] + }, + { + "cell_type": "markdown", + "id": "ee668a71", + "metadata": { + "editable": true + }, + "source": [ "## Setting up the problem\n", "\n", "Here, we will model a population $g(t)$ in an environment having carrying capacity $A$.\n", @@ -1105,7 +4940,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "febf10cc", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1119,12 +4957,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "494194e3", + "metadata": { + "editable": true + }, "source": [ "where $g(0) = g_0$.\n", "\n", - "In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$.\n", - "\n", + "In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$." + ] + }, + { + "cell_type": "markdown", + "id": "5efa7b11", + "metadata": { + "editable": true + }, + "source": [ "## The trial solution\n", "\n", "We will get a slightly different trial solution, as the boundary conditions are different\n", @@ -1142,8 +4991,16 @@ "\n", "$$\n", "g(t) = \\frac{Ag_0}{g_0 + (A - g_0)\\exp(-\\alpha A t)}\n", - "$$\n", - "\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "568131dc", + "metadata": { + "editable": true + }, + "source": [ "## The program using Autograd\n", "\n", "The network will be the similar as for the exponential decay example, but with some small modifications for our problem." @@ -1151,8 +5008,15 @@ }, { "cell_type": "code", - "execution_count": 3, - "metadata": {}, + "execution_count": 33, + "id": "8737e028", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1171,9 +5035,12 @@ " g0 = 1.2\n", " return alpha, A, g0\n", "\n", - "def deep_neural_network(P, x):\n", + "def deep_neural_network(deep_params, x):\n", " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(P) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", + " # parameters to all the hidden\n", + " # layers AND the output layer.\n", "\n", " # Assumes input x being an one-dimensional array\n", " num_values = np.size(x)\n", @@ -1190,7 +5057,7 @@ "\n", " for l in range(N_hidden):\n", " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = P[l]\n", + " w_hidden = deep_params[l]\n", "\n", " # Add a row of ones to include bias\n", " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", @@ -1204,7 +5071,7 @@ " ## Output layer:\n", "\n", " # Get the weights and bias for this layer\n", - " w_output = P[-1]\n", + " w_output = deep_params[-1]\n", "\n", " # Include bias:\n", " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", @@ -1215,6 +5082,8 @@ " return x_output\n", "\n", "\n", + "\n", + "\n", "def cost_function_deep(P, x):\n", "\n", " # Evaluate the trial function with the current parameters P\n", @@ -1322,7 +5191,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0904f64d", + "metadata": { + "editable": true + }, "source": [ "## Using forward Euler to solve the ODE\n", "\n", @@ -1339,7 +5211,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6f3577a8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1351,7 +5226,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "56d4410b", + "metadata": { + "editable": true + }, "source": [ "along with the condition that $g(0) = g_0$.\n", "\n", @@ -1362,7 +5240,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "48d2707e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1375,14 +5256,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "66d99f85", + "metadata": { + "editable": true + }, "source": [ "Now, if $g_i = g(t_i)$ then" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "3c9447d9", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1401,7 +5288,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "724b97f1", + "metadata": { + "editable": true + }, "source": [ "for $i \\geq 1$ and $g_0 = g(t_0) = g(0) = g_0$.\n", "\n", @@ -1411,8 +5301,15 @@ }, { "cell_type": "code", - "execution_count": 4, - "metadata": {}, + "execution_count": 34, + "id": "58b0da70", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "# Assume that all function definitions from the example program using Autograd\n", @@ -1484,7 +5381,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f1230dee", + "metadata": { + "editable": true + }, "source": [ "## Example: Solving the one dimensional Poisson equation\n", "\n", @@ -1493,7 +5393,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ba2c6d0a", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1507,7 +5410,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bab1c7d3", + "metadata": { + "editable": true + }, "source": [ "where $f(x)$ is a given function for $x \\in (0,1)$.\n", "\n", @@ -1516,7 +5422,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "42bfde23", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -1528,12 +5437,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7b3a2504", + "metadata": { + "editable": true + }, "source": [ "This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.\n", "The results from the networks can then be compared to the analytical solution.\n", - "In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks.\n", - "\n", + "In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks." + ] + }, + { + "cell_type": "markdown", + "id": "a419909c", + "metadata": { + "editable": true + }, + "source": [ "## The specific equation to solve for\n", "\n", "Here, the function $g(x)$ to solve for follows the equation" @@ -1541,7 +5461,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "125f8197", + "metadata": { + "editable": true + }, "source": [ "$$\n", "-g''(x) = f(x),\\qquad x \\in (0,1)\n", @@ -1550,14 +5473,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "16376b60", + "metadata": { + "editable": true + }, "source": [ "where $f(x)$ is a given function, along with the chosen conditions" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "044c76ec", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1571,7 +5500,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0ec4860b", + "metadata": { + "editable": true + }, "source": [ "In this example, we consider the case when $f(x) = (3x + x^2)\\exp(x)$.\n", "\n", @@ -1580,7 +5512,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "03e27ec0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_t(x) = x \\cdot (1-x) \\cdot N(P,x)\n", @@ -1589,14 +5524,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "82fdb51f", + "metadata": { + "editable": true + }, "source": [ "The analytical solution for this problem is" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "82e39d0e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g(x) = x(1 - x)\\exp(x)\n", @@ -1605,15 +5546,25 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bf029e6c", + "metadata": { + "editable": true + }, "source": [ "## Solving the equation using Autograd" ] }, { "cell_type": "code", - "execution_count": 5, - "metadata": {}, + "execution_count": 35, + "id": "e10d7641", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1626,7 +5577,10 @@ "\n", "def deep_neural_network(deep_params, x):\n", " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", + " # parameters to all the hidden\n", + " # layers AND the output layer.\n", "\n", " # Assumes input x being an one-dimensional array\n", " num_values = np.size(x)\n", @@ -1667,6 +5621,7 @@ "\n", " return x_output\n", "\n", + "\n", "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", "\n", @@ -1770,7 +5725,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "82891392", + "metadata": { + "editable": true + }, "source": [ "## Comparing with a numerical scheme\n", "\n", @@ -1789,7 +5747,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ad4ef510", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1803,14 +5764,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eb8ab804", + "metadata": { + "editable": true + }, "source": [ "If $x_i = i \\Delta x = x_{i-1} + \\Delta x$ and $g_i = g(x_i)$ for $i = 1,\\dots N_x - 2$ with $N_x$ being the number of values for $x$, ([15](#approx)) becomes" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f9b7b2a0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1822,14 +5789,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6a71c7bb", + "metadata": { + "editable": true + }, "source": [ "Since we know from our problem that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d19780a8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1841,7 +5814,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "00fedc6e", + "metadata": { + "editable": true + }, "source": [ "along with the conditions $g(0) = g(1) = 0$,\n", "the following scheme can be used to find an approximate solution for $g(x)$ numerically:" @@ -1849,7 +5825,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "28005c86", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1866,7 +5845,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d562bb0c", + "metadata": { + "editable": true + }, "source": [ "for $i = 1, \\dots, N_x - 2$ where $g_0 = g_{N_x - 1} = 0$ and $f(x_i) = (3x_i + x_i^2)\\exp(x_i)$, which is given for our specific problem.\n", "\n", @@ -1875,7 +5857,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bdee81e4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{aligned}\n", @@ -1909,10 +5894,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ddf436f5", + "metadata": { + "editable": true + }, + "source": [ + "which makes it possible to solve for the vector $\\boldsymbol{g}$." + ] + }, + { + "cell_type": "markdown", + "id": "66ae2d44", + "metadata": { + "editable": true + }, "source": [ - "which makes it possible to solve for the vector $\\boldsymbol{g}$.\n", - "\n", "## Setting up the code\n", "\n", "We can then compare the result from this numerical scheme with the output from our network using Autograd:" @@ -1920,8 +5916,15 @@ }, { "cell_type": "code", - "execution_count": 6, - "metadata": {}, + "execution_count": 36, + "id": "17f02a24", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -1934,7 +5937,10 @@ "\n", "def deep_neural_network(deep_params, x):\n", " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + " # deep_params is a list, len() should be used\n", + " N_hidden = len(deep_params) - 1 # -1 since params consists of\n", + " # parameters to all the hidden\n", + " # layers AND the output layer.\n", "\n", " # Assumes input x being an one-dimensional array\n", " num_values = np.size(x)\n", @@ -1975,6 +5981,7 @@ "\n", " return x_output\n", "\n", + "\n", "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", "\n", @@ -2118,7 +6125,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "51ee4433", + "metadata": { + "editable": true + }, "source": [ "## Partial Differential Equations\n", "\n", @@ -2132,7 +6142,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1ec16aab", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -2146,10 +6159,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "64fd215d", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "3efab799", + "metadata": { + "editable": true + }, "source": [ - "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.\n", - "\n", "## Type of problem\n", "\n", "The problem our network must solve for, is similar to the ODE case.\n", @@ -2160,7 +6184,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "80e6d77c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2171,14 +6198,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f08a42bd", + "metadata": { + "editable": true + }, "source": [ "where $h_1(x_1,\\dots,x_N)$ is a function that ensures $g_t(x_1,\\dots,x_N)$ satisfies some given conditions.\n", "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.\n", "\n", - "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.\n", - "\n", - "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "af035b50", + "metadata": { + "editable": true + }, + "source": [ "## Network requirements\n", "\n", "The network tries then the minimize the cost function following the\n", @@ -2194,7 +6231,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ee147dfb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C\\left(x_1, \\dots, x_N, P\\right) = \\left( f\\left(x_1, \\, \\dots \\, , x_N, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1}, \\dots , \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_N}, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(x_1,\\dots,x_N) }{\\partial x_N^n} \\right) \\right)^2\n", @@ -2203,7 +6243,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "850e95ed", + "metadata": { + "editable": true + }, "source": [ "## More details\n", "\n", @@ -2212,7 +6255,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "96f9cca4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C\\left(\\boldsymbol{x}, P\\right) = f\\left( \\left( \\boldsymbol{x}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}) }{\\partial x_N^n} \\right) \\right)^2\n", @@ -2221,14 +6267,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "70394cae", + "metadata": { + "editable": true + }, "source": [ "If we also have $M$ different sets of values for $x_1, \\dots, x_N$, that is $\\boldsymbol{x}_i = \\big(x_1^{(i)}, \\dots, x_N^{(i)}\\big)$ for $i = 1,\\dots,M$ being the rows in matrix $X$, the cost function can be generalized into" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d06e6c30", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C\\left(X, P \\right) = \\sum_{i=1}^M f\\left( \\left( \\boldsymbol{x}_i, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}_i) }{\\partial x_N^n} \\right) \\right)^2.\n", @@ -2237,7 +6289,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b4972f88", + "metadata": { + "editable": true + }, "source": [ "## Example: The diffusion equation\n", "\n", @@ -2246,7 +6301,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3d35cbd3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", @@ -2255,14 +6313,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "984bf645", + "metadata": { + "editable": true + }, "source": [ "where a possible choice of conditions are" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9d58d0ec", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2275,10 +6339,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "99cf8f47", + "metadata": { + "editable": true + }, + "source": [ + "with $u(x)$ being some given function." + ] + }, + { + "cell_type": "markdown", + "id": "777ad3a8", + "metadata": { + "editable": true + }, "source": [ - "with $u(x)$ being some given function.\n", - "\n", "## Defining the problem\n", "\n", "For this case, we want to find $g(x,t)$ such that" @@ -2286,7 +6361,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7182b747", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -2300,14 +6378,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3c40d528", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7cb1e15a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2320,16 +6404,25 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5c4bcdb5", + "metadata": { + "editable": true + }, "source": [ "with $u(x) = \\sin(\\pi x)$.\n", "\n", "First, let us set up the deep neural network.\n", "The deep neural network will follow the same structure as discussed in the examples solving the ODEs.\n", - "First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions.\n", - "\n", - "\n", - "\n", + "First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions." + ] + }, + { + "cell_type": "markdown", + "id": "c84ff432", + "metadata": { + "editable": true + }, + "source": [ "## Setting up the network using Autograd\n", "\n", "The only change to do here, is to extend our network such that\n", @@ -2343,8 +6436,15 @@ }, { "cell_type": "code", - "execution_count": 7, - "metadata": {}, + "execution_count": 37, + "id": "ba62ab4c", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "def sigmoid(z):\n", @@ -2358,7 +6458,7 @@ " num_points = np.size(x,1)\n", "\n", " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + " N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", "\n", " # Assume that the input layer does nothing to the input x\n", " x_input = x\n", @@ -2395,7 +6495,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7fd9e6dc", + "metadata": { + "editable": true + }, "source": [ "## Setting up the network using Autograd; The trial solution\n", "\n", @@ -2417,8 +6520,16 @@ "$$\n", "h_1(x,t) = (1-t)\\Big(u(x) - \\big((1-x)u(0) + x u(1)\\big)\\Big) = (1-t)u(x) = (1-t)\\sin(\\pi x)\n", "$$\n", - "since $(0) = u(1) = 0$ and $u(x) = \\sin(\\pi x)$.\n", - "\n", + "since $(0) = u(1) = 0$ and $u(x) = \\sin(\\pi x)$." + ] + }, + { + "cell_type": "markdown", + "id": "6c63c928", + "metadata": { + "editable": true + }, + "source": [ "## Why the jacobian?\n", "\n", "The Jacobian is used because the program must find the derivative of\n", @@ -2442,8 +6553,15 @@ }, { "cell_type": "code", - "execution_count": 8, - "metadata": {}, + "execution_count": 38, + "id": "4192bf3d", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "# Set up the trial function:\n", @@ -2486,7 +6604,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "87f8417d", + "metadata": { + "editable": true + }, "source": [ "## Setting up the network using Autograd; The full program\n", "\n", @@ -2502,15 +6623,21 @@ "Be aware, though, that it is fairly slow for the parameters used.\n", "A better result is possible, but requires more iterations, and thus longer time to complete.\n", "\n", - "\n", "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.\n", "Using TensorFlow results in a much better execution time. Try it!" ] }, { "cell_type": "code", - "execution_count": 9, - "metadata": {}, + "execution_count": 39, + "id": "1572e93b", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -2533,7 +6660,7 @@ " num_points = np.size(x,1)\n", "\n", " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + " N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", "\n", " # Assume that the input layer does nothing to the input x\n", " x_input = x\n", @@ -2676,7 +6803,7 @@ " T,X = np.meshgrid(t,x)\n", "\n", " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", + " ax = fig.add_suplot(projection='3d')\n", " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n", " s = ax.plot_surface(T,X,g_dnn_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n", " ax.set_xlabel('Time $t$')\n", @@ -2684,14 +6811,14 @@ "\n", "\n", " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", + " ax = fig.add_suplot(projection='3d')\n", " ax.set_title('Analytical solution')\n", " s = ax.plot_surface(T,X,G_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n", " ax.set_xlabel('Time $t$')\n", " ax.set_ylabel('Position $x$');\n", "\n", " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", + " ax = fig.add_suplot(projection='3d')\n", " ax.set_title('Difference')\n", " s = ax.plot_surface(T,X,diff_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n", " ax.set_xlabel('Time $t$')\n", @@ -2740,7 +6867,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bf7afd74", + "metadata": { + "editable": true + }, "source": [ "## Example: Solving the wave equation with Neural Networks\n", "\n", @@ -2749,7 +6879,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fdef78b2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2\\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", @@ -2758,7 +6891,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "be570613", + "metadata": { + "editable": true + }, "source": [ "with $c$ being the specified wave speed.\n", "\n", @@ -2767,7 +6903,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9f81e04f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -2781,10 +6920,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "91171d8b", + "metadata": { + "editable": true + }, + "source": [ + "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." + ] + }, + { + "cell_type": "markdown", + "id": "dbbbb8a5", + "metadata": { + "editable": true + }, "source": [ - "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.\n", - "\n", "## The problem to solve for\n", "\n", "The wave equation to solve for, is" @@ -2792,7 +6942,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3f1be58e", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -2806,7 +6959,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d54c4188", + "metadata": { + "editable": true + }, "source": [ "where $c$ is the given wave speed.\n", "The chosen conditions for this equation are" @@ -2814,7 +6970,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "952c58e8", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -2831,11 +6990,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a650bae2", + "metadata": { + "editable": true + }, + "source": [ + "In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$." + ] + }, + { + "cell_type": "markdown", + "id": "9e0b8996", + "metadata": { + "editable": true + }, "source": [ - "In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$.\n", - "\n", - "\n", "## The trial solution\n", "Setting up the network is done in similar matter as for the example of solving the diffusion equation.\n", "The only things we have to change, is the trial solution such that it satisfies the conditions from ([20](#condwave)) and the cost function.\n", @@ -2852,23 +7021,46 @@ "h_1(x,t) = (1-t^2)u(x) + tv(x)\n", "$$\n", "\n", - "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.\n", - "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "0f3f1985", + "metadata": { + "editable": true + }, + "source": [ "## The analytical solution\n", "\n", "The analytical solution for our specific problem, is\n", "\n", "$$\n", "g(x,t) = \\sin(\\pi x)\\cos(\\pi t) - \\sin(\\pi x)\\sin(\\pi t)\n", - "$$\n", - "\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "fbd35329", + "metadata": { + "editable": true + }, + "source": [ "## Solving the wave equation - the full program using Autograd" ] }, { "cell_type": "code", - "execution_count": 10, - "metadata": {}, + "execution_count": 40, + "id": "6ccf9344", + "metadata": { + "collapsed": false, + "editable": true, + "jupyter": { + "outputs_hidden": false + } + }, "outputs": [], "source": [ "import autograd.numpy as np\n", @@ -2925,7 +7117,7 @@ " num_points = np.size(x,1)\n", "\n", " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", + " N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", "\n", " # Assume that the input layer does nothing to the input x\n", " x_input = x\n", @@ -3030,7 +7222,7 @@ " T,X = np.meshgrid(t,x)\n", "\n", " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", + " ax = fig.add_suplot(projection='3d')\n", " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n", " s = ax.plot_surface(T,X,res,linewidth=0,antialiased=False,cmap=cm.viridis)\n", " ax.set_xlabel('Time $t$')\n", @@ -3038,7 +7230,7 @@ "\n", "\n", " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", + " ax = fig.add_suplot(projection='3d')\n", " ax.set_title('Analytical solution')\n", " s = ax.plot_surface(T,X,res_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n", " ax.set_xlabel('Time $t$')\n", @@ -3046,7 +7238,7 @@ "\n", "\n", " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", + " ax = fig.add_suplot(projection='3d')\n", " ax.set_title('Difference')\n", " s = ax.plot_surface(T,X,diff,linewidth=0,antialiased=False,cmap=cm.viridis)\n", " ax.set_xlabel('Time $t$')\n", @@ -3095,7 +7287,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "988e09cf", + "metadata": { + "editable": true + }, "source": [ "## Resources on differential equations and deep learning\n", "\n", @@ -3105,1635 +7300,13 @@ "\n", "3. [Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener](http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf)\n", "\n", - "4. [Introduction to Partial Differential Equations by A. Tveito, R. Winther](https://www.springer.com/us/book/9783540225515)\n", - "\n", - "## Friday, Principal Component Analysis\n", - "\n", - "[Overview video](https://www.youtube.com/watch?v=fkf4IBRSeEc&ab_channel=SteveBrunton)\n", - "\n", - "## Basic ideas of the Principal Component Analysis (PCA)\n", - "\n", - "The principal component analysis deals with the problem of fitting a\n", - "low-dimensional affine subspace $S$ of dimension $d$ much smaller than\n", -<<<<<<< HEAD - "the totaldimension $D$ of the problem at hand (our data\n", - "set). Mathematically it can be formulated as a statistical problem or\n", - "a geometric problem. In our discussion of the theorem for the\n", - "classical PCA, we will stay with a statistical approach. This is also\n", - "what set the scene historically which for the PCA.\n", -======= - "the total dimension $D$ of the problem at hand (our data\n", - "set). Mathematically it can be formulated as a statistical problem or\n", - "a geometric problem. In our discussion of the theorem for the\n", - "classical PCA, we will stay with a statistical approach. \n", - "Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable.\n", ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "\n", - "We have a data set defined by a design/feature matrix $\\boldsymbol{X}$ (see below for its definition) \n", - "* Each data point is determined by $p$ extrinsic (measurement) variables\n", - "\n", - "* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?\n", - "\n", - "* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n", - "\n", -<<<<<<< HEAD -======= - "A good read is for example [Vidal, Ma and Sastry](https://www.springer.com/gp/book/9780387878102).\n", - "\n", - "\n", ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "## Introducing the Covariance and Correlation functions\n", - "\n", - "Before we discuss the PCA theorem, we need to remind ourselves about\n", - "the definition of the covariance and the correlation function. These are quantities \n", - "\n", - "Suppose we have defined two vectors\n", - "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where for example" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With this definition and recalling that the variance is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we can rewrite the covariance matrix as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The covariance takes values between zero and infinity and may thus\n", - "lead to problems with loss of numerical precision for particularly\n", - "large values. It is common to scale the covariance matrix by\n", - "introducing instead the correlation matrix defined via the so-called\n", - "correlation function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n", - "\\in [-1,1]$. This avoids eventual problems with too large values. We\n", - "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n", - "and $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the above example this is the function we constructed using **pandas**.\n", - "\n", - "## Correlation Function and Design/Feature Matrix\n", - "\n", - "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n", - "we defined the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", - "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", - "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", - "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", - "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", - "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n", - "entries $n$ being the row elements.\n", - "We can rewrite the design/feature matrix in terms of its column vectors as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with a given vector" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With these definitions, we can now rewrite our $2\\times 2$\n", - "correaltion/covariance matrix in terms of a moe general design/feature\n", - "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n", - "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the correlation matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Covariance Matrix Examples\n", - "\n", - "\n", - "The Numpy function **np.cov** calculates the covariance elements using\n", - "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n", - "the exact mean values. The following simple function uses the\n", - "**np.vstack** function which takes each vector of dimension $1\\times n$\n", - "and produces a $2\\times n$ matrix $\\boldsymbol{W}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n", - " x_1 & y_1 \\\\\n", - " x_2 & y_2\\\\\n", - " \\dots & \\dots \\\\\n", - " x_{n-2} & y_{n-2}\\\\\n", - " x_{n-1} & y_{n-1} & \n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which in turn is converted into into the $2\\times 2$ covariance matrix\n", - "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", - "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n", - "function **np.mean(x)**. We can also extract the eigenvalues of the\n", - "covariance matrix through the **np.linalg.eig()** function." - ] - }, - { - "cell_type": "code", -<<<<<<< HEAD - "execution_count": 11, - "metadata": {}, - "outputs": [], -======= - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "-0.0295549375800962\n", - "3.790157415516731\n", - "[[ 1.14945017 3.28385419]\n", - " [ 3.28385419 10.22579788]]\n" - ] - } - ], ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "n = 100\n", - "x = np.random.normal(size=n)\n", - "print(np.mean(x))\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "print(np.mean(y))\n", - "W = np.vstack((x, y))\n", - "C = np.cov(W)\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Correlation Matrix\n", - "\n", - "The previous example can be converted into the correlation matrix by\n", - "simply scaling the matrix elements with the variances. We should also\n", - "subtract the mean values for each column. This leads to the following\n", - "code which sets up the correlations matrix for the previous example in\n", - "a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)." - ] - }, - { - "cell_type": "code", -<<<<<<< HEAD - "execution_count": 12, - "metadata": {}, - "outputs": [], -======= - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0.08073726712724406\n", - "1.6145539590295142\n", - "[[1. 0.63404481]\n", - " [0.63404481 1. ]]\n" - ] - } - ], ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "source": [ - "import numpy as np\n", - "n = 100\n", - "# define two vectors \n", - "x = np.random.random(size=n)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "#scaling the x and y vectors \n", - "x = x - np.mean(x)\n", - "y = y - np.mean(y)\n", - "variance_x = np.sum(x@x)/n\n", - "variance_y = np.sum(y@y)/n\n", - "print(variance_x)\n", - "print(variance_y)\n", - "cov_xy = np.sum(x@y)/n\n", - "cov_xx = np.sum(x@x)/n\n", - "cov_yy = np.sum(y@y)/n\n", - "C = np.zeros((2,2))\n", - "C[0,0]= cov_xx/variance_x\n", - "C[1,1]= cov_yy/variance_y\n", - "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n", - "C[1,0]= C[0,1]\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see that the matrix elements along the diagonal are one as they\n", - "should be and that the matrix is symmetric. Furthermore, diagonalizing\n", - "this matrix we easily see that it is a positive definite matrix.\n", - "\n", - "The above procedure with **numpy** can be made more compact if we use **pandas**.\n", - "\n", - "## Correlation Matrix with Pandas\n", - "\n", - "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code" - ] - }, - { - "cell_type": "code", -<<<<<<< HEAD - "execution_count": 13, - "metadata": {}, - "outputs": [], -======= - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[[ 0.01396941 0.49068974]\n", - " [ 0.54918099 2.04838299]\n", - " [-0.35991553 -1.16529785]\n", - " [ 0.74909071 1.11467729]\n", - " [ 1.10998316 4.0040917 ]\n", - " [-0.98934642 -2.16772616]\n", - " [ 0.25009971 0.75283979]\n", - " [-0.57918262 -1.70870953]\n", - " [-0.98545332 -3.90181134]\n", - " [ 0.24157391 0.53286336]]\n", - " 0 1\n", - "0 0.013969 0.490690\n", - "1 0.549181 2.048383\n", - "2 -0.359916 -1.165298\n", - "3 0.749091 1.114677\n", - "4 1.109983 4.004092\n", - "5 -0.989346 -2.167726\n", - "6 0.250100 0.752840\n", - "7 -0.579183 -1.708710\n", - "8 -0.985453 -3.901811\n", - "9 0.241574 0.532863\n", - " 0 1\n", - "0 1.000000 0.959994\n", - "1 0.959994 1.000000\n" - ] - } - ], ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "n = 10\n", - "x = np.random.normal(size=n)\n", - "x = x - np.mean(x)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "y = y - np.mean(y)\n", - "X = (np.vstack((x, y))).T\n", - "print(X)\n", - "Xpd = pd.DataFrame(X)\n", - "print(Xpd)\n", - "correlation_matrix = Xpd.corr()\n", - "print(correlation_matrix)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We expand this model to the Franke function discussed above.\n", - "\n", - "## Correlation Matrix with Pandas and the Franke function" - ] - }, - { - "cell_type": "code", -<<<<<<< HEAD - "execution_count": 14, - "metadata": {}, - "outputs": [], -======= - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " 0 1 2 3 4 5 6 7 \\\n", - "0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 \n", - "1 0.0 0.072184 0.069825 0.069428 0.071162 0.072822 0.060421 0.061903 \n", - "2 0.0 0.069825 0.069297 0.065490 0.068155 0.070919 0.055665 0.057749 \n", - "3 0.0 0.069428 0.065490 0.071945 0.072269 0.072413 0.065947 0.066493 \n", - "4 0.0 0.071162 0.068155 0.072269 0.073368 0.074365 0.065102 0.066207 \n", - "5 0.0 0.072822 0.070919 0.072413 0.074365 0.076313 0.064012 0.065724 \n", - "6 0.0 0.060421 0.055665 0.065947 0.065102 0.064012 0.062745 0.062435 \n", - "7 0.0 0.061903 0.057749 0.066493 0.066207 0.065724 0.062435 0.062545 \n", - "8 0.0 0.063660 0.060176 0.067220 0.067552 0.067741 0.062209 0.062780 \n", - "9 0.0 0.065675 0.062949 0.068101 0.069119 0.070057 0.062036 0.063114 \n", - "10 0.0 0.052443 0.047291 0.059402 0.057799 0.055912 0.058081 0.057183 \n", - "11 0.0 0.053341 0.048621 0.059668 0.058469 0.057019 0.057756 0.057169 \n", - "12 0.0 0.054483 0.050229 0.060122 0.059366 0.058394 0.057550 0.057302 \n", - "13 0.0 0.055889 0.052145 0.060775 0.060506 0.060062 0.057464 0.057588 \n", - "14 0.0 0.057577 0.054396 0.061634 0.061905 0.062047 0.057497 0.058031 \n", - "\n", - " 8 9 10 11 12 13 14 \n", - "0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 \n", - "1 0.063660 0.065675 0.052443 0.053341 0.054483 0.055889 0.057577 \n", - "2 0.060176 0.062949 0.047291 0.048621 0.050229 0.052145 0.054396 \n", - "3 0.067220 0.068101 0.059402 0.059668 0.060122 0.060775 0.061634 \n", - "4 0.067552 0.069119 0.057799 0.058469 0.059366 0.060506 0.061905 \n", - "5 0.067741 0.070057 0.055912 0.057019 0.058394 0.060062 0.062047 \n", - "6 0.062209 0.062036 0.058081 0.057756 0.057550 0.057464 0.057497 \n", - "7 0.062780 0.063114 0.057183 0.057169 0.057302 0.057588 0.058031 \n", - "8 0.063524 0.064419 0.056301 0.056626 0.057130 0.057825 0.058718 \n", - "9 0.064419 0.065935 0.055400 0.056095 0.057007 0.058150 0.059542 \n", - "10 0.056301 0.055400 0.054868 0.054129 0.053455 0.052843 0.052283 \n", - "11 0.056626 0.056095 0.054129 0.053624 0.053205 0.052870 0.052614 \n", - "12 0.057130 0.057007 0.053455 0.053205 0.053063 0.053031 0.053108 \n", - "13 0.057825 0.058150 0.052843 0.052870 0.053031 0.053332 0.053775 \n", - "14 0.058718 0.059542 0.052283 0.052614 0.053108 0.053775 0.054625 \n" - ] - } - ], ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "\n", - "\n", - "def FrankeFunction(x,y):\n", - "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - "\treturn term1 + term2 + term3 + term4\n", - "\n", - "\n", - "def create_X(x, y, n ):\n", - "\tif len(x.shape) > 1:\n", - "\t\tx = np.ravel(x)\n", - "\t\ty = np.ravel(y)\n", - "\n", - "\tN = len(x)\n", - "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", - "\tX = np.ones((N,l))\n", - "\n", - "\tfor i in range(1,n+1):\n", - "\t\tq = int((i)*(i+1)/2)\n", - "\t\tfor k in range(i+1):\n", - "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", - "\n", - "\treturn X\n", - "\n", - "\n", - "# Making meshgrid of datapoints and compute Franke's function\n", - "n = 4\n", - "N = 100\n", - "x = np.sort(np.random.uniform(0, 1, N))\n", - "y = np.sort(np.random.uniform(0, 1, N))\n", - "z = FrankeFunction(x, y)\n", - "X = create_X(x, y, n=n) \n", - "\n", - "Xpd = pd.DataFrame(X)\n", - "# subtract the mean values and set up the covariance matrix\n", - "Xpd = Xpd - Xpd.mean()\n", - "covariance_matrix = Xpd.cov()\n", - "print(covariance_matrix)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We note here that the covariance is zero for the first rows and\n", - "columns since all matrix elements in the design matrix were set to one\n", -<<<<<<< HEAD - "(we are fitting the function in terms of a polynomial of degree $n$).\n", - "\n", - "This means that the variance for these elements will be zero and will\n", - "cause problems when we set up the correlation matrix. We can simply\n", - "drop these elements and construct a correlation\n", - "matrix without these elements. \n", -======= - "(we are fitting the function in terms of a polynomial of degree $n$). We would however not include the intercept\n", - "and wee can simply\n", - "drop these elements and construct a correlation\n", - "matrix without them. \n", ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "\n", - "\n", - "## Rewriting the Covariance and/or Correlation Matrix\n", - "\n", - "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T= \\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{00} & x_{01}\\\\\n", - "x_{10} & x_{11}\\\\\n", - "\\end{bmatrix}=\\begin{bmatrix}\n", - "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we then compute the expectation value" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T=\\begin{bmatrix}\n", - "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n", - "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is just" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n", - "\n", - "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n", - "\n", - "\n", - "## Towards the PCA theorem\n", - "\n", - "We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T= \\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\\boldsymbol{S}$.\n", - "These matrices are defined as $\\boldsymbol{S}\\in {\\mathbb{R}}^{p\\times p}$ and obey the orthogonality requirements $\\boldsymbol{S}\\boldsymbol{S}^T=\\boldsymbol{S}^T\\boldsymbol{S}=\\boldsymbol{I}$. The matrix can be written out in terms of the column vectors $\\boldsymbol{s}_i$ as $\\boldsymbol{S}=[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$ and $\\boldsymbol{s}_i \\in {\\mathbb{R}}^{p}$.\n", - "\n", - "Assume also that there is a transformation $\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T=\\boldsymbol{C}[\\boldsymbol{y}]$ such that the new matrix $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal with elements $[\\lambda_0,\\lambda_1,\\lambda_2,\\dots,\\lambda_{p-1}]$. \n", - "\n", - "That is we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{y}] = \\mathbb{E}[\\boldsymbol{S}\\boldsymbol{X}\\boldsymbol{X}^T\\boldsymbol{S}^T]=\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}^T$ from the left we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{S}^T_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is\n", - "$\\lambda_0 > \\lambda_1 > \\dots > \\lambda_{p-1}$. \n", - "\n", - "\n", - "The eigenvalues tell us then how much we need to stretch the\n", - "corresponding eigenvectors. Dimensions with large eigenvalues have\n", - "thus large variations (large variance) and define therefore useful\n", - "dimensions. The data points are more spread out in the direction of\n", - "these eigenvectors. Smaller eigenvalues mean on the other hand that\n", - "the corresponding eigenvectors are shrunk accordingly and the data\n", - "points are tightly bunched together and there is not much variation in\n", - "these specific directions. Hopefully then we could leave it out\n", - "dimensions where the eigenvalues are very small. If $p$ is very large,\n", - "we could then aim at reducing $p$ to $l << p$ and handle only $l$\n", - "features/predictors.\n", - "\n", - "## The Algorithm before theorem\n", - "\n", - "Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. \n", - "* Set up the datapoints for the design/feature matrix $\\boldsymbol{X}$ with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ referring to the column numbers and the entries $n$ being the row elements." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", - "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", - "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", - "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", - "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", - "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Center the data by subtracting the mean value for each column. This leads to a new matrix $\\boldsymbol{X}\\rightarrow \\overline{\\boldsymbol{X}}$.\n", - "\n", - "* Compute then the covariance/correlation matrix $\\mathbb{E}[\\overline{\\boldsymbol{X}}\\overline{\\boldsymbol{X}}^T]$.\n", - "\n", - "* Find the eigenpairs of $\\boldsymbol{C}$ with eigenvalues $[\\lambda_0,\\lambda_1,\\dots,\\lambda_{p-1}]$ and eigenvectors $[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$.\n", - "\n", - "* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.\n", - "\n", - "* Keep only those $l$ eigenvalues larger than a selected threshold value, discarding thus $p-l$ features since we expect small variations in the data here.\n", - "\n", - "## Writing our own PCA code\n", - "\n", - "We will use a simple example first with two-dimensional data\n", - "drawn from a multivariate normal distribution with the following mean and covariance matrix:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n", - "2 & 2\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note that the mean refers to each column of data. \n", - "We will generate $n = 1000$ points $X = \\{ x_1, \\ldots, x_N \\}$ from\n", - "this distribution, and store them in the $1000 \\times 2$ matrix $\\boldsymbol{X}$.\n", - "\n", - "The following Python code aids in setting up the data and writing out the design matrix.\n", - "Note that the function **multivariate** returns also the covariance discussed above and that it is defined by dividing by $n-1$ instead of $n$." - ] - }, - { - "cell_type": "code", -<<<<<<< HEAD - "execution_count": 15, -======= - "execution_count": 5, ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from IPython.display import display\n", - "n = 10000\n", - "mean = (-1, 2)\n", - "cov = [[4, 2], [2, 2]]\n", - "X = np.random.multivariate_normal(mean, cov, n)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we are going to implement the PCA algorithm. We will break it down into various substeps.\n", - "\n", - "### Compute the sample mean and center the data\n", - "\n", - "The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\bar{x}_i = x_i - \\mu_n.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When you are done with these steps, print out $\\mu_n$ to verify it is\n", - "close to $\\mu$ and plot your mean centered data to verify it is\n", - "centered at the origin! Compare your code with the functionality from **Scikit-Learn** discussed above.\n", - "The following code elements perform these operations using **pandas** or using our own functionality for doing so. The latter, using **numpy** is rather simple through the **mean()** function." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [], - "source": [ - "df = pd.DataFrame(X)\n", - "# Pandas does the centering for us\n", - "df = df -df.mean()\n", - "# we center it ourselves\n", - "X_centered = X - X.mean(axis=0)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Alternatively, we could use the functions we discussed\n", - "earlier for scaling the data set. That is, we could have used the\n", - "**StandardScaler** function in **Scikit-Learn**, a function which ensures\n", - "that for each feature/predictor we study the mean value is zero and\n", - "the variance is one (every column in the design/feature matrix). You\n", - "would then not get the same results, since we divide by the\n", - "variance. The diagonal covariance matrix elements will then be one,\n", - "while the non-diagonal ones need to be divided by $2\\sqrt{2}$ for our\n", - "specific case.\n", - "\n", - "### Compute the sample covariance\n", - "\n", - "Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\Sigma_n = \\frac{1}{n-1} \\sum_{i=1}^n \\bar{x}_i^T \\bar{x}_i = \\frac{1}{n-1} \\sum_{i=1}^n (x_i - \\mu_n)^T (x_i - \\mu_n)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the data points $x_i \\in \\mathbb{R}^p$ (here in this example $p = 2$) are column vectors and $x^T$ is the transpose of $x$.\n", - "We can write our own code or simply use either the functionaly of **numpy** or that of **pandas**, as follows" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [], - "source": [ - "print(df.cov())\n", - "print(np.cov(X_centered.T))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note that the way we define the covariance matrix here has a factor $n-1$ instead of $n$. This is included in the **cov()** function by **numpy** and **pandas**. \n", - "Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific $2\\times 2$ covariance matrix." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [], - "source": [ - "# extract the relevant columns from the centered design matrix of dim n x 2\n", - "x = X_centered[:,0]\n", - "y = X_centered[:,1]\n", - "Cov = np.zeros((2,2))\n", - "Cov[0,1] = np.sum(x.T@y)/(n-1.0)\n", - "Cov[0,0] = np.sum(x.T@x)/(n-1.0)\n", - "Cov[1,1] = np.sum(y.T@y)/(n-1.0)\n", - "Cov[1,0]= Cov[0,1]\n", - "print(\"Centered covariance using own code\")\n", - "print(Cov)\n", - "plt.plot(x, y, 'x')\n", - "plt.axis('equal')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Depending on the number of points $n$, we will get results that are close to the covariance values defined above.\n", - "The plot shows how the data are clustered around a line with slope close to one. Is this expected?\n", - "\n", - "### Diagonalize the sample covariance matrix to obtain the principal components\n", - "\n", - "Now we are ready to solve for the principal components! To do so we\n", - "diagonalize the sample covariance matrix $\\Sigma$. We can use the\n", - "function **np.linalg.eig** to do so. It will return the eigenvalues and\n", - "eigenvectors of $\\Sigma$. Once we have these we can perform the \n", - "following tasks:\n", - "\n", - "* We compute the percentage of the total variance captured by the first principal component\n", - "\n", - "* We plot the mean centered data and lines along the first and second principal components\n", - "\n", - "* Then we project the mean centered data onto the first and second principal components, and plot the projected data. \n", - "\n", - "* Finally, we approximate the data as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $v_0$ is the first principal component. \n", - "\n", - "Collecting all these steps we can write our own PCA function and\n", - "compare this with the functionality included in **Scikit-Learn**. \n", - "\n", - "The code here outlines some of the elements we could include in the\n", - "analysis. Feel free to extend upon this in order to address the above\n", - "questions." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": {}, - "outputs": [], - "source": [ - "# diagonalize and obtain eigenvalues, not necessarily sorted\n", - "EigValues, EigVectors = np.linalg.eig(Cov)\n", - "# sort eigenvectors and eigenvalues\n", - "#permute = EigValues.argsort()\n", - "#EigValues = EigValues[permute]\n", - "#EigVectors = EigVectors[:,permute]\n", - "print(\"Eigenvalues of Covariance matrix\")\n", - "for i in range(2):\n", - " print(EigValues[i])\n", - "FirstEigvector = EigVectors[:,0]\n", - "SecondEigvector = EigVectors[:,1]\n", - "print(\"First eigenvector\")\n", - "print(FirstEigvector)\n", - "print(\"Second eigenvector\")\n", - "print(SecondEigvector)\n", - "#thereafter we do a PCA with Scikit-learn\n", - "from sklearn.decomposition import PCA\n", - "pca = PCA(n_components = 2)\n", - "X2Dsl = pca.fit_transform(X)\n", - "print(\"Eigenvector of largest eigenvalue\")\n", - "print(pca.components_.T[:, 0])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code does not contain all the above elements, but it shows how we can use **Scikit-Learn** to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? \n", - "\n", - "## Classical PCA Theorem\n", - "\n", - "We assume now that we have a design matrix $\\boldsymbol{X}$ which has been\n", - "centered as discussed above. For the sake of simplicity we skip the\n", - "overline symbol. The matrix is defined in terms of the various column\n", - "vectors $[\\boldsymbol{x}_0,\\boldsymbol{x}_1,\\dots, \\boldsymbol{x}_{p-1}]$ each with dimension\n", - "$\\boldsymbol{x}\\in {\\mathbb{R}}^{n}$.\n", - "\n", - "We assume also that we have an orthogonal transformation $\\boldsymbol{W}\\in {\\mathbb{R}}^{p\\times p}$. We define the reconstruction error (which is similar to the mean squared error we have seen before) as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "J(\\boldsymbol{W},\\boldsymbol{Z}) = \\frac{1}{n}\\sum_i (\\boldsymbol{x}_i - \\overline{\\boldsymbol{x}}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\overline{\\boldsymbol{x}}_i = \\boldsymbol{W}\\boldsymbol{z}_i$, where $\\boldsymbol{z}_i$ is a row vector with dimension ${\\mathbb{R}}^{n}$ of the matrix\n", - "$\\boldsymbol{Z}\\in{\\mathbb{R}}^{p\\times n}$. When doing PCA we want to reduce this dimensionality. \n", - "\n", - "The PCA theorem states that minimizing the above reconstruction error\n", - "corresponds to setting $\\boldsymbol{W}=\\boldsymbol{S}$, the orthogonal matrix which\n", - "diagonalizes the empirical covariance(correlation) matrix. The optimal\n", - "low-dimensional encoding of the data is then given by a set of vectors\n", - "$\\boldsymbol{z}_i$ with at most $l$ vectors, with $l << p$, defined by the\n", - "orthogonal projection of the data onto the columns spanned by the\n", - "eigenvectors of the covariance(correlations matrix).\n", - "\n", -<<<<<<< HEAD - "The proof which follows will be updated by mid January 2020.\n", -======= - "\n", ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "\n", - "## Proof of the PCA Theorem\n", - "\n", - "To show the PCA theorem let us start with the assumption that there is one vector $\\boldsymbol{w}_0$ which corresponds to a solution which minimized the reconstruction error $J$. This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of $\\boldsymbol{w}_0$ and $\\boldsymbol{z}_0$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "J(\\boldsymbol{w}_0,\\boldsymbol{z}_0)= \\frac{1}{n}\\sum_i (\\boldsymbol{x}_i - z_{i0}\\boldsymbol{w}_0)^2=\\frac{1}{n}\\sum_i (\\boldsymbol{x}_i^T\\boldsymbol{x}_i - 2z_{i0}\\boldsymbol{w}_0^T\\boldsymbol{x}_i+z_{i0}^2\\boldsymbol{w}_0^T\\boldsymbol{w}_0),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which we can rewrite due to the orthogonality of $\\boldsymbol{w}_i$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "J(\\boldsymbol{w}_0,\\boldsymbol{z}_0)=\\frac{1}{n}\\sum_i (\\boldsymbol{x}_i^T\\boldsymbol{x}_i - 2z_{i0}\\boldsymbol{w}_0^T\\boldsymbol{x}_i+z_{i0}^2).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Minimizing $J$ with respect to the unknown parameters $z_{0i}$ we obtain that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "z_{i0}=\\boldsymbol{w}_0^T\\boldsymbol{x}_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the vectors on the rhs are known. \n", - "\n", - "\n", - "## PCA Proof continued\n", - "\n", - "We have now found the unknown parameters $z_{i0}$. These correspond to the projected coordinates and we can write" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "J(\\boldsymbol{w}_0)= \\frac{1}{p}\\sum_i (\\boldsymbol{x}_i^T\\boldsymbol{x}_i - z_{i0}^2)=\\mathrm{const}-\\frac{1}{n}\\sum_i z_{i0}^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can show that the variance of the projected coordinates defined by $\\boldsymbol{w}_0^T\\boldsymbol{x}_i$ are given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}[\\boldsymbol{w}_0^T\\boldsymbol{x}_i] = \\frac{1}{n}\\sum_i z_{i0}^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "since the expectation value of" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}[\\boldsymbol{w}_0^T\\boldsymbol{x}_i] = \\mathbb{E}[z_{i0}]= \\boldsymbol{w}_0^T\\mathbb{E}[\\boldsymbol{x}_i]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have used the fact that our data are centered.\n", - "\n", - "Recalling our definition of the covariance as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T=\\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have thus that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}[\\boldsymbol{w}_0^T\\boldsymbol{x}_i] = \\frac{1}{n}\\sum_i z_{i0}^2=\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We are almost there, we have obtained a relation between minimizing\n", - "the reconstruction error and the variance and the covariance\n", - "matrix. Minimizing the error is equivalent to maximizing the variance\n", - "of the projected data.\n", - "\n", - "## The final step\n", - "\n", - "We could trivially maximize the variance of the projection (and\n", - "thereby minimize the error in the reconstruction function) by letting\n", - "the norm-2 of $\\boldsymbol{w}_0$ go to infinity. However, this norm since we\n", - "want the matrix $\\boldsymbol{W}$ to be an orthogonal matrix, is constrained by\n", - "$\\vert\\vert \\boldsymbol{w}_0 \\vert\\vert_2^2=1$. Imposing this condition via a\n", - "Lagrange multiplier we can then in turn maximize" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "J(\\boldsymbol{w}_0)= \\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0+\\lambda_0(1-\\boldsymbol{w}_0^T\\boldsymbol{w}_0).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial J(\\boldsymbol{w}_0)}{\\partial \\boldsymbol{w}_0}= 2\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0-2\\lambda_0\\boldsymbol{w}_0=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "meaning that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix**! If we left multiply with $\\boldsymbol{w}_0^T$ we have the variance of the projected data is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we want to maximize the variance (minimize the construction error)\n", - "we simply pick the eigenvector of the covariance matrix with the\n", - "largest eigenvalue. This establishes the link between the minimization\n", - "of the reconstruction function $J$ in terms of an orthogonal matrix\n", - "and the maximization of the variance and thereby the covariance of our\n", - "observations encoded in the design/feature matrix $\\boldsymbol{X}$.\n", - "\n", - "The proof\n", - "for the other eigenvectors $\\boldsymbol{w}_1,\\boldsymbol{w}_2,\\dots$ can be\n", - "established by applying the above arguments and using the fact that\n", - "our basis of eigenvectors is orthogonal, see [Murphy chapter\n", - "12.2](https://mitpress.mit.edu/books/machine-learning-1). The\n", - "discussion in chapter 12.2 of Murphy's text has also a nice link with\n", - "the Singular Value Decomposition theorem. For categorical data, see\n", - "chapter 12.4 and discussion therein.\n", - "\n", -<<<<<<< HEAD - "Additional part of the proof for the other eigenvectors will be added by mid January 2020.\n", - "\n", - "## Geometric Interpretation and link with Singular Value Decomposition\n", - "\n", - "This material will be added by mid January 2020.\n", -======= - "For more details, see for example [Vidal, Ma and Sastry, chapter 2](https://www.springer.com/gp/book/9780387878102).\n", - "\n", - "## Geometric Interpretation and link with Singular Value Decomposition\n", - "\n", - "For a detailed demonstration of the geometric interpretation, see [Vidal, Ma and Sastry, section 2.1.2](https://www.springer.com/gp/book/9780387878102).\n", ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 - "\n", - "\n", - "## Principal Component Analysis\n", - "\n", - "Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.\n", - "First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.\n", - "\n", - "The following Python code uses NumPy’s **svd()** function to obtain all the principal components of the\n", - "training set, then extracts the first two principal components. First we center the data using either **pandas** or our own code" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "from IPython.display import display\n", - "np.random.seed(100)\n", - "# setting up a 10 x 5 vanilla matrix \n", - "rows = 10\n", - "cols = 5\n", - "X = np.random.randn(rows,cols)\n", - "df = pd.DataFrame(X)\n", - "# Pandas does the centering for us\n", - "df = df -df.mean()\n", - "display(df)\n", - "\n", - "# we center it ourselves\n", - "X_centered = X - X.mean(axis=0)\n", - "# Then check the difference between pandas and our own set up\n", - "print(X_centered-df)\n", - "#Now we do an SVD\n", - "U, s, V = np.linalg.svd(X_centered)\n", - "c1 = V.T[:, 0]\n", - "c2 = V.T[:, 1]\n", - "W2 = V.T[:, :2]\n", - "X2D = X_centered.dot(W2)\n", - "print(X2D)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering\n", - "the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t\n", - "forget to center the data first.\n", - "\n", - "Once you have identified all the principal components, you can reduce the dimensionality of the dataset\n", - "down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.\n", - "Selecting this hyperplane ensures that the projection will preserve as much variance as possible." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [], - "source": [ - "W2 = V.T[:, :2]\n", - "X2D = X_centered.dot(W2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## PCA and scikit-learn\n", - "\n", - "Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The\n", - "following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note\n", - "that it automatically takes care of centering the data):" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": {}, - "outputs": [], - "source": [ - "#thereafter we do a PCA with Scikit-learn\n", - "from sklearn.decomposition import PCA\n", - "pca = PCA(n_components = 2)\n", - "X2D = pca.fit_transform(X)\n", - "print(X2D)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "After fitting the PCA transformer to the dataset, you can access the principal components using the\n", - "components variable (note that it contains the PCs as horizontal vectors, so, for example, the first\n", - "principal component is equal to" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": {}, - "outputs": [], - "source": [ - "pca.components_.T[:, 0]." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Another very useful piece of information is the explained variance ratio of each principal component,\n", - "available via the $explained\\_variance\\_ratio$ variable. It indicates the proportion of the dataset’s\n", - "variance that lies along the axis of each principal component. \n", - "\n", - "## Back to the Cancer Data\n", - "We can now repeat the above but applied to real data, in this case our breast cancer data.\n", - "Here we compute performance scores on the training data using logistic regression." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": {}, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "\n", - "logreg = LogisticRegression()\n", - "logreg.fit(X_train, y_train)\n", - "print(\"Train set accuracy from Logistic Regression: {:.2f}\".format(logreg.score(X_train,y_train)))\n", - "# We scale the data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "# Then perform again a log reg fit\n", - "logreg.fit(X_train_scaled, y_train)\n", - "print(\"Train set accuracy scaled data: {:.2f}\".format(logreg.score(X_train_scaled,y_train)))\n", - "#thereafter we do a PCA with Scikit-learn\n", - "from sklearn.decomposition import PCA\n", - "pca = PCA(n_components = 2)\n", - "X2D_train = pca.fit_transform(X_train_scaled)\n", - "# and finally compute the log reg fit and the score on the training data\t\n", - "logreg.fit(X2D_train,y_train)\n", - "print(\"Train set accuracy scaled and PCA data: {:.2f}\".format(logreg.score(X2D_train,y_train)))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. \n", - "\n", - "## More on the PCA\n", - "\n", - "Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to\n", - "choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).\n", - "Unless, of course, you are reducing dimensionality for data visualization — in that case you will\n", - "generally want to reduce the dimensionality down to 2 or 3.\n", - "The following code computes PCA without reducing dimensionality, then computes the minimum number\n", - "of dimensions required to preserve 95% of the training set’s variance:" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [], - "source": [ - "pca = PCA()\n", - "pca.fit(X)\n", - "cumsum = np.cumsum(pca.explained_variance_ratio_)\n", - "d = np.argmax(cumsum >= 0.95) + 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You could then set $n\\_components=d$ and run PCA again. However, there is a much better option: instead\n", - "of specifying the number of principal components you want to preserve, you can set $n\\_components$ to be\n", - "a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": {}, - "outputs": [], - "source": [ - "pca = PCA(n_components=0.95)\n", - "X_reduced = pca.fit_transform(X)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Incremental PCA\n", - "\n", - "One problem with the preceding implementation of PCA is that it requires the whole training set to fit in\n", - "memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n", - "been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n", - "at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n", - "instances arrive).\n", - "\n", - "## Randomized PCA\n", - "\n", - "Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic\n", - "algorithm that quickly finds an approximation of the first d principal components. Its computational\n", - "complexity is $O(m \\times d^2)+O(d^3)$, instead of $O(m \\times n^2) + O(n^3)$, so it is dramatically faster than the\n", - "previous algorithms when $d$ is much smaller than $n$.\n", - "\n", - "\n", - "\n", - "\n", - "## Kernel PCA\n", - "\n", - "The kernel trick is a mathematical technique that implicitly maps instances into a\n", - "very high-dimensional space (called the feature space), enabling nonlinear classification and regression\n", - "with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature\n", - "space corresponds to a complex nonlinear decision boundary in the original space.\n", - "It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear\n", - "projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at\n", - "preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a\n", - "twisted manifold.\n", - "For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.decomposition import KernelPCA\n", - "rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", gamma=0.04)\n", - "X_reduced = rbf_pca.fit_transform(X)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LLE\n", - "\n", - "Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction\n", - "(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous\n", - "algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its\n", - "closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where\n", - "these local relationships are best preserved (more details shortly). \n", - "\n", - "\n", - "\n", - "## Other techniques\n", - "\n", - "\n", - "There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.\n", - "\n", - "Here are some of the most popular:\n", - "* **Multidimensional Scaling (MDS)** reduces dimensionality while trying to preserve the distances between the instances.\n", - "\n", - "* **Isomap** creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.\n", - "\n", - "* **t-Distributed Stochastic Neighbor Embedding** (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).\n", - "\n", - "* Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures." + "4. [Introduction to Partial Differential Equations by A. Tveito, R. Winther](https://www.springer.com/us/book/9783540225515)" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -4747,13 +7320,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", -<<<<<<< HEAD - "version": "3.6.8" -======= - "version": "3.8.3" ->>>>>>> 9b0e2e75096cc1acee65bfac25f4eff818140252 + "version": "3.9.15" } }, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz index 27f05a662..daf852197 100644 Binary files a/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz and b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz differ diff --git a/doc/pub/week43/ipynb/week43.ipynb b/doc/pub/week43/ipynb/week43.ipynb index 0635c602d..b190102b6 100644 --- a/doc/pub/week43/ipynb/week43.ipynb +++ b/doc/pub/week43/ipynb/week43.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "6107bf3a", + "id": "5e07edf2", "metadata": { "editable": true }, @@ -14,42 +14,44 @@ }, { "cell_type": "markdown", - "id": "fdc249e0", + "id": "44b465a0", "metadata": { "editable": true }, "source": [ "# Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway\n", "\n", - "Date: **October 21, 2024**" + "Date: **October 20, 2025**" ] }, { "cell_type": "markdown", - "id": "92454b8c", + "id": "9d7bd8c9", "metadata": { "editable": true }, "source": [ "## Plans for week 43\n", "\n", - "**Material for the lecture on Monday October 21, 2024.**\n", + "**Material for the lecture on Monday October 20, 2025.**\n", "\n", - " * Building our own Feed-forward Neural Network with intro to Tensorflow\n", + "1. Reminder from last week, see also lecture notes from week 42 at as well as those from week 41, see see . \n", "\n", - " * Solving differential equations with Neural Networks\n", + "2. Building our own Feed-forward Neural Network.\n", "\n", - " * Video of lecture at \n", + "3. Coding examples using Tensorflow/Keras and Pytorch examples. The Pytorch examples are adapted from Rashcka's text, see chapters 11-13.. \n", "\n", - " * Video os second part, solving differential equations with neural networks at \n", + "4. Start discussions on how to use neural networks for solving differential equations (ordinary and partial ones). This topic continues next week as well.\n", "\n", - " * Whiteboard notes on solving differential equations at " + "5. Video of lecture at \n", + "\n", + "6. Whiteboard notes at " ] }, { "cell_type": "markdown", - "id": "7ad9295b", + "id": "c50cff0f", "metadata": { "editable": true }, @@ -57,57 +59,14 @@ "## Exercises and lab session week 43\n", "**Lab sessions on Tuesday and Wednesday.**\n", "\n", - " * Exercise on writing your own neural network code\n", + "1. Work on writing your own neural network code and discussions of project 2. If you didn't get time to do the exercises from the two last weeks, we recommend doing so as these exercises give you the basic elements of a neural network code.\n", "\n", - " * The exercises this week will be continued next week as well\n", - "\n", - " * Discussion of project 2" + "2. The exercises this week are tailored to the optional part of project 2, and deal with studying ways to display results from classification problems" ] }, { "cell_type": "markdown", - "id": "cbe78b79", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematics of deep learning\n", - "\n", - "**Two recent books online.**\n", - "\n", - "1. The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen at , published as [Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022](https://doi.org/10.1017/9781009025096.002)\n", - "\n", - "2. Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger at " - ] - }, - { - "cell_type": "markdown", - "id": "52f3d73d", - "metadata": { - "editable": true - }, - "source": [ - "## Reminder on books with hands-on material and codes\n", - "* Sebastian Rashcka et al, Machine learning with Scikit-Learn and PyTorch at " - ] - }, - { - "cell_type": "markdown", - "id": "afcf91a9", - "metadata": { - "editable": true - }, - "source": [ - "## Reading recommendations\n", - "\n", - "1. Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub site at . See also chapters 12 and 13 on using Pytorch to make a Neural network code. \n", - "\n", - "2. Goodfellow et al, chapter 6 and 7 contain most of the neural network background." - ] - }, - { - "cell_type": "markdown", - "id": "73c52766", + "id": "fe8d32ed", "metadata": { "editable": true }, @@ -115,12 +74,12 @@ "## Using Automatic differentiation\n", "\n", "In our discussions of ordinary differential equations and neural network codes\n", - "we will also study the usage of Autograd, see for example in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from [week 39](https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html) and the Autograd documentation at ." + "we will also study the usage of Autograd, see for example in computing gradients for deep learning. For the documentation of Autograd and examples see the Autograd documentation at and the lecture slides from week 41, see ." ] }, { "cell_type": "markdown", - "id": "0c8d3f87", + "id": "99999ab4", "metadata": { "editable": true }, @@ -137,23 +96,23 @@ }, { "cell_type": "markdown", - "id": "e37a061f", + "id": "b4489372", "metadata": { "editable": true }, "source": [ - "## Lecture Monday October 21" + "## Lecture Monday October 20" ] }, { "cell_type": "markdown", - "id": "c9dcc967", + "id": "f7435e4a", "metadata": { "editable": true }, "source": [ "## Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations\n", - "This is a reminder from where we ended last week.\n", + "This is a reminder from last week.\n", "\n", "**The architecture (our model).**\n", "\n", @@ -174,7 +133,7 @@ }, { "cell_type": "markdown", - "id": "5ff0f230", + "id": "e2561576", "metadata": { "editable": true }, @@ -197,7 +156,7 @@ }, { "cell_type": "markdown", - "id": "9bfa26c0", + "id": "39ed46ed", "metadata": { "editable": true }, @@ -209,7 +168,7 @@ }, { "cell_type": "markdown", - "id": "eb6f6d75", + "id": "776b50ac", "metadata": { "editable": true }, @@ -221,7 +180,7 @@ }, { "cell_type": "markdown", - "id": "8474f6a3", + "id": "b0ad385d", "metadata": { "editable": true }, @@ -231,7 +190,7 @@ }, { "cell_type": "markdown", - "id": "0edb9d87", + "id": "bb592830", "metadata": { "editable": true }, @@ -243,7 +202,7 @@ }, { "cell_type": "markdown", - "id": "5e0a7cea", + "id": "41259526", "metadata": { "editable": true }, @@ -257,7 +216,7 @@ }, { "cell_type": "markdown", - "id": "790a822d", + "id": "47eaff91", "metadata": { "editable": true }, @@ -269,7 +228,7 @@ }, { "cell_type": "markdown", - "id": "adec1944", + "id": "05b74533", "metadata": { "editable": true }, @@ -281,7 +240,7 @@ }, { "cell_type": "markdown", - "id": "556caafc", + "id": "6edb8648", "metadata": { "editable": true }, @@ -291,7 +250,7 @@ }, { "cell_type": "markdown", - "id": "17f55244", + "id": "a663fc08", "metadata": { "editable": true }, @@ -303,7 +262,7 @@ }, { "cell_type": "markdown", - "id": "d2cb9b96", + "id": "479150e0", "metadata": { "editable": true }, @@ -315,7 +274,7 @@ }, { "cell_type": "markdown", - "id": "ededcd6c", + "id": "41b9b1ea", "metadata": { "editable": true }, @@ -325,7 +284,7 @@ }, { "cell_type": "markdown", - "id": "837b7226", + "id": "590c403a", "metadata": { "editable": true }, @@ -337,7 +296,7 @@ }, { "cell_type": "markdown", - "id": "be1f3b39", + "id": "3db8cbb4", "metadata": { "editable": true }, @@ -349,7 +308,7 @@ }, { "cell_type": "markdown", - "id": "a320c88d", + "id": "a204182a", "metadata": { "editable": true }, @@ -372,7 +331,7 @@ }, { "cell_type": "markdown", - "id": "d832d09f", + "id": "4fe58cce", "metadata": { "editable": true }, @@ -384,7 +343,7 @@ }, { "cell_type": "markdown", - "id": "588ddc37", + "id": "a14f6d08", "metadata": { "editable": true }, @@ -396,7 +355,7 @@ }, { "cell_type": "markdown", - "id": "ff490c14", + "id": "4c290410", "metadata": { "editable": true }, @@ -406,7 +365,7 @@ }, { "cell_type": "markdown", - "id": "33129f1d", + "id": "ca1ac514", "metadata": { "editable": true }, @@ -418,7 +377,7 @@ }, { "cell_type": "markdown", - "id": "2cd95b52", + "id": "b9bcfab3", "metadata": { "editable": true }, @@ -439,7 +398,7 @@ }, { "cell_type": "markdown", - "id": "36bff826", + "id": "2fdf56f7", "metadata": { "editable": true }, @@ -453,7 +412,7 @@ }, { "cell_type": "markdown", - "id": "9ef16459", + "id": "14bf193c", "metadata": { "editable": true }, @@ -465,7 +424,7 @@ }, { "cell_type": "markdown", - "id": "4cc08f94", + "id": "df29068f", "metadata": { "editable": true }, @@ -487,7 +446,7 @@ }, { "cell_type": "markdown", - "id": "ea028825", + "id": "2fb5a29e", "metadata": { "editable": true }, @@ -509,1499 +468,7 @@ }, { "cell_type": "markdown", - "id": "921a49ef", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up a Multi-layer perceptron model for classification\n", - "\n", - "We are now gong to develop an example based on the MNIST data\n", - "base. This is a classification problem and we need to use our\n", - "cross-entropy function we discussed in connection with logistic\n", - "regression. The cross-entropy defines our cost function for the\n", - "classificaton problems with neural networks.\n", - "\n", - "In binary classification with two classes $(0, 1)$ we define the\n", - "logistic/sigmoid function as the probability that a particular input\n", - "is in class $0$ or $1$. This is possible because the logistic\n", - "function takes any input from the real numbers and inputs a number\n", - "between 0 and 1, and can therefore be interpreted as a probability. It\n", - "also has other nice properties, such as a derivative that is simple to\n", - "calculate.\n", - "\n", - "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", - "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", - "represents our activation values $z$. We have" - ] - }, - { - "cell_type": "markdown", - "id": "9a029a10", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "40d7c3b7", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "cf8c63fe", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1b6c3403", - "metadata": { - "editable": true - }, - "source": [ - "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", - "of our network." - ] - }, - { - "cell_type": "markdown", - "id": "8143e962", - "metadata": { - "editable": true - }, - "source": [ - "## Defining the cost function\n", - "\n", - "Our cost function is given as (see the Logistic regression lectures)" - ] - }, - { - "cell_type": "markdown", - "id": "6619f034", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = - \\sum_{i=1}^n\n", - "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\boldsymbol{\\theta}) .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6b4e1124", - "metadata": { - "editable": true - }, - "source": [ - "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", - "for each point in the dataset $\\mathcal{L}_i(\\boldsymbol{\\theta})$. \n", - "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", - "than maximizing a negative number. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", - "\n", - "$y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", - "\n", - "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$).. \n", - "\n", - "If $\\boldsymbol{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", - "output vector $\\boldsymbol{y}_i$. \n", - "The probability of $\\boldsymbol{x}_i$ being in class $c$ will be given by the softmax function:" - ] - }, - { - "cell_type": "markdown", - "id": "f0373257", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "P(y_{ic} = 1 \\mid \\boldsymbol{x}_i, \\boldsymbol{\\theta}) = \\frac{\\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_c)}}\n", - "{\\sum_{c'=0}^{C-1} \\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_{c'})}} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f958a039", - "metadata": { - "editable": true - }, - "source": [ - "which reduces to the logistic function in the binary case. \n", - "The likelihood of this $C$-class classifier\n", - "is now given as:" - ] - }, - { - "cell_type": "markdown", - "id": "e67e2ba4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "de66b0e1", - "metadata": { - "editable": true - }, - "source": [ - "Again we take the negative log-likelihood to define our cost function:" - ] - }, - { - "cell_type": "markdown", - "id": "8f041533", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8840e115", - "metadata": { - "editable": true - }, - "source": [ - "See the logistic regression lectures for a full definition of the cost function.\n", - "\n", - "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!" - ] - }, - { - "cell_type": "markdown", - "id": "f21c7506", - "metadata": { - "editable": true - }, - "source": [ - "## Example: binary classification problem\n", - "\n", - "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" - ] - }, - { - "cell_type": "markdown", - "id": "72c3c921", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\boldsymbol{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\boldsymbol{\\beta})}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e37b9409", - "metadata": { - "editable": true - }, - "source": [ - "where we had defined the logistic (sigmoid) function" - ] - }, - { - "cell_type": "markdown", - "id": "0f635478", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(y_i =1\\vert x_i,\\boldsymbol{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "96e12d56", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "25625fe3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(y_i =0\\vert x_i,\\boldsymbol{\\beta})=1-p(y_i =1\\vert x_i,\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cd61de5c", - "metadata": { - "editable": true - }, - "source": [ - "The parameters $\\boldsymbol{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", - "\n", - "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "id": "9bb7f55b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6e427758", - "metadata": { - "editable": true - }, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "e28000bc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1986d31a", - "metadata": { - "editable": true - }, - "source": [ - "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", - "Our cost function at the final layer $l=L$ is now" - ] - }, - { - "cell_type": "markdown", - "id": "c1797668", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "07583c6a", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" - ] - }, - { - "cell_type": "markdown", - "id": "978e292d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d6385ead", - "metadata": { - "editable": true - }, - "source": [ - "In case we use another activation function than the logistic one, we need to evaluate other derivatives." - ] - }, - { - "cell_type": "markdown", - "id": "8335897f", - "metadata": { - "editable": true - }, - "source": [ - "## The Softmax function\n", - "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" - ] - }, - { - "cell_type": "markdown", - "id": "50f96054", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "db6ebd31", - "metadata": { - "editable": true - }, - "source": [ - "For the Softmax function we have" - ] - }, - { - "cell_type": "markdown", - "id": "e5c3f583", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7988ff75", - "metadata": { - "editable": true - }, - "source": [ - "Its derivative with respect to $z_j^l$ gives" - ] - }, - { - "cell_type": "markdown", - "id": "d3073ab9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a4be6483", - "metadata": { - "editable": true - }, - "source": [ - "which in case of the simply binary model reduces to having $i=j$." - ] - }, - { - "cell_type": "markdown", - "id": "cbbc9199", - "metadata": { - "editable": true - }, - "source": [ - "## Developing a code for doing neural networks with back propagation\n", - "\n", - "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", - "\n", - "1. Collect and pre-process data \n", - "\n", - "2. Define model and architecture \n", - "\n", - "3. Choose cost function and optimizer \n", - "\n", - "4. Train the model \n", - "\n", - "5. Evaluate model performance on test data \n", - "\n", - "6. Adjust hyperparameters (if necessary, network architecture)" - ] - }, - { - "cell_type": "markdown", - "id": "67083baf", - "metadata": { - "editable": true - }, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", - "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", - "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", - "of handwritten digits that is commonly used for training various image processing systems. \n", - "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", - "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", - "\n", - "To feed data into a feed-forward neural network we need to represent\n", - "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", - "row represents an *input*, in this case a handwritten digit, and\n", - "each column represents a *feature*, in this case a pixel. The\n", - "correct answers, also known as *labels* or *targets* are\n", - "represented as a 1D array of integers \n", - "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", - "\n", - "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", - "measurements of height (in m) \n", - "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", - "\n", - "$$ X = \\begin{bmatrix}\n", - "1.85 & 81\\\\\n", - "1.71 & 65\\\\\n", - "1.95 & 103\\\\\n", - "1.55 & 42\\\\\n", - "1.63 & 56\n", - "\\end{bmatrix} ,$$ \n", - "\n", - "and the targets would be: \n", - "\n", - "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", - "\n", - "Since each input image is a 2D matrix, we need to flatten the image\n", - "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", - "design/feature matrix. This means we lose all spatial information in the\n", - "image, such as locality and translational invariance. More complicated\n", - "architectures such as Convolutional Neural Networks can take advantage\n", - "of such information, and are most commonly applied when analyzing\n", - "images." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "ce086d04", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "54bfb494", - "metadata": { - "editable": true - }, - "source": [ - "## Train and test datasets\n", - "\n", - "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", - "\n", - "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", - "\n", - "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", - "no bias in the sampling. \n", - "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", - "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", - "collected from 12.00 to 24.00." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "63b09387", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)\n", - "\n", - "# equivalently in numpy\n", - "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", - " n_inputs = len(inputs)\n", - " inputs_shuffled = inputs.copy()\n", - " labels_shuffled = labels.copy()\n", - " \n", - " np.random.shuffle(inputs_shuffled)\n", - " np.random.shuffle(labels_shuffled)\n", - " \n", - " train_end = int(n_inputs*train_size)\n", - " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", - " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", - " \n", - " return X_train, X_test, Y_train, Y_test\n", - "\n", - "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", - "\n", - "print(\"Number of training images: \" + str(len(X_train)))\n", - "print(\"Number of test images: \" + str(len(X_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "8af9f143", - "metadata": { - "editable": true - }, - "source": [ - "## Define model and architecture\n", - "\n", - "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", - "\n", - "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", - "\n", - "$$ y = f(z) ,$$\n", - "\n", - "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", - "and $w_i$ is the weight to input $i$. \n", - "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", - "\n", - "The simplest activation function for a neuron is the *Heaviside* function:\n", - "\n", - "$$ f(z) = \n", - "\\begin{cases}\n", - "1, & z > 0\\\\\n", - "0, & \\text{otherwise}\n", - "\\end{cases}\n", - "$$\n", - "\n", - "A feed-forward neural network with this activation is known as a *perceptron*. \n", - "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", - "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", - "and we call these architectures *multiclass perceptrons*. \n", - "\n", - "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", - "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", - "\n", - "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", - "We will be using the sigmoid function $\\sigma(x)$: \n", - "\n", - "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", - "\n", - "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." - ] - }, - { - "cell_type": "markdown", - "id": "0878e62d", - "metadata": { - "editable": true - }, - "source": [ - "## Layers\n", - "\n", - "* Input \n", - "\n", - "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", - "\n", - "* Hidden layer\n", - "\n", - "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", - "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", - "\n", - "* Output\n", - "\n", - "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", - "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", - "\n", - "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", - "\n", - "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", - "\n", - "$$ P(\\text{class $j$} \\mid \\text{input $\\boldsymbol{a}$}) = \\frac{\\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_j)}}\n", - "{\\sum_{c=0}^{9} \\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_c)}} ,$$ \n", - "\n", - "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\boldsymbol{a}$, with $\\boldsymbol{w}_j$ the weights of neuron $j$ to the inputs. \n", - "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", - "The exponent is just the weighted sum of inputs as before: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", - "\n", - "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", - "weights to the output layer." - ] - }, - { - "cell_type": "markdown", - "id": "32e84e6b", - "metadata": { - "editable": true - }, - "source": [ - "## Weights and biases\n", - "\n", - "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", - "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", - "\n", - "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", - "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", - "\n", - "The bias weights $\\boldsymbol{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "2f1c2946", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# building our neural network\n", - "\n", - "n_inputs, n_features = X_train.shape\n", - "n_hidden_neurons = 50\n", - "n_categories = 10\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01" - ] - }, - { - "cell_type": "markdown", - "id": "8f3da5d5", - "metadata": { - "editable": true - }, - "source": [ - "## Feed-forward pass\n", - "\n", - "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", - "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", - "\n", - "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", - "\n", - "this is then passed through our activation function \n", - "\n", - "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", - "\n", - "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", - "\n", - "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", - "\n", - "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", - "\n", - "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", - "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$" - ] - }, - { - "cell_type": "markdown", - "id": "bd250632", - "metadata": { - "editable": true - }, - "source": [ - "## Matrix multiplications\n", - "\n", - "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", - "layer have the dimensions \n", - "$W_{hidden} = (n_{features}, n_{hidden})$,\n", - "we can easily feed the network all our training data in one go by taking the matrix product \n", - "\n", - "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", - "\n", - "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", - "for each input image and each hidden neuron. \n", - "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", - "\n", - "$$ \\boldsymbol{z}^{l} = \\boldsymbol{X} \\boldsymbol{W}^{l} + \\boldsymbol{b}^{l} ,$$\n", - "\n", - "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", - "This is then passed through the activation: \n", - "\n", - "$$ \\boldsymbol{a}^{l} = f(\\boldsymbol{z}^l) .$$ \n", - "\n", - "This is fed to the output layer: \n", - "\n", - "$$ \\boldsymbol{z}^{L} = \\boldsymbol{a}^{L} \\boldsymbol{W}^{L} + \\boldsymbol{b}^{L} .$$\n", - "\n", - "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", - "\n", - "$$ output = softmax (\\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "9367a90d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# setup the feed-forward pass, subscript h = hidden layer\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " return probabilities\n", - "\n", - "probabilities = feed_forward(X_train)\n", - "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", - "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", - "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", - "print()\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "predictions = predict(X_train)\n", - "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", - "print(\"prediction for image 0: \" + str(predictions[0]))\n", - "print(\"correct label for image 0: \" + str(Y_train[0]))" - ] - }, - { - "cell_type": "markdown", - "id": "06333cb2", - "metadata": { - "editable": true - }, - "source": [ - "## Choose cost function and optimizer\n", - "\n", - "To measure how well our neural network is doing we need to introduce a cost function. \n", - "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", - "that gives the total error of our network across all samples the *cost* function.\n", - "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$$ y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", - "\n", - "$$ y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", - "\n", - "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", - "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\boldsymbol{x}_i$ in the dataset.\n", - "\n", - "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", - "probability of the correct category $c'$ \n", - "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", - "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\boldsymbol{\\theta}$ represents the parameters of our network, i.e. all the weights and biases." - ] - }, - { - "cell_type": "markdown", - "id": "c7de629a", - "metadata": { - "editable": true - }, - "source": [ - "## Optimizing the cost function\n", - "\n", - "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\n", - "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 *local* minimum of the cost function. \n", - "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", - "\n", - "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", - "\n", - "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", - "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", - "\n", - "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", - "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", - "on a subset of the data called a *minibatch*. \n", - "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", - "is $N/M$. \n", - "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", - "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", - "\n", - "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", - "\n", - "This has two important benefits: \n", - "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", - "\n", - "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", - "\n", - "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)." - ] - }, - { - "cell_type": "markdown", - "id": "467898fe", - "metadata": { - "editable": true - }, - "source": [ - "## Regularization\n", - "\n", - "It is common to add an extra term to the cost function, proportional\n", - "to the size of the weights. This is equivalent to constraining the\n", - "size of the weights, so that they do not grow out of control.\n", - "Constraining the size of the weights means that the weights cannot\n", - "grow arbitrarily large to fit the training data, and in this way\n", - "reduces *overfitting*.\n", - "\n", - "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", - "\n", - "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\boldsymbol{w} \\rvert \\rvert_2^2 \n", - "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", - "\n", - "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", - "\n", - "In order to train the model, we need to calculate the derivative of\n", - "the cost function with respect to every bias and weight in the\n", - "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", - "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", - "layer ($+1$ for the bias), and the gradient must be calculated for\n", - "every parameter. We use the *backpropagation* algorithm discussed\n", - "above. This is a clever use of the chain rule that allows us to\n", - "calculate the gradient efficently." - ] - }, - { - "cell_type": "markdown", - "id": "da72e113", - "metadata": { - "editable": true - }, - "source": [ - "## Matrix multiplication\n", - "\n", - "To more efficently train our network these equations are implemented using matrix operations. \n", - "The error in the output layer is calculated simply as, with $\\boldsymbol{t}$ being our targets, \n", - "\n", - "$$ \\delta_L = \\boldsymbol{t} - \\boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ \n", - "\n", - "The gradient for the output weights is calculated as \n", - "\n", - "$$ \\nabla W_{L} = \\boldsymbol{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", - "\n", - "where $\\boldsymbol{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", - "Since we are going backwards we have to transpose the activation matrix. \n", - "\n", - "The gradient with respect to the output bias is then \n", - "\n", - "$$ \\nabla \\boldsymbol{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", - "\n", - "The error in the hidden layer is \n", - "\n", - "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", - "\n", - "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", - "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", - "the *Hadamard product*, meaning element-wise multiplication. \n", - "\n", - "This again gives us the gradients in the hidden layer: \n", - "\n", - "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", - "\n", - "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "356881fc", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# to categorical turns our integer vector into a onehot representation\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "# one-hot in numpy\n", - "def to_categorical_numpy(integer_vector):\n", - " n_inputs = len(integer_vector)\n", - " n_categories = np.max(integer_vector) + 1\n", - " onehot_vector = np.zeros((n_inputs, n_categories))\n", - " onehot_vector[range(n_inputs), integer_vector] = 1\n", - " \n", - " return onehot_vector\n", - "\n", - "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", - "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", - "\n", - "def feed_forward_train(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " # for backpropagation need activations in hidden and output layers\n", - " return a_h, probabilities\n", - "\n", - "def backpropagation(X, Y):\n", - " a_h, probabilities = feed_forward_train(X)\n", - " \n", - " # error in the output layer\n", - " error_output = probabilities - Y\n", - " # error in the hidden layer\n", - " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", - " \n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_h.T, error_output)\n", - " output_bias_gradient = np.sum(error_output, axis=0)\n", - " \n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", - " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", - "\n", - "eta = 0.01\n", - "lmbd = 0.01\n", - "for i in range(1000):\n", - " # calculate gradients\n", - " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", - " \n", - " # regularization term gradients\n", - " dWo += lmbd * output_weights\n", - " dWh += lmbd * hidden_weights\n", - " \n", - " # update weights and biases\n", - " output_weights -= eta * dWo\n", - " output_bias -= eta * dBo\n", - " hidden_weights -= eta * dWh\n", - " hidden_bias -= eta * dBh\n", - "\n", - "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" - ] - }, - { - "cell_type": "markdown", - "id": "978a1d33", - "metadata": { - "editable": true - }, - "source": [ - "## Improving performance\n", - "\n", - "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. \n", - "In order to obtain a network that does something useful, we will have to do a bit more work. \n", - "\n", - "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", - "\n", - "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", - "going through the entire dataset ($n/M$ batches) an *epoch*.\n", - "\n", - "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", - "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/)." - ] - }, - { - "cell_type": "markdown", - "id": "2c42fc5d", - "metadata": { - "editable": true - }, - "source": [ - "## Full object-oriented implementation\n", - "\n", - "It is very natural to think of the network as an object, with specific instances of the network\n", - "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." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "c54a3f5d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "class NeuralNetwork:\n", - " def __init__(\n", - " self,\n", - " X_data,\n", - " Y_data,\n", - " n_hidden_neurons=50,\n", - " n_categories=10,\n", - " epochs=10,\n", - " batch_size=100,\n", - " eta=0.1,\n", - " lmbd=0.0):\n", - "\n", - " self.X_data_full = X_data\n", - " self.Y_data_full = Y_data\n", - "\n", - " self.n_inputs = X_data.shape[0]\n", - " self.n_features = X_data.shape[1]\n", - " self.n_hidden_neurons = n_hidden_neurons\n", - " self.n_categories = n_categories\n", - "\n", - " self.epochs = epochs\n", - " self.batch_size = batch_size\n", - " self.iterations = self.n_inputs // self.batch_size\n", - " self.eta = eta\n", - " self.lmbd = lmbd\n", - "\n", - " self.create_biases_and_weights()\n", - "\n", - " def create_biases_and_weights(self):\n", - " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", - " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", - "\n", - " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", - " self.output_bias = np.zeros(self.n_categories) + 0.01\n", - "\n", - " def feed_forward(self):\n", - " # feed-forward for training\n", - " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", - " self.a_h = sigmoid(self.z_h)\n", - "\n", - " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", - "\n", - " exp_term = np.exp(self.z_o)\n", - " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - "\n", - " def feed_forward_out(self, X):\n", - " # feed-forward for output\n", - " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", - " a_h = sigmoid(z_h)\n", - "\n", - " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", - " \n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " return probabilities\n", - "\n", - " def backpropagation(self):\n", - " error_output = self.probabilities - self.Y_data\n", - " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", - "\n", - " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", - " self.output_bias_gradient = np.sum(error_output, axis=0)\n", - "\n", - " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", - " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " if self.lmbd > 0.0:\n", - " self.output_weights_gradient += self.lmbd * self.output_weights\n", - " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", - "\n", - " self.output_weights -= self.eta * self.output_weights_gradient\n", - " self.output_bias -= self.eta * self.output_bias_gradient\n", - " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", - " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", - "\n", - " def predict(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - " def predict_probabilities(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return probabilities\n", - "\n", - " def train(self):\n", - " data_indices = np.arange(self.n_inputs)\n", - "\n", - " for i in range(self.epochs):\n", - " for j in range(self.iterations):\n", - " # pick datapoints with replacement\n", - " chosen_datapoints = np.random.choice(\n", - " data_indices, size=self.batch_size, replace=False\n", - " )\n", - "\n", - " # minibatch training data\n", - " self.X_data = self.X_data_full[chosen_datapoints]\n", - " self.Y_data = self.Y_data_full[chosen_datapoints]\n", - "\n", - " self.feed_forward()\n", - " self.backpropagation()" - ] - }, - { - "cell_type": "markdown", - "id": "bde5d577", - "metadata": { - "editable": true - }, - "source": [ - "## Evaluate model performance on test data\n", - "\n", - "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. \n", - "We measure the performance of the network using the *accuracy* score. \n", - "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 $1$. \n", - "\n", - "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\tilde{y}_i = y_i)}{n} ,$$ \n", - "\n", - "where $I$ is the indicator function, $1$ if $\\tilde{y}_i = y_i$ and $0$ otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "0ff4f685", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "epochs = 100\n", - "batch_size = 100\n", - "\n", - "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - "dnn.train()\n", - "test_predict = dnn.predict(X_test)\n", - "\n", - "# accuracy score from scikit library\n", - "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - "\n", - "# equivalent in numpy\n", - "def accuracy_score_numpy(Y_test, Y_pred):\n", - " return np.sum(Y_test == Y_pred) / len(Y_test)\n", - "\n", - "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" - ] - }, - { - "cell_type": "markdown", - "id": "222281ee", - "metadata": { - "editable": true - }, - "source": [ - "## Adjust hyperparameters\n", - "\n", - "We now perform a grid search to find the optimal hyperparameters for the network. \n", - "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "bff5aecd", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store the models for later use\n", - "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "# grid search\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - " dnn.train()\n", - " \n", - " DNN_numpy[i][j] = dnn\n", - " \n", - " test_predict = dnn.predict(X_test)\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "205932c1", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "90a6c9a8", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_numpy[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "8616f12b", - "metadata": { - "editable": true - }, - "source": [ - "## scikit-learn implementation\n", - "\n", - "**scikit-learn** focuses more\n", - "on traditional machine learning methods, such as regression,\n", - "clustering, decision trees, etc. As such, it has only two types of\n", - "neural networks: Multi Layer Perceptron outputting continuous values,\n", - "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", - "*MLPClassifier*. We will see how simple it is to use these classes.\n", - "\n", - "**scikit-learn** implements a few improvements from our neural network,\n", - "such as early stopping, a varying learning rate, different\n", - "optimization methods, etc. We would therefore expect a better\n", - "performance overall." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "38c2dff0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.neural_network import MLPClassifier\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X_train, Y_train)\n", - " \n", - " DNN_scikit[i][j] = dnn\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "766c15ae", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "b8670cd3", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "512ca005", + "id": "bab79791", "metadata": { "editable": true }, @@ -2019,7 +486,7 @@ }, { "cell_type": "markdown", - "id": "0fa97800", + "id": "cc32bc9d", "metadata": { "editable": true }, @@ -2053,8 +520,8 @@ }, { "cell_type": "code", - "execution_count": 12, - "id": "7bdc829d", + "execution_count": 1, + "id": "deb81088", "metadata": { "collapsed": false, "editable": true @@ -2066,7 +533,7 @@ }, { "cell_type": "markdown", - "id": "1fcedfc6", + "id": "979148b0", "metadata": { "editable": true }, @@ -2077,8 +544,8 @@ }, { "cell_type": "code", - "execution_count": 13, - "id": "a96a6361", + "execution_count": 2, + "id": "ad63b8d9", "metadata": { "collapsed": false, "editable": true @@ -2091,7 +558,7 @@ }, { "cell_type": "markdown", - "id": "540e8c9b", + "id": "1417a40e", "metadata": { "editable": true }, @@ -2101,8 +568,8 @@ }, { "cell_type": "code", - "execution_count": 14, - "id": "73b6c334", + "execution_count": 3, + "id": "d56acb3a", "metadata": { "collapsed": false, "editable": true @@ -2115,7 +582,7 @@ }, { "cell_type": "markdown", - "id": "df6cd2ce", + "id": "6a163d27", "metadata": { "editable": true }, @@ -2129,8 +596,8 @@ }, { "cell_type": "code", - "execution_count": 15, - "id": "b5d544a0", + "execution_count": 4, + "id": "9ee390a8", "metadata": { "collapsed": false, "editable": true @@ -2142,7 +609,7 @@ }, { "cell_type": "markdown", - "id": "a456ab5f", + "id": "528ea3d5", "metadata": { "editable": true }, @@ -2154,7 +621,7 @@ }, { "cell_type": "markdown", - "id": "53a01445", + "id": "32178225", "metadata": { "editable": true }, @@ -2166,14 +633,16 @@ }, { "cell_type": "code", - "execution_count": 16, - "id": "3026f2a6", + "execution_count": 5, + "id": "e37f86e4", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ + "%matplotlib inline\n", + "\n", "# import necessary packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", @@ -2221,8 +690,8 @@ }, { "cell_type": "code", - "execution_count": 17, - "id": "9b5cdbc5", + "execution_count": 6, + "id": "06a7c3bd", "metadata": { "collapsed": false, "editable": true @@ -2250,8 +719,8 @@ }, { "cell_type": "code", - "execution_count": 18, - "id": "62419d1b", + "execution_count": 7, + "id": "358b46c5", "metadata": { "collapsed": false, "editable": true @@ -2280,8 +749,8 @@ }, { "cell_type": "code", - "execution_count": 19, - "id": "ba4de85c", + "execution_count": 8, + "id": "5a0445fb", "metadata": { "collapsed": false, "editable": true @@ -2307,8 +776,8 @@ }, { "cell_type": "code", - "execution_count": 20, - "id": "0ba97552", + "execution_count": 9, + "id": "f301c7cf", "metadata": { "collapsed": false, "editable": true @@ -2350,18 +819,116 @@ }, { "cell_type": "markdown", - "id": "e3785d9f", + "id": "610c95e1", "metadata": { "editable": true }, "source": [ - "## The Breast Cancer Data, now with Keras" + "## Using Pytorch with the full MNIST data set" ] }, { "cell_type": "code", - "execution_count": 21, - "id": "9c50fc5e", + "execution_count": 10, + "id": "d0f3ad9a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "import torchvision\n", + "import torchvision.transforms as transforms\n", + "\n", + "# Device configuration: use GPU if available\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# MNIST dataset (downloads if not already present)\n", + "transform = transforms.Compose([\n", + " transforms.ToTensor(),\n", + " transforms.Normalize((0.5,), (0.5,)) # normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range)\n", + "])\n", + "train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)\n", + "test_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)\n", + "\n", + "train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)\n", + "\n", + "\n", + "class NeuralNet(nn.Module):\n", + " def __init__(self):\n", + " super(NeuralNet, self).__init__()\n", + " self.fc1 = nn.Linear(28*28, 100) # first hidden layer (784 -> 100)\n", + " self.fc2 = nn.Linear(100, 100) # second hidden layer (100 -> 100)\n", + " self.fc3 = nn.Linear(100, 10) # output layer (100 -> 10 classes)\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1) # flatten images into vectors of size 784\n", + " x = torch.relu(self.fc1(x)) # hidden layer 1 + ReLU activation\n", + " x = torch.relu(self.fc2(x)) # hidden layer 2 + ReLU activation\n", + " x = self.fc3(x) # output layer (logits for 10 classes)\n", + " return x\n", + "\n", + "model = NeuralNet().to(device)\n", + "\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)\n", + "\n", + "num_epochs = 10\n", + "for epoch in range(num_epochs):\n", + " model.train() # set model to training mode\n", + " running_loss = 0.0\n", + " for images, labels in train_loader:\n", + " # Move data to device (GPU if available, else CPU)\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad() # reset gradients to zero\n", + " outputs = model(images) # forward pass: compute predictions\n", + " loss = criterion(outputs, labels) # compute cross-entropy loss\n", + " loss.backward() # backpropagate to compute gradients\n", + " optimizer.step() # update weights using SGD step \n", + "\n", + " running_loss += loss.item()\n", + " # Compute average loss over all batches in this epoch\n", + " avg_loss = running_loss / len(train_loader)\n", + " print(f\"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}\")\n", + "\n", + "#Evaluation on the Test Set\n", + "\n", + "\n", + "\n", + "model.eval() # set model to evaluation mode \n", + "correct = 0\n", + "total = 0\n", + "with torch.no_grad(): # disable gradient calculation for evaluation \n", + " for images, labels in test_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + " _, predicted = torch.max(outputs, dim=1) # class with highest score\n", + " total += labels.size(0)\n", + " correct += (predicted == labels).sum().item()\n", + "\n", + "accuracy = 100 * correct / total\n", + "print(f\"Test Accuracy: {accuracy:.2f}%\")" + ] + }, + { + "cell_type": "markdown", + "id": "aad687aa", + "metadata": { + "editable": true + }, + "source": [ + "## And a similar example using Tensorflow with Keras" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "b6c4fad4", "metadata": { "collapsed": false, "editable": true @@ -2370,180 +937,63 @@ "source": [ "\n", "import tensorflow as tf\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import seaborn as sns\n", - "from sklearn.model_selection import train_test_split as splitter\n", - "from sklearn.datasets import load_breast_cancer\n", - "import pickle\n", - "import os \n", + "from tensorflow import keras\n", + "from tensorflow.keras import layers, regularizers\n", "\n", + "# Check for GPU (TensorFlow will use it automatically if available)\n", + "gpus = tf.config.list_physical_devices('GPU')\n", + "print(f\"GPUs available: {gpus}\")\n", "\n", - "\"\"\"Load breast cancer dataset\"\"\"\n", + "# 1) Load and preprocess MNIST\n", + "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n", + "# Normalize to [0, 1]\n", + "x_train = (x_train.astype(\"float32\") / 255.0)\n", + "x_test = (x_test.astype(\"float32\") / 255.0)\n", "\n", - "np.random.seed(0) #create same seed for random number every time\n", + "# 2) Build the model: 784 -> 100 -> 100 -> 10\n", + "l2_reg = 1e-4 # L2 regularization strength\n", "\n", - "cancer=load_breast_cancer() #Download breast cancer dataset\n", + "model = keras.Sequential([\n", + " layers.Input(shape=(28, 28)),\n", + " layers.Flatten(),\n", + " layers.Dense(100, activation=\"relu\",\n", + " kernel_regularizer=regularizers.l2(l2_reg)),\n", + " layers.Dense(100, activation=\"relu\",\n", + " kernel_regularizer=regularizers.l2(l2_reg)),\n", + " layers.Dense(10, activation=\"softmax\") # output probabilities for 10 classes\n", + "])\n", "\n", - "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n", - "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n", - "labels=cancer.feature_names[0:30]\n", + "# 3) Compile with SGD + weight decay via L2 regularizers\n", + "model.compile(\n", + " optimizer=keras.optimizers.SGD(learning_rate=0.01),\n", + " loss=\"sparse_categorical_crossentropy\",\n", + " metrics=[\"accuracy\"],\n", + ")\n", "\n", - "print('The content of the breast cancer dataset is:') #Print information about the datasets\n", - "print(labels)\n", - "print('-------------------------')\n", - "print(\"inputs = \" + str(inputs.shape))\n", - "print(\"outputs = \" + str(outputs.shape))\n", - "print(\"labels = \"+ str(labels.shape))\n", + "model.summary()\n", "\n", - "x=inputs #Reassign the Feature and Label matrices to other variables\n", - "y=outputs\n", + "# 4) Train\n", + "history = model.fit(\n", + " x_train, y_train,\n", + " epochs=10,\n", + " batch_size=64,\n", + " validation_split=0.1, # optional: monitor validation during training\n", + " verbose=1\n", + ")\n", "\n", - "#%% \n", - "\n", - "# Visualisation of dataset (for correlation analysis)\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean perimeter',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean compactness',fontweight='bold')\n", - "plt.ylabel('Mean concavity',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean texture',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean perimeter',fontweight='bold')\n", - "plt.ylabel('Mean compactness',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "# Generate training and testing datasets\n", - "\n", - "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n", - "#and add to input matrix\n", - "\n", - "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n", - "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n", - "X=np.hstack((temp1,temp2)) \n", - "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n", - "X=np.hstack((X,temp)) \n", - "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n", - "X=np.hstack((X,temp)) \n", - "\n", - "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n", - "\n", - "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n", - "y_test=to_categorical(y_test)\n", - "\n", - "del temp1,temp2,temp\n", - "\n", - "# %%\n", - "\n", - "# Define tunable parameters\"\n", - "\n", - "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n", - "lamda=0.01 #Define hyperparameter\n", - "n_layers=2 #Define number of hidden layers in the model\n", - "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n", - "epochs=100 #Number of reiterations over the input data\n", - "batch_size=100 #Number of samples per gradient update\n", - "\n", - "# %%\n", - "\n", - "\"\"\"Define function to return Deep Neural Network model\"\"\"\n", - "\n", - "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n", - " model=Sequential() \n", - " for i in range(n_layers): #Run loop to add hidden layers to the model\n", - " if (i==0): #First layer requires input dimensions\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n", - " else: #Subsequent layers are capable of automatic shape inferencing\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n", - " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n", - " sgd=optimizers.SGD(learning_rate=eta)\n", - " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n", - " return model\n", - "\n", - " \n", - "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n", - "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n", - "\n", - "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n", - " for j in range(len(eta)): #accuracy scores \n", - " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n", - " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n", - " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n", - " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n", - " \n", - "\n", - "def plot_data(x,y,data,title=None):\n", - "\n", - " # plot results\n", - " fontsize=16\n", - "\n", - "\n", - " fig = plt.figure()\n", - " ax = fig.add_subplot(111)\n", - " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n", - " \n", - " cbar=fig.colorbar(cax)\n", - " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n", - " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n", - " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n", - "\n", - " # put text on matrix elements\n", - " for i, x_val in enumerate(np.arange(len(x))):\n", - " for j, y_val in enumerate(np.arange(len(y))):\n", - " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n", - " ax.text(x_val, y_val, c, va='center', ha='center')\n", - "\n", - " # convert axis vaues to to string labels\n", - " x=[str(i) for i in x]\n", - " y=[str(i) for i in y]\n", - "\n", - "\n", - " ax.set_xticklabels(['']+x)\n", - " ax.set_yticklabels(['']+y)\n", - "\n", - " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n", - " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n", - " if title is not None:\n", - " ax.set_title(title)\n", - "\n", - " plt.tight_layout()\n", - "\n", - " plt.show()\n", - " \n", - "plot_data(eta,n_neuron,Train_accuracy, 'training')\n", - "plot_data(eta,n_neuron,Test_accuracy, 'testing')" + "# 5) Evaluate on test set\n", + "test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)\n", + "print(f\"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}\")" ] }, { "cell_type": "markdown", - "id": "ade357fd", + "id": "73162fbb", "metadata": { "editable": true }, "source": [ - "## Building a neural network code\n", + "## Building our own neural network code\n", "\n", "Here we present a flexible object oriented codebase\n", "for a feed forward neural network, along with a demonstration of how\n", @@ -2557,7 +1007,7 @@ }, { "cell_type": "markdown", - "id": "77afb266", + "id": "86f36041", "metadata": { "editable": true }, @@ -2578,8 +1028,8 @@ }, { "cell_type": "code", - "execution_count": 22, - "id": "bfd96580", + "execution_count": 12, + "id": "bcbec449", "metadata": { "collapsed": false, "editable": true @@ -2720,7 +1170,7 @@ }, { "cell_type": "markdown", - "id": "ace26b9a", + "id": "961989d9", "metadata": { "editable": true }, @@ -2735,8 +1185,8 @@ }, { "cell_type": "code", - "execution_count": 23, - "id": "60867348", + "execution_count": 13, + "id": "1e9fbe0f", "metadata": { "collapsed": false, "editable": true @@ -2749,7 +1199,7 @@ }, { "cell_type": "markdown", - "id": "12f1d032", + "id": "b5adb1b4", "metadata": { "editable": true }, @@ -2760,8 +1210,8 @@ }, { "cell_type": "code", - "execution_count": 24, - "id": "78ae91c3", + "execution_count": 14, + "id": "dc4f4d28", "metadata": { "collapsed": false, "editable": true @@ -2783,7 +1233,7 @@ }, { "cell_type": "markdown", - "id": "e505e6ef", + "id": "8964d118", "metadata": { "editable": true }, @@ -2798,8 +1248,8 @@ }, { "cell_type": "code", - "execution_count": 25, - "id": "195b3f3b", + "execution_count": 15, + "id": "3a8470bd", "metadata": { "collapsed": false, "editable": true @@ -2837,7 +1287,7 @@ }, { "cell_type": "markdown", - "id": "683f7300", + "id": "ab4daf8f", "metadata": { "editable": true }, @@ -2849,8 +1299,8 @@ }, { "cell_type": "code", - "execution_count": 26, - "id": "5e9a52eb", + "execution_count": 16, + "id": "cf8922ac", "metadata": { "collapsed": false, "editable": true @@ -2871,7 +1321,7 @@ }, { "cell_type": "markdown", - "id": "34fd5422", + "id": "fab332c4", "metadata": { "editable": true }, @@ -2886,8 +1336,8 @@ }, { "cell_type": "code", - "execution_count": 27, - "id": "429ec779", + "execution_count": 17, + "id": "5ab56013", "metadata": { "collapsed": false, "editable": true @@ -2945,7 +1395,7 @@ }, { "cell_type": "markdown", - "id": "f1ffb711", + "id": "969612c3", "metadata": { "editable": true }, @@ -2959,8 +1409,8 @@ }, { "cell_type": "code", - "execution_count": 28, - "id": "a08ff105", + "execution_count": 18, + "id": "313878c6", "metadata": { "collapsed": false, "editable": true @@ -2981,7 +1431,7 @@ }, { "cell_type": "markdown", - "id": "a6e789db", + "id": "095347a2", "metadata": { "editable": true }, @@ -3004,8 +1454,8 @@ }, { "cell_type": "code", - "execution_count": 29, - "id": "9f0ef730", + "execution_count": 19, + "id": "9ea2b0b7", "metadata": { "collapsed": false, "editable": true @@ -3477,7 +1927,7 @@ }, { "cell_type": "markdown", - "id": "6d6cae4f", + "id": "0f29bccd", "metadata": { "editable": true }, @@ -3488,8 +1938,8 @@ }, { "cell_type": "code", - "execution_count": 30, - "id": "e2c91847", + "execution_count": 20, + "id": "dc37b403", "metadata": { "collapsed": false, "editable": true @@ -3533,7 +1983,7 @@ }, { "cell_type": "markdown", - "id": "e9049787", + "id": "91790369", "metadata": { "editable": true }, @@ -3548,8 +1998,8 @@ }, { "cell_type": "code", - "execution_count": 31, - "id": "a3af9356", + "execution_count": 21, + "id": "62585c7a", "metadata": { "collapsed": false, "editable": true @@ -3564,7 +2014,7 @@ }, { "cell_type": "markdown", - "id": "7c016294", + "id": "69cdc171", "metadata": { "editable": true }, @@ -3574,8 +2024,8 @@ }, { "cell_type": "code", - "execution_count": 32, - "id": "456a3a63", + "execution_count": 22, + "id": "d0713298", "metadata": { "collapsed": false, "editable": true @@ -3590,7 +2040,7 @@ }, { "cell_type": "markdown", - "id": "a66bd6e5", + "id": "310f805d", "metadata": { "editable": true }, @@ -3605,8 +2055,8 @@ }, { "cell_type": "code", - "execution_count": 33, - "id": "861e3e2b", + "execution_count": 23, + "id": "216d1c44", "metadata": { "collapsed": false, "editable": true @@ -3620,7 +2070,7 @@ }, { "cell_type": "markdown", - "id": "614514f4", + "id": "ba2e5a39", "metadata": { "editable": true }, @@ -3634,8 +2084,8 @@ }, { "cell_type": "code", - "execution_count": 34, - "id": "595d3148", + "execution_count": 24, + "id": "8c5b291e", "metadata": { "collapsed": false, "editable": true @@ -3660,8 +2110,8 @@ }, { "cell_type": "code", - "execution_count": 35, - "id": "6d87e7d4", + "execution_count": 25, + "id": "4f6aa682", "metadata": { "collapsed": false, "editable": true @@ -3676,7 +2126,7 @@ }, { "cell_type": "markdown", - "id": "c21d1a42", + "id": "3ff7c54a", "metadata": { "editable": true }, @@ -3686,8 +2136,8 @@ }, { "cell_type": "code", - "execution_count": 36, - "id": "a4c194ca", + "execution_count": 26, + "id": "4bbcaedd", "metadata": { "collapsed": false, "editable": true @@ -3702,7 +2152,7 @@ }, { "cell_type": "markdown", - "id": "11d9fe2d", + "id": "aa4f54fe", "metadata": { "editable": true }, @@ -3712,8 +2162,8 @@ }, { "cell_type": "code", - "execution_count": 37, - "id": "006df1f5", + "execution_count": 27, + "id": "c11be1f5", "metadata": { "collapsed": false, "editable": true @@ -3732,8 +2182,8 @@ }, { "cell_type": "code", - "execution_count": 38, - "id": "e5d4f374", + "execution_count": 28, + "id": "78482f24", "metadata": { "collapsed": false, "editable": true @@ -3748,7 +2198,7 @@ }, { "cell_type": "markdown", - "id": "6d0775a4", + "id": "678b88e7", "metadata": { "editable": true }, @@ -3762,8 +2212,8 @@ }, { "cell_type": "code", - "execution_count": 39, - "id": "0437ee65", + "execution_count": 29, + "id": "833a7321", "metadata": { "collapsed": false, "editable": true @@ -3800,7 +2250,7 @@ }, { "cell_type": "markdown", - "id": "676f6839", + "id": "1af2ad7b", "metadata": { "editable": true }, @@ -3812,8 +2262,8 @@ }, { "cell_type": "code", - "execution_count": 40, - "id": "a0614327", + "execution_count": 30, + "id": "752c6403", "metadata": { "collapsed": false, "editable": true @@ -3836,7 +2286,7 @@ }, { "cell_type": "markdown", - "id": "2e3e6a48", + "id": "0a7c91e3", "metadata": { "editable": true }, @@ -3846,7 +2296,7 @@ }, { "cell_type": "markdown", - "id": "a0600f67", + "id": "40ffa1fb", "metadata": { "editable": true }, @@ -3873,7 +2323,7 @@ }, { "cell_type": "markdown", - "id": "2e2db428", + "id": "191ba3eb", "metadata": { "editable": true }, @@ -3887,7 +2337,7 @@ }, { "cell_type": "markdown", - "id": "79bc94bf", + "id": "a0be312a", "metadata": { "editable": true }, @@ -3904,7 +2354,7 @@ }, { "cell_type": "markdown", - "id": "8aae9608", + "id": "000663cf", "metadata": { "editable": true }, @@ -3920,7 +2370,7 @@ }, { "cell_type": "markdown", - "id": "5d4d34df", + "id": "f5b87995", "metadata": { "editable": true }, @@ -3932,7 +2382,7 @@ }, { "cell_type": "markdown", - "id": "4789ccab", + "id": "a166c0b6", "metadata": { "editable": true }, @@ -3950,7 +2400,7 @@ }, { "cell_type": "markdown", - "id": "f5bde685", + "id": "f1e49a2c", "metadata": { "editable": true }, @@ -3971,7 +2421,7 @@ }, { "cell_type": "markdown", - "id": "4651cd07", + "id": "207d1a97", "metadata": { "editable": true }, @@ -3988,7 +2438,7 @@ }, { "cell_type": "markdown", - "id": "6254e156", + "id": "94a061a1", "metadata": { "editable": true }, @@ -4000,7 +2450,7 @@ }, { "cell_type": "markdown", - "id": "20333501", + "id": "93244d03", "metadata": { "editable": true }, @@ -4011,7 +2461,7 @@ }, { "cell_type": "markdown", - "id": "813fe9a1", + "id": "6dc16fd4", "metadata": { "editable": true }, @@ -4028,7 +2478,7 @@ }, { "cell_type": "markdown", - "id": "ab52e1ed", + "id": "01f4c14a", "metadata": { "editable": true }, @@ -4039,7 +2489,7 @@ }, { "cell_type": "markdown", - "id": "ad9ead42", + "id": "1784066c", "metadata": { "editable": true }, @@ -4055,7 +2505,7 @@ }, { "cell_type": "markdown", - "id": "9d7307ee", + "id": "43e1b7bf", "metadata": { "editable": true }, @@ -4067,7 +2517,7 @@ }, { "cell_type": "markdown", - "id": "25cd1ecf", + "id": "5c28e60a", "metadata": { "editable": true }, @@ -4084,7 +2534,7 @@ }, { "cell_type": "markdown", - "id": "1628ddd6", + "id": "cfd2e420", "metadata": { "editable": true }, @@ -4096,7 +2546,7 @@ }, { "cell_type": "markdown", - "id": "6559be22", + "id": "b93aa0f8", "metadata": { "editable": true }, @@ -4114,7 +2564,7 @@ }, { "cell_type": "markdown", - "id": "ad3489df", + "id": "093952f0", "metadata": { "editable": true }, @@ -4124,7 +2574,7 @@ }, { "cell_type": "markdown", - "id": "3baa5d51", + "id": "8f82fa61", "metadata": { "editable": true }, @@ -4136,7 +2586,7 @@ }, { "cell_type": "markdown", - "id": "6793951c", + "id": "027d9c52", "metadata": { "editable": true }, @@ -4153,7 +2603,7 @@ }, { "cell_type": "markdown", - "id": "029174ae", + "id": "c18c4ee8", "metadata": { "editable": true }, @@ -4165,7 +2615,7 @@ }, { "cell_type": "markdown", - "id": "502a37dc", + "id": "a0d7fc0a", "metadata": { "editable": true }, @@ -4176,7 +2626,7 @@ }, { "cell_type": "markdown", - "id": "86f46ea0", + "id": "73cd72f4", "metadata": { "editable": true }, @@ -4188,7 +2638,7 @@ }, { "cell_type": "markdown", - "id": "3327e0e0", + "id": "a4d0850f", "metadata": { "editable": true }, @@ -4198,7 +2648,7 @@ }, { "cell_type": "markdown", - "id": "27d583c4", + "id": "62f3b94f", "metadata": { "editable": true }, @@ -4218,7 +2668,7 @@ }, { "cell_type": "markdown", - "id": "344a02b5", + "id": "f5144858", "metadata": { "editable": true }, @@ -4235,7 +2685,7 @@ }, { "cell_type": "markdown", - "id": "2ba3f9de", + "id": "6b441362", "metadata": { "editable": true }, @@ -4254,7 +2704,7 @@ }, { "cell_type": "markdown", - "id": "21fcac4a", + "id": "abfe2d6d", "metadata": { "editable": true }, @@ -4266,7 +2716,7 @@ }, { "cell_type": "markdown", - "id": "04a26245", + "id": "aabb6c7b", "metadata": { "editable": true }, @@ -4276,7 +2726,7 @@ }, { "cell_type": "markdown", - "id": "bbe30d4d", + "id": "11fc8b1b", "metadata": { "editable": true }, @@ -4293,7 +2743,7 @@ }, { "cell_type": "markdown", - "id": "bf115ba7", + "id": "604c92b4", "metadata": { "editable": true }, @@ -4303,7 +2753,7 @@ }, { "cell_type": "markdown", - "id": "e07822af", + "id": "e2cd7572", "metadata": { "editable": true }, @@ -4319,7 +2769,7 @@ }, { "cell_type": "markdown", - "id": "0bd949a8", + "id": "d916a5f6", "metadata": { "editable": true }, @@ -4331,7 +2781,7 @@ }, { "cell_type": "markdown", - "id": "e682bd3f", + "id": "d746e69c", "metadata": { "editable": true }, @@ -4343,7 +2793,7 @@ }, { "cell_type": "markdown", - "id": "9a5d7cbb", + "id": "4c34c242", "metadata": { "editable": true }, @@ -4355,7 +2805,7 @@ }, { "cell_type": "markdown", - "id": "5005ba3b", + "id": "f55f3047", "metadata": { "editable": true }, @@ -4365,7 +2815,7 @@ }, { "cell_type": "markdown", - "id": "a6c678bc", + "id": "485e4671", "metadata": { "editable": true }, @@ -4377,7 +2827,7 @@ }, { "cell_type": "markdown", - "id": "5d9081a6", + "id": "5628ca35", "metadata": { "editable": true }, @@ -4394,7 +2844,7 @@ }, { "cell_type": "markdown", - "id": "d30b3296", + "id": "da2c90ea", "metadata": { "editable": true }, @@ -4404,7 +2854,7 @@ }, { "cell_type": "markdown", - "id": "ba7ad1dc", + "id": "d386a466", "metadata": { "editable": true }, @@ -4416,7 +2866,7 @@ }, { "cell_type": "markdown", - "id": "c5c85fae", + "id": "ec3d975a", "metadata": { "editable": true }, @@ -4430,7 +2880,7 @@ }, { "cell_type": "markdown", - "id": "31455ab3", + "id": "4f0f47e7", "metadata": { "editable": true }, @@ -4446,7 +2896,7 @@ }, { "cell_type": "markdown", - "id": "db892730", + "id": "a757d9cf", "metadata": { "editable": true }, @@ -4458,7 +2908,7 @@ }, { "cell_type": "markdown", - "id": "77581ff5", + "id": "ee093dd9", "metadata": { "editable": true }, @@ -4480,7 +2930,7 @@ }, { "cell_type": "markdown", - "id": "2066b3b8", + "id": "4d3954bf", "metadata": { "editable": true }, @@ -4492,7 +2942,7 @@ }, { "cell_type": "markdown", - "id": "e5b2ec88", + "id": "b4b36b8c", "metadata": { "editable": true }, @@ -4515,7 +2965,7 @@ }, { "cell_type": "markdown", - "id": "7e73e4d1", + "id": "36e8a1dd", "metadata": { "editable": true }, @@ -4531,7 +2981,7 @@ }, { "cell_type": "markdown", - "id": "6e75a17f", + "id": "af2e68be", "metadata": { "editable": true }, @@ -4543,7 +2993,7 @@ }, { "cell_type": "markdown", - "id": "508d5800", + "id": "7b8922c6", "metadata": { "editable": true }, @@ -4567,7 +3017,7 @@ }, { "cell_type": "markdown", - "id": "c2e068bb", + "id": "2aa977d9", "metadata": { "editable": true }, @@ -4579,7 +3029,7 @@ }, { "cell_type": "markdown", - "id": "1c41a567", + "id": "48eccfa6", "metadata": { "editable": true }, @@ -4600,7 +3050,7 @@ }, { "cell_type": "markdown", - "id": "ee777fc2", + "id": "d4c2cdbf", "metadata": { "editable": true }, @@ -4612,7 +3062,7 @@ }, { "cell_type": "markdown", - "id": "4867702f", + "id": "be26d9c9", "metadata": { "editable": true }, @@ -4631,7 +3081,7 @@ }, { "cell_type": "markdown", - "id": "e8b191a7", + "id": "f3703c9a", "metadata": { "editable": true }, @@ -4641,7 +3091,7 @@ }, { "cell_type": "markdown", - "id": "07edf9ef", + "id": "9859680c", "metadata": { "editable": true }, @@ -4655,7 +3105,7 @@ }, { "cell_type": "markdown", - "id": "a44c683c", + "id": "c3df269d", "metadata": { "editable": true }, @@ -4667,7 +3117,7 @@ }, { "cell_type": "markdown", - "id": "8e35cfd6", + "id": "dc69023a", "metadata": { "editable": true }, @@ -4679,7 +3129,7 @@ }, { "cell_type": "markdown", - "id": "cad756d7", + "id": "d4bed3bd", "metadata": { "editable": true }, @@ -4696,7 +3146,7 @@ }, { "cell_type": "markdown", - "id": "e89f3475", + "id": "ed2a4f9a", "metadata": { "editable": true }, @@ -4708,7 +3158,7 @@ }, { "cell_type": "markdown", - "id": "05770b4f", + "id": "b9a4f604", "metadata": { "editable": true }, @@ -4730,7 +3180,7 @@ }, { "cell_type": "markdown", - "id": "aba3f2e6", + "id": "e48d507f", "metadata": { "editable": true }, @@ -4745,7 +3195,7 @@ }, { "cell_type": "markdown", - "id": "b9bfa280", + "id": "b84c5cf5", "metadata": { "editable": true }, @@ -4755,8 +3205,8 @@ }, { "cell_type": "code", - "execution_count": 41, - "id": "4eebdf51", + "execution_count": 31, + "id": "293d0f7d", "metadata": { "collapsed": false, "editable": true @@ -4911,7 +3361,7 @@ }, { "cell_type": "markdown", - "id": "091cc419", + "id": "54c070e1", "metadata": { "editable": true }, @@ -4925,8 +3375,8 @@ }, { "cell_type": "code", - "execution_count": 42, - "id": "665731ce", + "execution_count": 32, + "id": "4ab2467e", "metadata": { "collapsed": false, "editable": true @@ -5095,7 +3545,7 @@ }, { "cell_type": "markdown", - "id": "50bc17b7", + "id": "05126a03", "metadata": { "editable": true }, @@ -5108,7 +3558,7 @@ }, { "cell_type": "markdown", - "id": "340763a0", + "id": "7b4e9871", "metadata": { "editable": true }, @@ -5125,7 +3575,7 @@ }, { "cell_type": "markdown", - "id": "26658651", + "id": "20266e3a", "metadata": { "editable": true }, @@ -5141,7 +3591,7 @@ }, { "cell_type": "markdown", - "id": "6abebf29", + "id": "8a3f1b3d", "metadata": { "editable": true }, @@ -5154,7 +3604,7 @@ }, { "cell_type": "markdown", - "id": "a68128ae", + "id": "14dfc04b", "metadata": { "editable": true }, @@ -5171,7 +3621,7 @@ }, { "cell_type": "markdown", - "id": "b5000a32", + "id": "b125d1d3", "metadata": { "editable": true }, @@ -5183,7 +3633,7 @@ }, { "cell_type": "markdown", - "id": "306c6e46", + "id": "226a3528", "metadata": { "editable": true }, @@ -5210,7 +3660,7 @@ }, { "cell_type": "markdown", - "id": "c7d0d8c3", + "id": "adeeb731", "metadata": { "editable": true }, @@ -5222,8 +3672,8 @@ }, { "cell_type": "code", - "execution_count": 43, - "id": "a2b6af75", + "execution_count": 33, + "id": "eb3ed6d1", "metadata": { "collapsed": false, "editable": true @@ -5402,7 +3852,7 @@ }, { "cell_type": "markdown", - "id": "78241a6c", + "id": "2407df1c", "metadata": { "editable": true }, @@ -5422,7 +3872,7 @@ }, { "cell_type": "markdown", - "id": "e493bb17", + "id": "e30d9840", "metadata": { "editable": true }, @@ -5437,7 +3887,7 @@ }, { "cell_type": "markdown", - "id": "68995ee5", + "id": "4af6e338", "metadata": { "editable": true }, @@ -5451,7 +3901,7 @@ }, { "cell_type": "markdown", - "id": "f0e67441", + "id": "606cf0d3", "metadata": { "editable": true }, @@ -5467,7 +3917,7 @@ }, { "cell_type": "markdown", - "id": "b0722fa9", + "id": "3275ea67", "metadata": { "editable": true }, @@ -5477,7 +3927,7 @@ }, { "cell_type": "markdown", - "id": "6376873b", + "id": "8c36efec", "metadata": { "editable": true }, @@ -5499,7 +3949,7 @@ }, { "cell_type": "markdown", - "id": "57a0317c", + "id": "5290cde6", "metadata": { "editable": true }, @@ -5512,8 +3962,8 @@ }, { "cell_type": "code", - "execution_count": 44, - "id": "d16f77f1", + "execution_count": 34, + "id": "d5488516", "metadata": { "collapsed": false, "editable": true @@ -5589,7 +4039,7 @@ }, { "cell_type": "markdown", - "id": "e704b947", + "id": "d631641d", "metadata": { "editable": true }, @@ -5601,7 +4051,7 @@ }, { "cell_type": "markdown", - "id": "1feb358d", + "id": "3bd8043b", "metadata": { "editable": true }, @@ -5618,7 +4068,7 @@ }, { "cell_type": "markdown", - "id": "05027662", + "id": "818ac1d8", "metadata": { "editable": true }, @@ -5630,7 +4080,7 @@ }, { "cell_type": "markdown", - "id": "96d6d6a0", + "id": "894be116", "metadata": { "editable": true }, @@ -5645,7 +4095,7 @@ }, { "cell_type": "markdown", - "id": "d4dfad8a", + "id": "c2fce07f", "metadata": { "editable": true }, @@ -5657,7 +4107,7 @@ }, { "cell_type": "markdown", - "id": "ffe7eb65", + "id": "1e2ffb5e", "metadata": { "editable": true }, @@ -5669,7 +4119,7 @@ }, { "cell_type": "markdown", - "id": "2e3acb6a", + "id": "5677eb07", "metadata": { "editable": true }, @@ -5681,7 +4131,7 @@ }, { "cell_type": "markdown", - "id": "600af805", + "id": "89173815", "metadata": { "editable": true }, @@ -5691,7 +4141,7 @@ }, { "cell_type": "markdown", - "id": "3a61de1c", + "id": "f6e81c01", "metadata": { "editable": true }, @@ -5708,7 +4158,7 @@ }, { "cell_type": "markdown", - "id": "6475eda5", + "id": "82b4c100", "metadata": { "editable": true }, @@ -5720,7 +4170,7 @@ }, { "cell_type": "markdown", - "id": "4c506a87", + "id": "05574f7f", "metadata": { "editable": true }, @@ -5732,7 +4182,7 @@ }, { "cell_type": "markdown", - "id": "24701ca8", + "id": "5c17a08c", "metadata": { "editable": true }, @@ -5742,7 +4192,7 @@ }, { "cell_type": "markdown", - "id": "826b9055", + "id": "a0ce240a", "metadata": { "editable": true }, @@ -5754,7 +4204,7 @@ }, { "cell_type": "markdown", - "id": "323573be", + "id": "d90da9be", "metadata": { "editable": true }, @@ -5764,8 +4214,8 @@ }, { "cell_type": "code", - "execution_count": 45, - "id": "4234c03b", + "execution_count": 35, + "id": "ffd8b552", "metadata": { "collapsed": false, "editable": true @@ -5930,7 +4380,7 @@ }, { "cell_type": "markdown", - "id": "5f7a90b0", + "id": "2cde42e7", "metadata": { "editable": true }, @@ -5952,7 +4402,7 @@ }, { "cell_type": "markdown", - "id": "532f1254", + "id": "e24a46af", "metadata": { "editable": true }, @@ -5969,7 +4419,7 @@ }, { "cell_type": "markdown", - "id": "ece44428", + "id": "2417ec7c", "metadata": { "editable": true }, @@ -5979,7 +4429,7 @@ }, { "cell_type": "markdown", - "id": "c34e3e05", + "id": "012a9c2b", "metadata": { "editable": true }, @@ -5994,7 +4444,7 @@ }, { "cell_type": "markdown", - "id": "9186a55c", + "id": "101bccb8", "metadata": { "editable": true }, @@ -6004,7 +4454,7 @@ }, { "cell_type": "markdown", - "id": "0644e2f2", + "id": "280cdc54", "metadata": { "editable": true }, @@ -6019,7 +4469,7 @@ }, { "cell_type": "markdown", - "id": "b3bdd092", + "id": "38bc9035", "metadata": { "editable": true }, @@ -6030,7 +4480,7 @@ }, { "cell_type": "markdown", - "id": "e1e12027", + "id": "3925a117", "metadata": { "editable": true }, @@ -6050,7 +4500,7 @@ }, { "cell_type": "markdown", - "id": "334ba808", + "id": "6f86e85b", "metadata": { "editable": true }, @@ -6062,7 +4512,7 @@ }, { "cell_type": "markdown", - "id": "3e465af3", + "id": "394b14bc", "metadata": { "editable": true }, @@ -6099,7 +4549,7 @@ }, { "cell_type": "markdown", - "id": "c854491a", + "id": "5ab07ae1", "metadata": { "editable": true }, @@ -6109,7 +4559,7 @@ }, { "cell_type": "markdown", - "id": "6f5435eb", + "id": "8134c34f", "metadata": { "editable": true }, @@ -6121,8 +4571,8 @@ }, { "cell_type": "code", - "execution_count": 46, - "id": "aec3e689", + "execution_count": 36, + "id": "4362f9a9", "metadata": { "collapsed": false, "editable": true @@ -6327,7 +4777,7 @@ }, { "cell_type": "markdown", - "id": "349c11e3", + "id": "c66dc85a", "metadata": { "editable": true }, @@ -6344,7 +4794,7 @@ }, { "cell_type": "markdown", - "id": "d4adb530", + "id": "cf60d1fc", "metadata": { "editable": true }, @@ -6361,7 +4811,7 @@ }, { "cell_type": "markdown", - "id": "8b9396bf", + "id": "bff85f6e", "metadata": { "editable": true }, @@ -6371,7 +4821,7 @@ }, { "cell_type": "markdown", - "id": "059b4467", + "id": "64289867", "metadata": { "editable": true }, @@ -6386,7 +4836,7 @@ }, { "cell_type": "markdown", - "id": "5a7fcf9e", + "id": "75d3a4d2", "metadata": { "editable": true }, @@ -6400,7 +4850,7 @@ }, { "cell_type": "markdown", - "id": "df2d65c5", + "id": "6f3e695d", "metadata": { "editable": true }, @@ -6413,7 +4863,7 @@ }, { "cell_type": "markdown", - "id": "ae173d6c", + "id": "da1ba3cf", "metadata": { "editable": true }, @@ -6433,7 +4883,7 @@ }, { "cell_type": "markdown", - "id": "bdaf49ce", + "id": "373065ff", "metadata": { "editable": true }, @@ -6445,7 +4895,7 @@ }, { "cell_type": "markdown", - "id": "8fc692b7", + "id": "2281eade", "metadata": { "editable": true }, @@ -6457,7 +4907,7 @@ }, { "cell_type": "markdown", - "id": "3d9a8d27", + "id": "989a8905", "metadata": { "editable": true }, @@ -6469,7 +4919,7 @@ }, { "cell_type": "markdown", - "id": "8bb8693c", + "id": "b36367a0", "metadata": { "editable": true }, @@ -6479,7 +4929,7 @@ }, { "cell_type": "markdown", - "id": "8f12a71a", + "id": "6f6f51dd", "metadata": { "editable": true }, @@ -6491,7 +4941,7 @@ }, { "cell_type": "markdown", - "id": "92c02c54", + "id": "35bd1e4a", "metadata": { "editable": true }, @@ -6503,7 +4953,7 @@ }, { "cell_type": "markdown", - "id": "3574103a", + "id": "2b804c0a", "metadata": { "editable": true }, @@ -6515,7 +4965,7 @@ }, { "cell_type": "markdown", - "id": "0c5567ec", + "id": "07f20557", "metadata": { "editable": true }, @@ -6525,7 +4975,7 @@ }, { "cell_type": "markdown", - "id": "e239c04b", + "id": "0e14c702", "metadata": { "editable": true }, @@ -6541,7 +4991,7 @@ }, { "cell_type": "markdown", - "id": "b32c6b70", + "id": "a19c5cae", "metadata": { "editable": true }, @@ -6551,7 +5001,7 @@ }, { "cell_type": "markdown", - "id": "dfb3bad0", + "id": "de041a40", "metadata": { "editable": true }, @@ -6563,7 +5013,7 @@ }, { "cell_type": "markdown", - "id": "14519bf8", + "id": "519bb7a7", "metadata": { "editable": true }, @@ -6580,7 +5030,7 @@ }, { "cell_type": "markdown", - "id": "a0882035", + "id": "129322ea", "metadata": { "editable": true }, @@ -6590,7 +5040,7 @@ }, { "cell_type": "markdown", - "id": "bf1f5906", + "id": "ddc7b725", "metadata": { "editable": true }, @@ -6606,7 +5056,7 @@ }, { "cell_type": "markdown", - "id": "61a16dd6", + "id": "5497b34b", "metadata": { "editable": true }, @@ -6620,7 +5070,7 @@ }, { "cell_type": "markdown", - "id": "99949d7b", + "id": "0b9040e4", "metadata": { "editable": true }, @@ -6638,8 +5088,8 @@ }, { "cell_type": "code", - "execution_count": 47, - "id": "f9faf581", + "execution_count": 37, + "id": "17097802", "metadata": { "collapsed": false, "editable": true @@ -6694,7 +5144,7 @@ }, { "cell_type": "markdown", - "id": "3cbeb7ac", + "id": "a2178b56", "metadata": { "editable": true }, @@ -6724,7 +5174,7 @@ }, { "cell_type": "markdown", - "id": "04a66fd1", + "id": "533f4e84", "metadata": { "editable": true }, @@ -6752,8 +5202,8 @@ }, { "cell_type": "code", - "execution_count": 48, - "id": "83ad594f", + "execution_count": 38, + "id": "7b494481", "metadata": { "collapsed": false, "editable": true @@ -6800,7 +5250,7 @@ }, { "cell_type": "markdown", - "id": "dbe6f74a", + "id": "9f4b4939", "metadata": { "editable": true }, @@ -6825,8 +5275,8 @@ }, { "cell_type": "code", - "execution_count": 49, - "id": "a29e5348", + "execution_count": 39, + "id": "83d6eb7d", "metadata": { "collapsed": false, "editable": true @@ -7060,7 +5510,7 @@ }, { "cell_type": "markdown", - "id": "f2171b20", + "id": "ada13a48", "metadata": { "editable": true }, @@ -7072,7 +5522,7 @@ }, { "cell_type": "markdown", - "id": "e2c87638", + "id": "e4727d73", "metadata": { "editable": true }, @@ -7084,7 +5534,7 @@ }, { "cell_type": "markdown", - "id": "d8595812", + "id": "0b86d555", "metadata": { "editable": true }, @@ -7096,7 +5546,7 @@ }, { "cell_type": "markdown", - "id": "6969d557", + "id": "216948d5", "metadata": { "editable": true }, @@ -7113,7 +5563,7 @@ }, { "cell_type": "markdown", - "id": "f39d16ef", + "id": "44c25fdc", "metadata": { "editable": true }, @@ -7123,7 +5573,7 @@ }, { "cell_type": "markdown", - "id": "6c8e08dd", + "id": "98f919eb", "metadata": { "editable": true }, @@ -7135,7 +5585,7 @@ }, { "cell_type": "markdown", - "id": "699a4862", + "id": "01299767", "metadata": { "editable": true }, @@ -7152,7 +5602,7 @@ }, { "cell_type": "markdown", - "id": "3e5b810b", + "id": "556587c5", "metadata": { "editable": true }, @@ -7163,7 +5613,7 @@ }, { "cell_type": "markdown", - "id": "c3f9ac9b", + "id": "c9eb4f3a", "metadata": { "editable": true }, @@ -7183,7 +5633,7 @@ }, { "cell_type": "markdown", - "id": "56f7fba0", + "id": "63128ef6", "metadata": { "editable": true }, @@ -7193,7 +5643,7 @@ }, { "cell_type": "markdown", - "id": "2788d661", + "id": "ff568c81", "metadata": { "editable": true }, @@ -7219,7 +5669,7 @@ }, { "cell_type": "markdown", - "id": "2094e988", + "id": "7b32c8dd", "metadata": { "editable": true }, @@ -7235,7 +5685,7 @@ }, { "cell_type": "markdown", - "id": "aac9bb21", + "id": "fc33e683", "metadata": { "editable": true }, @@ -7245,8 +5695,8 @@ }, { "cell_type": "code", - "execution_count": 50, - "id": "550bea3f", + "execution_count": 40, + "id": "2f923958", "metadata": { "collapsed": false, "editable": true @@ -7477,7 +5927,7 @@ }, { "cell_type": "markdown", - "id": "80a6f6ef", + "id": "95dea76f", "metadata": { "editable": true }, diff --git a/doc/src/week43/backup2022.do.txt b/doc/src/week43/Previousversions/backup2022.do.txt similarity index 100% rename from doc/src/week43/backup2022.do.txt rename to doc/src/week43/Previousversions/backup2022.do.txt diff --git a/doc/src/week43/Previousversions/exercisesweek43.do.txt b/doc/src/week43/Previousversions/exercisesweek43.do.txt new file mode 100644 index 000000000..105d59dd8 --- /dev/null +++ b/doc/src/week43/Previousversions/exercisesweek43.do.txt @@ -0,0 +1,1284 @@ +TITLE: Exercises weeks 43 and 44 +AUTHOR: October 23-27, 2023 +DATE: Deadline is Sunday November 5 at midnight + +You can hand in the exercises from week 43 and week 44 as one exercise and get a total score of two additional points. + +======= Overarching aims of the exercises weeks 43 and 44 ======= + +The aim of the exercises this week and next week is to get started with writing a neural network code +of relevance for project 2. + + +During week 41 we discussed three different types of gates, the +so-called XOR, the OR and the AND gates. In order to develop a code +for neural networks, it can be useful to set up a simpler system with +only two inputs and one output. This can make it easier to debug and +study the feed forward pass and the back propagation part. In the +exercise this and next week, we propose to study this system with just +one hidden layer and two hidden nodes. There is only one output node +and we can choose to use either a simple regression case (fitting a +line) or just a binary classification case with the cross-entropy as +cost function. + + +Their inputs and outputs can be +summarized using the following tables, first for the OR gate with +inputs $x_1$ and $x_2$ and outputs $y$: + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 1 | +| 1 | 0 | 1 | +| 1 | 1 | 1 | +|---------------------| + +!split +===== The AND and XOR Gates ===== + +The AND gate is defined as + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 0 | +| 1 | 0 | 0 | +| 1 | 1 | 1 | +|---------------------| + +And finally we have the XOR gate + +|---------------------| +| $x_1$ | $x_2$ | $y$ | +|---------------------| +| 0 | 0 | 0 | +| 0 | 1 | 1 | +| 1 | 0 | 1 | +| 1 | 1 | 0 | +|---------------------| + +!split +===== Representing the Data Sets ===== + +Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads + +!bt +\bm{X}=\begin{bmatrix} 0 & 0 \\ + 0 & 1 \\ + 1 & 0 \\ + 1 & 1 \end{bmatrix}, +!et + +while the vector of outputs is $\bm{y}^T=[0,1,1,0]$ for the XOR gate, $\bm{y}^T=[0,0,0,1]$ for the AND gate and $\bm{y}^T=[0,1,1,1]$ for the OR gate. + + + +Your tasks here are + +o Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs. +o Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function. +o Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output. +o Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets. +o Set up the cost function (cross entropy for classification of binary cases). +o Calculate the gradients needed for the back propagation part. +o Use the gradients to train the network in the back propagation part. Think of using automatic differentiation. +o Train the network and study your results and compare with results obtained either with _scikit-learn_ or _TensorFlow_. + +Everything you develop here can be used directly into the code for the project. + + +!split +===== Setting up dimensionalities by hand ===== + +It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by +!bt +\bm{W_h}=\begin{bmatrix} 1 & 1 \\ + 1 & 1 \end{bmatrix}, +!et + +Multiplying $\bm{X}$ and $\bm{W}$ gives + +!bt +\bm{X}{W}_h=\begin{bmatrix} 0 & 0 \\ + 1 & 1 \\ + 1 & 1 \\ + 2 & 2 \end{bmatrix}, +!et +Assume also that the bias vector for the hidden layer is +!bt +\bm{b}_h=\begin{bmatrix} 0 \\ + -1\end{bmatrix}, +!et +Adding it gives us the input to the activation function of the hidden layer +!bt +\bm{z}_h=\bm{X}\bm{W}_h+\bm{b}_h=\begin{bmatrix} 0 & -1 \\ + 1 & 0 \\ + 1 & 0 \\ + 2 & 1 \end{bmatrix}, +!et + +Let us then assume that our activation function is the RELU function, which simply means that we take the max of $0$ and the elements of the input argument $\bm{z}_h$, that is we have +!bt +\bm{a}_h=\mathrm{RELU}(\bm{z}_h=\bm{X}\bm{W}_h+\bm{b}_h)=\begin{bmatrix} 0 & 0 \\ + 1 & 0 \\ + 1 & 0 \\ + 2 & 1 \end{bmatrix}, +!et +Assume also that the bias of the output layer is zero and that the weights of the output layer are +!bt +\bm{w}_o=\begin{bmatrix} 1 \\ + -2\end{bmatrix}, +!et +and multiplying with $\bm{a}_h$ gives the output +!bt +\bm{a}_o=\begin{bmatrix} 0 & 0 \\ + 1 & 0 \\ + 1 & 0 \\ + 2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\ + -2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix}, +!et +the wanted result. Pay attention to the dimensionalities as well. + + +!split +===== Setting up the Neural Network ===== + +We define first our design matrix and the various output vectors for the different gates. + +!bc pycod +""" +Simple code that tests XOR, OR and AND gates with linear regression +""" + +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + +def sigmoid(x): + return 1/(1 + np.exp(-x)) + +def feed_forward(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + probabilities = sigmoid(z_o) + return probabilities + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# Design matrix +X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) + +# The XOR gate +yXOR = np.array( [ 0, 1 ,1, 0]) +# The OR gate +yOR = np.array( [ 0, 1 ,1, 1]) +# The AND gate +yAND = np.array( [ 0, 0 ,0, 1]) + +# Defining the neural network +n_inputs, n_features = X.shape +n_hidden_neurons = 2 +n_categories = 1 +n_features = 2 + +# we make the weights normally distributed using numpy.random.randn + +# weights and bias in the hidden layer +hidden_weights = np.random.randn(n_features, n_hidden_neurons) +hidden_bias = np.zeros(n_hidden_neurons) + 0.01 + +# weights and bias in the output layer +output_weights = np.random.randn(n_hidden_neurons, n_categories) +output_bias = np.zeros(n_categories) + 0.01 + +probabilities = feed_forward(X) +print(probabilities) + +!ec + +Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above. + +!split +===== The Code using Scikit-Learn ===== + +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn.neural_network import MLPClassifier +from sklearn.metrics import accuracy_score +import seaborn as sns + +# ensure the same random numbers appear every time +np.random.seed(0) + +# Design matrix +X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) + +# The XOR gate +yXOR = np.array( [ 0, 1 ,1, 0]) +# The OR gate +yOR = np.array( [ 0, 1 ,1, 1]) +# The AND gate +yAND = np.array( [ 0, 0 ,0, 1]) + +# Defining the neural network +n_hidden_neurons = 2 + +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +epochs = 100 + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X, yXOR) + DNN_scikit[i][j] = dnn + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on data set: ", dnn.score(X, yXOR)) + print() + +sns.set() +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + dnn = DNN_scikit[i][j] + test_pred = dnn.predict(X) + test_accuracy[i][j] = accuracy_score(yXOR, test_pred) + +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() + +!ec + +!split +===== Building a neural network code ===== + +Here we present a flexible object oriented codebase +for a feed forward neural network, along with a demonstration of how +to use it. Before we get into the details of the neural network, we +will first present some implementations of various schedulers, cost +functions and activation functions that can be used together with the +neural network. + +The codes here were developed by Eric Reber and Gregor Kajda during spring 2023. + +=== Learning rate methods === + +The code below shows object oriented implementations of the Constant, +Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All +of the classes belong to the shared abstract Scheduler class, and +share the update_change() and reset() methods allowing for any of the +schedulers to be seamlessly used during the training stage, as will +later be shown in the fit() method of the neural +network. Update_change() only has one parameter, the gradient +($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted +from the weights. The reset() function takes no parameters, and resets +the desired variables. For Constant and Momentum, reset does nothing. + + +!bc pycod +import autograd.numpy as np + +class Scheduler: + """ + Abstract class for Schedulers + """ + + def __init__(self, eta): + self.eta = eta + + # should be overwritten + def update_change(self, gradient): + raise NotImplementedError + + # overwritten if needed + def reset(self): + pass + + +class Constant(Scheduler): + def __init__(self, eta): + super().__init__(eta) + + def update_change(self, gradient): + return self.eta * gradient + + def reset(self): + pass + + +class Momentum(Scheduler): + def __init__(self, eta: float, momentum: float): + super().__init__(eta) + self.momentum = momentum + self.change = 0 + + def update_change(self, gradient): + self.change = self.momentum * self.change + self.eta * gradient + return self.change + + def reset(self): + pass + + +class Adagrad(Scheduler): + def __init__(self, eta): + super().__init__(eta) + self.G_t = None + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + + if self.G_t is None: + self.G_t = np.zeros((gradient.shape[0], gradient.shape[0])) + + self.G_t += gradient @ gradient.T + + G_t_inverse = 1 / ( + delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1))) + ) + return self.eta * gradient * G_t_inverse + + def reset(self): + self.G_t = None + + +class AdagradMomentum(Scheduler): + def __init__(self, eta, momentum): + super().__init__(eta) + self.G_t = None + self.momentum = momentum + self.change = 0 + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + + if self.G_t is None: + self.G_t = np.zeros((gradient.shape[0], gradient.shape[0])) + + self.G_t += gradient @ gradient.T + + G_t_inverse = 1 / ( + delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1))) + ) + self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse + return self.change + + def reset(self): + self.G_t = None + + +class RMS_prop(Scheduler): + def __init__(self, eta, rho): + super().__init__(eta) + self.rho = rho + self.second = 0.0 + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient + return self.eta * gradient / (np.sqrt(self.second + delta)) + + def reset(self): + self.second = 0.0 + + +class Adam(Scheduler): + def __init__(self, eta, rho, rho2): + super().__init__(eta) + self.rho = rho + self.rho2 = rho2 + self.moment = 0 + self.second = 0 + self.n_epochs = 1 + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + + self.moment = self.rho * self.moment + (1 - self.rho) * gradient + self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient + + moment_corrected = self.moment / (1 - self.rho**self.n_epochs) + second_corrected = self.second / (1 - self.rho2**self.n_epochs) + + return self.eta * moment_corrected / (np.sqrt(second_corrected + delta)) + + def reset(self): + self.n_epochs += 1 + self.moment = 0 + self.second = 0 + +!ec + +=== Usage of the above learning rate schedulers === + +To initalize a scheduler, simply create the object and pass in the +necessary parameters such as the learning rate and the momentum as +shown below. As the Scheduler class is an abstract class it should not +called directly, and will raise an error upon usage. + +!bc pycod +momentum_scheduler = Momentum(eta=1e-3, momentum=0.9) +adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) +!ec + +Here is a small example for how a segment of code using schedulers +could look. Switching out the schedulers is simple. + +!bc pycod +weights = np.ones((3,3)) +print(f"Before scheduler:\n{weights=}") + +epochs = 10 +for e in range(epochs): + gradient = np.random.rand(3, 3) + change = adam_scheduler.update_change(gradient) + weights = weights - change + adam_scheduler.reset() + +print(f"\nAfter scheduler:\n{weights=}") +!ec + + +=== Cost functions === + +Here we discuss cost functions that can be used when creating the +neural network. Every cost function takes the target vector as its +parameter, and returns a function valued only at $x$ such that it may +easily be differentiated. + + +!bc pycod +import autograd.numpy as np + +def CostOLS(target): + + def func(X): + return (1.0 / target.shape[0]) * np.sum((target - X) ** 2) + + return func + + +def CostLogReg(target): + + def func(X): + + return -(1.0 / target.shape[0]) * np.sum( + (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10)) + ) + + return func + + +def CostCrossEntropy(target): + + def func(X): + return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10)) + + return func +!ec + + +Below we give a short example of how these cost function may be used +to obtain results if you wish to test them out on your own using +AutoGrad's automatics differentiation. + +!bc pycod +from autograd import grad + +target = np.array([[1, 2, 3]]).T +a = np.array([[4, 5, 6]]).T + +cost_func = CostCrossEntropy +cost_func_derivative = grad(cost_func(target)) + +valued_at_a = cost_func_derivative(a) +print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}") +!ec + + +=== Activation functions === + +Finally, before we look at the neural network, we will look at the +activation functions which can be specified between the hidden layers +and as the output function. Each function can be valued for any given +vector or matrix X, and can be differentiated via derivate(). + +!bc pycod +import autograd.numpy as np +from autograd import elementwise_grad + +def identity(X): + return X + + +def sigmoid(X): + try: + return 1.0 / (1 + np.exp(-X)) + except FloatingPointError: + return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape)) + + +def softmax(X): + X = X - np.max(X, axis=-1, keepdims=True) + delta = 10e-10 + return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta) + + +def RELU(X): + return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape)) + + +def LRELU(X): + delta = 10e-4 + return np.where(X > np.zeros(X.shape), X, delta * X) + + +def derivate(func): + if func.__name__ == "RELU": + + def func(X): + return np.where(X > 0, 1, 0) + + return func + + elif func.__name__ == "LRELU": + + def func(X): + delta = 10e-4 + return np.where(X > 0, 1, delta) + + return func + + else: + return elementwise_grad(func) +!ec + +Below follows a short demonstration of how to use an activation +function. The derivative of the activation function will be important +when calculating the output delta term during backpropagation. Note +that derivate() can also be used for cost functions for a more +generalized approach. + +!bc pycod +z = np.array([[4, 5, 6]]).T +print(f"Input to activation function:\n{z}") + +act_func = sigmoid +a = act_func(z) +print(f"\nOutput from {act_func.__name__} activation function:\n{a}") + +act_func_derivative = derivate(act_func) +valued_at_z = act_func_derivative(a) +print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}") +!ec + +=== The Neural Network === + +Now that we have gotten a good understanding of the implementation of +some important components, we can take a look at an object oriented +implementation of a feed forward neural network. The feed forward +neural network has been implemented as a class named FFNN, which can +be initiated as a regressor or classifier dependant on the choice of +cost function. The FFNN can have any number of input nodes, hidden +layers with any amount of hidden nodes, and any amount of output nodes +meaning it can perform multiclass classification as well as binary +classification and regression problems. Although there is a lot of +code present, it makes for an easy to use and generalizeable interface +for creating many types of neural networks as will be demonstrated +below. + +!bc pycod +import math +import autograd.numpy as np +import sys +import warnings +from autograd import grad, elementwise_grad +from random import random, seed +from copy import deepcopy, copy +from typing import Tuple, Callable +from sklearn.utils import resample + +warnings.simplefilter("error") + + +class FFNN: + """ + Description: + ------------ + Feed Forward Neural Network with interface enabling flexible design of a + nerual networks architecture and the specification of activation function + in the hidden layers and output layer respectively. This model can be used + for both regression and classification problems, depending on the output function. + + Attributes: + ------------ + I dimensions (tuple[int]): A list of positive integers, which specifies the + number of nodes in each of the networks layers. The first integer in the array + defines the number of nodes in the input layer, the second integer defines number + of nodes in the first hidden layer and so on until the last number, which + specifies the number of nodes in the output layer. + II hidden_func (Callable): The activation function for the hidden layers + III output_func (Callable): The activation function for the output layer + IV cost_func (Callable): Our cost function + V seed (int): Sets random seed, makes results reproducible + """ + + def __init__( + self, + dimensions: tuple[int], + hidden_func: Callable = sigmoid, + output_func: Callable = lambda x: x, + cost_func: Callable = CostOLS, + seed: int = None, + ): + self.dimensions = dimensions + self.hidden_func = hidden_func + self.output_func = output_func + self.cost_func = cost_func + self.seed = seed + self.weights = list() + self.schedulers_weight = list() + self.schedulers_bias = list() + self.a_matrices = list() + self.z_matrices = list() + self.classification = None + + self.reset_weights() + self._set_classification() + + def fit( + self, + X: np.ndarray, + t: np.ndarray, + scheduler: Scheduler, + batches: int = 1, + epochs: int = 100, + lam: float = 0, + X_val: np.ndarray = None, + t_val: np.ndarray = None, + ): + """ + Description: + ------------ + This function performs the training the neural network by performing the feedforward and backpropagation + algorithm to update the networks weights. + + Parameters: + ------------ + I X (np.ndarray) : training data + II t (np.ndarray) : target data + III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent) + IV scheduler_args (list[int]) : list of all arguments necessary for scheduler + + Optional Parameters: + ------------ + V batches (int) : number of batches the datasets are split into, default equal to 1 + VI epochs (int) : number of iterations used to train the network, default equal to 100 + VII lam (float) : regularization hyperparameter lambda + VIII X_val (np.ndarray) : validation set + IX t_val (np.ndarray) : validation target set + + Returns: + ------------ + I scores (dict) : A dictionary containing the performance metrics of the model. + The number of the metrics depends on the parameters passed to the fit-function. + + """ + + # setup + if self.seed is not None: + np.random.seed(self.seed) + + val_set = False + if X_val is not None and t_val is not None: + val_set = True + + # creating arrays for score metrics + train_errors = np.empty(epochs) + train_errors.fill(np.nan) + val_errors = np.empty(epochs) + val_errors.fill(np.nan) + + train_accs = np.empty(epochs) + train_accs.fill(np.nan) + val_accs = np.empty(epochs) + val_accs.fill(np.nan) + + self.schedulers_weight = list() + self.schedulers_bias = list() + + batch_size = X.shape[0] // batches + + X, t = resample(X, t) + + # this function returns a function valued only at X + cost_function_train = self.cost_func(t) + if val_set: + cost_function_val = self.cost_func(t_val) + + # create schedulers for each weight matrix + for i in range(len(self.weights)): + self.schedulers_weight.append(copy(scheduler)) + self.schedulers_bias.append(copy(scheduler)) + + print(f"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}") + + try: + for e in range(epochs): + for i in range(batches): + # allows for minibatch gradient descent + if i == batches - 1: + # If the for loop has reached the last batch, take all thats left + X_batch = X[i * batch_size :, :] + t_batch = t[i * batch_size :, :] + else: + X_batch = X[i * batch_size : (i + 1) * batch_size, :] + t_batch = t[i * batch_size : (i + 1) * batch_size, :] + + self._feedforward(X_batch) + self._backpropagate(X_batch, t_batch, lam) + + # reset schedulers for each epoch (some schedulers pass in this call) + for scheduler in self.schedulers_weight: + scheduler.reset() + + for scheduler in self.schedulers_bias: + scheduler.reset() + + # computing performance metrics + pred_train = self.predict(X) + train_error = cost_function_train(pred_train) + + train_errors[e] = train_error + if val_set: + + pred_val = self.predict(X_val) + val_error = cost_function_val(pred_val) + val_errors[e] = val_error + + if self.classification: + train_acc = self._accuracy(self.predict(X), t) + train_accs[e] = train_acc + if val_set: + val_acc = self._accuracy(pred_val, t_val) + val_accs[e] = val_acc + + # printing progress bar + progression = e / epochs + print_length = self._progress_bar( + progression, + train_error=train_errors[e], + train_acc=train_accs[e], + val_error=val_errors[e], + val_acc=val_accs[e], + ) + except KeyboardInterrupt: + # allows for stopping training at any point and seeing the result + pass + + # visualization of training progression (similiar to tensorflow progression bar) + sys.stdout.write("\r" + " " * print_length) + sys.stdout.flush() + self._progress_bar( + 1, + train_error=train_errors[e], + train_acc=train_accs[e], + val_error=val_errors[e], + val_acc=val_accs[e], + ) + sys.stdout.write("") + + # return performance metrics for the entire run + scores = dict() + + scores["train_errors"] = train_errors + + if val_set: + scores["val_errors"] = val_errors + + if self.classification: + scores["train_accs"] = train_accs + + if val_set: + scores["val_accs"] = val_accs + + return scores + + def predict(self, X: np.ndarray, *, threshold=0.5): + """ + Description: + ------------ + Performs prediction after training of the network has been finished. + + Parameters: + ------------ + I X (np.ndarray): The design matrix, with n rows of p features each + + Optional Parameters: + ------------ + II threshold (float) : sets minimal value for a prediction to be predicted as the positive class + in classification problems + + Returns: + ------------ + I z (np.ndarray): A prediction vector (row) for each row in our design matrix + This vector is thresholded if regression=False, meaning that classification results + in a vector of 1s and 0s, while regressions in an array of decimal numbers + + """ + + predict = self._feedforward(X) + + if self.classification: + return np.where(predict > threshold, 1, 0) + else: + return predict + + def reset_weights(self): + """ + Description: + ------------ + Resets/Reinitializes the weights in order to train the network for a new problem. + + """ + if self.seed is not None: + np.random.seed(self.seed) + + self.weights = list() + for i in range(len(self.dimensions) - 1): + weight_array = np.random.randn( + self.dimensions[i] + 1, self.dimensions[i + 1] + ) + weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01 + + self.weights.append(weight_array) + + def _feedforward(self, X: np.ndarray): + """ + Description: + ------------ + Calculates the activation of each layer starting at the input and ending at the output. + Each following activation is calculated from a weighted sum of each of the preceeding + activations (except in the case of the input layer). + + Parameters: + ------------ + I X (np.ndarray): The design matrix, with n rows of p features each + + Returns: + ------------ + I z (np.ndarray): A prediction vector (row) for each row in our design matrix + """ + + # reset matrices + self.a_matrices = list() + self.z_matrices = list() + + # if X is just a vector, make it into a matrix + if len(X.shape) == 1: + X = X.reshape((1, X.shape[0])) + + # Add a coloumn of zeros as the first coloumn of the design matrix, in order + # to add bias to our data + bias = np.ones((X.shape[0], 1)) * 0.01 + X = np.hstack([bias, X]) + + # a^0, the nodes in the input layer (one a^0 for each row in X - where the + # exponent indicates layer number). + a = X + self.a_matrices.append(a) + self.z_matrices.append(a) + + # The feed forward algorithm + for i in range(len(self.weights)): + if i < len(self.weights) - 1: + z = a @ self.weights[i] + self.z_matrices.append(z) + a = self.hidden_func(z) + # bias column again added to the data here + bias = np.ones((a.shape[0], 1)) * 0.01 + a = np.hstack([bias, a]) + self.a_matrices.append(a) + else: + try: + # a^L, the nodes in our output layers + z = a @ self.weights[i] + a = self.output_func(z) + self.a_matrices.append(a) + self.z_matrices.append(z) + except Exception as OverflowError: + print( + "OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling" + ) + + # this will be a^L + return a + + def _backpropagate(self, X, t, lam): + """ + Description: + ------------ + Performs the backpropagation algorithm. In other words, this method + calculates the gradient of all the layers starting at the + output layer, and moving from right to left accumulates the gradient until + the input layer is reached. Each layers respective weights are updated while + the algorithm propagates backwards from the output layer (auto-differentation in reverse mode). + + Parameters: + ------------ + I X (np.ndarray): The design matrix, with n rows of p features each. + II t (np.ndarray): The target vector, with n rows of p targets. + III lam (float32): regularization parameter used to punish the weights in case of overfitting + + Returns: + ------------ + No return value. + + """ + out_derivative = derivate(self.output_func) + hidden_derivative = derivate(self.hidden_func) + + for i in range(len(self.weights) - 1, -1, -1): + # delta terms for output + if i == len(self.weights) - 1: + # for multi-class classification + if ( + self.output_func.__name__ == "softmax" + ): + delta_matrix = self.a_matrices[i + 1] - t + # for single class classification + else: + cost_func_derivative = grad(self.cost_func(t)) + delta_matrix = out_derivative( + self.z_matrices[i + 1] + ) * cost_func_derivative(self.a_matrices[i + 1]) + + # delta terms for hidden layer + else: + delta_matrix = ( + self.weights[i + 1][1:, :] @ delta_matrix.T + ).T * hidden_derivative(self.z_matrices[i + 1]) + + # calculate gradient + gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix + gradient_bias = np.sum(delta_matrix, axis=0).reshape( + 1, delta_matrix.shape[1] + ) + + # regularization term + gradient_weights += self.weights[i][1:, :] * lam + + # use scheduler + update_matrix = np.vstack( + [ + self.schedulers_bias[i].update_change(gradient_bias), + self.schedulers_weight[i].update_change(gradient_weights), + ] + ) + + # update weights and bias + self.weights[i] -= update_matrix + + def _accuracy(self, prediction: np.ndarray, target: np.ndarray): + """ + Description: + ------------ + Calculates accuracy of given prediction to target + + Parameters: + ------------ + I prediction (np.ndarray): vector of predicitons output network + (1s and 0s in case of classification, and real numbers in case of regression) + II target (np.ndarray): vector of true values (What the network ideally should predict) + + Returns: + ------------ + A floating point number representing the percentage of correctly classified instances. + """ + assert prediction.size == target.size + return np.average((target == prediction)) + def _set_classification(self): + """ + Description: + ------------ + Decides if FFNN acts as classifier (True) og regressor (False), + sets self.classification during init() + """ + self.classification = False + if ( + self.cost_func.__name__ == "CostLogReg" + or self.cost_func.__name__ == "CostCrossEntropy" + ): + self.classification = True + + def _progress_bar(self, progression, **kwargs): + """ + Description: + ------------ + Displays progress of training + """ + print_length = 40 + num_equals = int(progression * print_length) + num_not = print_length - num_equals + arrow = ">" if num_equals > 0 else "" + bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]" + perc_print = self._format(progression * 100, decimals=5) + line = f" {bar} {perc_print}% " + + for key in kwargs: + if not np.isnan(kwargs[key]): + value = self._format(kwargs[key], decimals=4) + line += f"| {key}: {value} " + sys.stdout.write("\r" + line) + sys.stdout.flush() + return len(line) + + def _format(self, value, decimals=4): + """ + Description: + ------------ + Formats decimal numbers for progress bar + """ + if value > 0: + v = value + elif value < 0: + v = -10 * value + else: + v = 1 + n = 1 + math.floor(math.log10(v)) + if n >= decimals - 1: + return str(round(value)) + return f"{value:.{decimals-n-1}f}" +!ec + +Before we make a model, we will quickly generate a dataset we can use +for our linear regression problem as shown below + +!bc pycod +import autograd.numpy as np +from sklearn.model_selection import train_test_split + +def SkrankeFunction(x, y): + return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2) + +def create_X(x, y, n): + if len(x.shape) > 1: + x = np.ravel(x) + y = np.ravel(y) + + N = len(x) + l = int((n + 1) * (n + 2) / 2) # Number of elements in beta + X = np.ones((N, l)) + + for i in range(1, n + 1): + q = int((i) * (i + 1) / 2) + for k in range(i + 1): + X[:, q + k] = (x ** (i - k)) * (y**k) + + return X + +step=0.5 +x = np.arange(0, 1, step) +y = np.arange(0, 1, step) +x, y = np.meshgrid(x, y) +target = SkrankeFunction(x, y) +target = target.reshape(target.shape[0], 1) + +poly_degree=3 +X = create_X(x, y, poly_degree) + +X_train, X_test, t_train, t_test = train_test_split(X, target) + +!ec + +Now that we have our dataset ready for the regression, we can create +our regressor. Note that with the seed parameter, we can make sure our +results stay the same every time we run the neural network. For +inititialization, we simply specify the dimensions (we wish the amount +of input nodes to be equal to the datapoints, and the output to +predict one value). + + +!bc pycod +input_nodes = X_train.shape[1] +output_nodes = 1 + +linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023) + +!ec + +We then fit our model with our training data using the scheduler of our choice. + +!bc pycod +linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Constant(eta=1e-3) +scores = linear_regression.fit(X_train, t_train, scheduler) + + +!ec + +Due to the progress bar we can see the MSE (train_error) throughout +the FFNN's training. Note that the fit() function has some optional +parameters with defualt arguments. For example, the regularization +hyperparameter can be left ignored if not needed, and equally the FFNN +will by default run for 100 epochs. These can easily be changed, such +as for example: + +!bc pycod +linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000) + +!ec + +We see that given more epochs to train on, the regressor reaches a lower MSE. + +Let us then switch to a binary classification. We use a binary +classification dataset, and follow a similar setup to the regression +case. + + + +!bc pycod +from sklearn.datasets import load_breast_cancer +from sklearn.preprocessing import MinMaxScaler + +wisconsin = load_breast_cancer() +X = wisconsin.data +target = wisconsin.target +target = target.reshape(target.shape[0], 1) + +X_train, X_val, t_train, t_val = train_test_split(X, target) + +scaler = MinMaxScaler() +scaler.fit(X_train) +X_train = scaler.transform(X_train) +X_val = scaler.transform(X_val) + + +!ec + +!bc pycod +input_nodes = X_train.shape[1] +output_nodes = 1 + +logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023) + +!ec + +We will now make use of our validation data by passing it into our fit function as a keyword argument + +!bc pycod +logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) +scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val) + + +!ec + +Finally, we will create a neural network with 2 hidden layers with activation functions. +!bc pycod +input_nodes = X_train.shape[1] +hidden_nodes1 = 100 +hidden_nodes2 = 30 +output_nodes = 1 + +dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes) + +neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023) + + +!ec + +!bc pycod +neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999) +scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val) + +!ec + +=== Multiclass classification === + +Finally, we will demonstrate the use case of multiclass classification +using our FFNN with the famous MNIST dataset, which contain images of +digits between the range of 0 to 9. + + +!bc pycod +from sklearn.datasets import load_digits + +def onehot(target: np.ndarray): + onehot = np.zeros((target.size, target.max() + 1)) + onehot[np.arange(target.size), target] = 1 + return onehot + +digits = load_digits() + +X = digits.data +target = digits.target +target = onehot(target) + +input_nodes = 64 +hidden_nodes1 = 100 +hidden_nodes2 = 30 +output_nodes = 10 + +dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes) + +multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy) + +multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999) +scores = multiclass.fit(X, target, scheduler, epochs=1000) + +!ec + + + +!split +===== Testing the XOR gate and other gates ===== + +Let us now use our code to test the XOR gate. + +!bc pycod +X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) + +# The XOR gate +yXOR = np.array( [[ 0], [1] ,[1], [0]]) + +input_nodes = X.shape[1] +output_nodes = 1 + +logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023) +logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights +scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999) +scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000) +!ec +Not bad, but the results depend strongly on the learning reate. Try different learning rates. diff --git a/doc/src/week43/version2021.do.txt b/doc/src/week43/Previousversions/version2021.do.txt similarity index 100% rename from doc/src/week43/version2021.do.txt rename to doc/src/week43/Previousversions/version2021.do.txt diff --git a/doc/src/week43/Previousversions/week43.do.txt b/doc/src/week43/Previousversions/week43.do.txt new file mode 100644 index 000000000..4fb97b4f8 --- /dev/null +++ b/doc/src/week43/Previousversions/week43.do.txt @@ -0,0 +1,5076 @@ +TITLE: Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo, Norway +DATE: October 20, 2025 + +!split +===== Plans for week 43 ===== + +!bblock Material for the lecture on Monday October 20, 2025 + * Building our own Feed-forward Neural Network with intro to Tensorflow + * Solving differential equations with Neural Networks +# * Video of lecture at URL:"https://youtu.be/vkBNTn-MLqs" +# * Video os second part, solving differential equations with neural networks at URL:"https://youtu.be/2N8To65I2wQ" +# * Whiteboard notes on solving differential equations at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOct21.pdf" +!eblock + + + +!split +===== Exercises and lab session week 43 ===== +!bblock Lab sessions on Tuesday and Wednesday + * Exercise on writing your own neural network code + * The exercises this week will be continued next week as well + * Discussion of project 2 +!eblock + + + +!split +===== Mathematics of deep learning ===== + +!bblock Two recent books online +o The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen at URL:"https://arxiv.org/abs/2105.04026", published as "Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022":"https://doi.org/10.1017/9781009025096.002" + +o Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger at URL:"https://doi.org/10.48550/arXiv.2310.20360" +!eblock + + +!split +===== Reminder on books with hands-on material and codes ===== +!bblock +* Sebastian Rashcka et al, Machine learning with Scikit-Learn and PyTorch at URL:"https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" +!eblock + + +!split +===== Reading recommendations ===== + +o Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub site at URL:"https://github.com/rasbt/machine-learning-book". See also chapters 12 and 13 on using Pytorch to make a Neural network code. +o Goodfellow et al, chapter 6 and 7 contain most of the neural network background. + + +!split +===== Using Automatic differentiation ===== + +In our discussions of ordinary differential equations and neural network codes +we will also study the usage of Autograd, see for example URL:"https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from "week 39":"https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html" and the Autograd documentation at URL:"https://github.com/HIPS/autograd". + + +!split +===== Back propagation and automatic differentiation ===== + +For more details on the back propagation algorithm and automatic differentiation see +o URL:"https://www.jmlr.org/papers/volume18/17-468/17-468.pdf" +o URL:"https://deepimaging.github.io/lectures/lecture_11_Backpropagation.pdf" +o Slides 12-44 at URL:"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf" + + + +!split +===== Lecture Monday October 21 ===== + + +!split +===== Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations ===== +This is a reminder from where we ended last week. + +!bblock The architecture (our model) +o Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays) +o Define the number of hidden layers and hidden nodes +o Define activation functions for hidden layers and output layers +o Define optimizer (plan learning rate, momentum, ADAgrad, RMSprop, ADAM etc) and array of initial learning rates +o Define cost function and possible regularization terms with hyperparameters +o Initialize weights and biases +o Fix number of iterations for the feed forward part and back propagation part +!eblock + +!split +===== Setting up the back propagation algorithm, part 1 ===== + +Let us write this out in the form of an algorithm. + +_First_, we set up the input data $\bm{x}$ and the activations +$\bm{z}_1$ of the input layer and compute the activation function and +the pertinent outputs $\bm{a}^1$. + +_Secondly_, we perform then the feed forward till we reach the output +layer and compute all $\bm{z}_l$ of the input layer and compute the +activation function and the pertinent outputs $\bm{a}^l$ for +$l=1,2,3,\dots,L$. + + +_Notation_: The first hidden layer has $l=1$ as label and the final output layer has $l=L$. + +!split +===== Setting up the back propagation algorithm, part 2 ===== + + +Thereafter we compute the ouput error $\bm{\delta}^L$ by computing all +!bt +\[ +\delta_j^L = \sigma'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. +\] +!et + +Then we compute the back propagate error for each $l=L-1,L-2,\dots,1$ as +!bt +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l). +\] +!et + +!split +===== Setting up the Back propagation algorithm, part 3 ===== + + +Finally, we update the weights and the biases using gradient descent +for each $l=L-1,L-2,\dots,1$ (the first hidden layer) and update the weights and biases +according to the rules + +!bt +\[ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +\] +!et + +!bt +\[ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +\] +!et +with $\eta$ being the learning rate. + +!split +===== Updating the gradients ===== + +With the back propagate error for each $l=L-1,L-2,\dots,1$ as +!bt +\[ +\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}\sigma'(z_j^l), +\] +!et +we update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,1$ and update the weights and biases according to the rules +!bt +\[ +w_{ij}^l\leftarrow = w_{ij}^l- \eta \delta_j^la_i^{l-1}, +\] +!et + +!bt +\[ +b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, +\] +!et + + + +!split +===== Activation functions ===== + + +A property that characterizes a neural network, other than its +connectivity, is the choice of activation function(s). The following +restrictions are imposed on an activation function for an FFNN to +fulfill the universal approximation theorem + + * Non-constant + + * Bounded + + * Monotonically-increasing + + * Continuous + +!split +=== Activation functions, examples === + +Typical examples are the logistic *Sigmoid* + +!bt +\[ + \sigma(x) = \frac{1}{1 + e^{-x}}, +\] +!et +and the *hyperbolic tangent* function +!bt +\[ + \sigma(x) = \tanh(x) +\] +!et + + +!split +===== The RELU function family ===== + +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. + +In some cases, you may find that half of your network’s neurons are +dead, especially if you used a large learning rate. During training, +if a neuron’s weights get updated such that the weighted sum of the +neuron’s inputs is negative, it will start outputting 0. When this +happen, the neuron is unlikely to come back to life since the gradient +of the ReLU function is 0 when its input is negative. + +!split +===== ELU function ===== + +To solve this problem, nowadays practitioners use a variant of the +ReLU function, such as the leaky ReLU discussed above or the so-called +exponential linear unit (ELU) function + + +!bt +\[ +ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. +\] +!et + +!split +===== Which activation function should we use? ===== + +In general it seems that the ELU activation function is better than +the leaky ReLU function (and its variants), which is better than +ReLU. ReLU performs better than $\tanh$ which in turn performs better +than the logistic function. + +If runtime performance is an issue, then you may opt for the leaky +ReLU function over the ELU function If you don’t want to tweak yet +another hyperparameter, you may just use the default $\alpha$ of +$0.01$ for the leaky ReLU, and $1$ for ELU. If you have spare time and +computing power, you can use cross-validation or bootstrap to evaluate +other activation functions. + + +!split +===== More on activation functions, output layers ===== + +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. + +_For the output layer:_ + +* 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. + + + + +!split +===== Setting up a Multi-layer perceptron model for classification ===== + +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 +regression. The cross-entropy defines our cost function for the +classificaton problems with neural networks. + +In binary classification with two classes $(0, 1)$ we define the +logistic/sigmoid function as the probability that a particular input +is in class $0$ or $1$. This is possible because the logistic +function takes any input from the real numbers and inputs a number +between 0 and 1, and can therefore be interpreted as a probability. It +also has other nice properties, such as a derivative that is simple to +calculate. + +For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$ +is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$ +represents our activation values $z$. We have +!bt +\[ +P(y = 0 \mid \bm{x}, \bm{\theta}) = \frac{1}{1 + \exp{(- \bm{x}})} , +\] +!et +and +!bt +\[ +P(y = 1 \mid \bm{x}, \bm{\theta}) = 1 - P(y = 0 \mid \bm{x}, \bm{\theta}) , +\] +!et + +where $y \in \{0, 1\}$ and $\bm{\theta}$ represents the weights and biases +of our network. + + +!split +===== Defining the cost function ===== + +Our cost function is given as (see the Logistic regression lectures) +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \ln P(\mathcal{D} \mid \bm{\theta}) = - \sum_{i=1}^n +y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\bm{\theta}) . +\] +!et + +This last equality means that we can interpret our *cost* function as a sum over the *loss* function +for each point in the dataset $\mathcal{L}_i(\bm{\theta})$. +The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather +than maximizing a negative number. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and + + +$y = 1 \quad \rightarrow \quad \bm{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 $\bm{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th +output vector $\bm{y}_i$. +The probability of $\bm{x}_i$ being in class $c$ will be given by the softmax function: + +!bt +\[ +P(y_{ic} = 1 \mid \bm{x}_i, \bm{\theta}) = \frac{\exp{((\bm{a}_i^{hidden})^T \bm{w}_c)}} +{\sum_{c'=0}^{C-1} \exp{((\bm{a}_i^{hidden})^T \bm{w}_{c'})}} , +\] +!et + +which reduces to the logistic function in the binary case. +The likelihood of this $C$-class classifier +is now given as: + +!bt +\[ +P(\mathcal{D} \mid \bm{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . +\] +!et +Again we take the negative log-likelihood to define our cost function: + +!bt +\[ +\mathcal{C}(\bm{\theta}) = - \log{P(\mathcal{D} \mid \bm{\theta})}. +\] +!et +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! + +!split +===== 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 +!bt +\[ +\mathcal{C}(\bm{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\bm{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\bm{\beta})}\right), +\] +!et +where we had defined the logistic (sigmoid) function +!bt +\[ +p(y_i =1\vert x_i,\bm{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, +\] +!et +and +!bt +\[ +p(y_i =0\vert x_i,\bm{\beta})=1-p(y_i =1\vert x_i,\bm{\beta}). +\] +!et +The parameters $\bm{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. + +Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. +We have then +!bt +\[ +a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, +\] +!et +with +!bt +\[ +z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, +\] +!et +where the superscript $l-1$ indicates that these are the outputs from layer $l-1$. +Our cost function at the final layer $l=L$ is now +!bt +\[ +\mathcal{C}(\bm{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), +\] +!et +where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get +!bt +\[ +\frac{\partial \mathcal{C}(\bm{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. +\] +!et +In case we use another activation function than the logistic one, we need to evaluate other derivatives. + + +!split +===== 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 +!bt +\[ +\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = +\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. +\] +!et +For the Softmax function we have +!bt +\[ +f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. +\] +!et +Its derivative with respect to $z_j^l$ gives +!bt +\[ +\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), +\] +!et +which in case of the simply binary model reduces to having $i=j$. + +!split +===== 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: + +o Collect and pre-process data +o Define model and architecture +o Choose cost function and optimizer +o Train the model +o Evaluate model performance on test data +o Adjust hyperparameters (if necessary, network architecture) + +!split +===== Collect and pre-process data ===== + +Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ +package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". +The *MNIST* (Modified National Institute of Standards and Technology) database is a large database +of handwritten digits that is commonly used for training various image processing systems. +The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each labeled from 0 to 9. +The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. + +To feed data into a feed-forward neural network we need to represent +the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each +row represents an *input*, in this case a handwritten digit, and +each column represents a *feature*, in this case a pixel. The +correct answers, also known as *labels* or *targets* are +represented as a 1D array of integers +$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. + +As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from +measurements of height (in m) +and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: + +$$ X = \begin{bmatrix} +1.85 & 81\\ +1.71 & 65\\ +1.95 & 103\\ +1.55 & 42\\ +1.63 & 56 +\end{bmatrix} ,$$ + +and the targets would be: + +$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ + +Since each input image is a 2D matrix, we need to flatten the image +(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a +design/feature matrix. This means we lose all spatial information in the +image, such as locality and translational invariance. More complicated +architectures such as Convolutional Neural Networks can take advantage +of such information, and are most commonly applied when analyzing +images. + + +!bc pycod +# 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 +%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 + +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# flatten the image +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 +n_inputs = len(inputs) +inputs = inputs.reshape(n_inputs, -1) +print("X = (n_inputs, n_features) = " + str(inputs.shape)) + + +# choose some random images to display +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() +!ec + +!split +===== Train and test datasets ===== + +Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. + +We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. + +It is important that the train and test datasets are drawn randomly from our dataset, to ensure +no bias in the sampling. +Say you are taking measurements of weather data to predict the weather in the coming 5 days. +You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data +collected from 12.00 to 24.00. + + +!bc pycod +from sklearn.model_selection import train_test_split + +# 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) + +# equivalently in numpy +def train_test_split_numpy(inputs, labels, train_size, test_size): + n_inputs = len(inputs) + inputs_shuffled = inputs.copy() + labels_shuffled = labels.copy() + + np.random.shuffle(inputs_shuffled) + np.random.shuffle(labels_shuffled) + + train_end = int(n_inputs*train_size) + X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] + Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] + + return X_train, X_test, Y_train, Y_test + +#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) + +print("Number of training images: " + str(len(X_train))) +print("Number of test images: " + str(len(X_test))) +!ec + +!split +===== Define model and architecture ===== + +Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have + +$$ z = \sum_{i=1}^n w_i a_i ,$$ + +$$ y = f(z) ,$$ + +where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer +and $w_i$ is the weight to input $i$. +The activation of the neurons in the input layer is just the features (e.g. a pixel value). + +The simplest activation function for a neuron is the *Heaviside* function: + +$$ f(z) = +\begin{cases} +1, & z > 0\\ +0, & \text{otherwise} +\end{cases} +$$ + +A feed-forward neural network with this activation is known as a *perceptron*. +For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. +This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), +and we call these architectures *multiclass perceptrons*. + +However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and +Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. + +Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). +We will be using the sigmoid function $\sigma(x)$: + +$$ 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. + +!split +===== Layers ===== + +* Input +Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. + +* Hidden layer +We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. +Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. + +* Output +If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, +which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. + +For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. + +Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: + +$$ P(\text{class $j$} \mid \text{input $\bm{a}$}) = \frac{\exp{(\bm{a}^T \bm{w}_j)}} +{\sum_{c=0}^{9} \exp{(\bm{a}^T \bm{w}_c)}} ,$$ + +i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\bm{a}$, with $\bm{w}_j$ the weights of neuron $j$ to the inputs. +The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. +The exponent is just the weighted sum of inputs as before: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ + +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. + +!split +===== Weights and biases ===== + +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. + +Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range +of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: + +$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ + +The bias weights $\bm{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. +!bc pycod +# building our neural network + +n_inputs, n_features = X_train.shape +n_hidden_neurons = 50 +n_categories = 10 + +# we make the weights normally distributed using numpy.random.randn + +# weights and bias in the hidden layer +hidden_weights = np.random.randn(n_features, n_hidden_neurons) +hidden_bias = np.zeros(n_hidden_neurons) + 0.01 + +# weights and bias in the output layer +output_weights = np.random.randn(n_hidden_neurons, n_categories) +output_bias = np.zeros(n_categories) + 0.01 +!ec + +!split +===== Feed-forward pass ===== + +Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. +For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: + +$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ + +this is then passed through our activation function + +$$ a_{j}^{l} = f(z_{j}^{l}) .$$ + +We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: + +$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ + +Finally we calculate the output of neuron $j$ in the output layer using the softmax function: + +$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} +{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ + +!split +===== Matrix multiplications ===== + +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})$, +we can easily feed the network all our training data in one go by taking the matrix product + +$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ + +and obtain a matrix that holds the weighted sum of inputs to the hidden layer +for each input image and each hidden neuron. +We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: + +$$ \bm{z}^{l} = \bm{X} \bm{W}^{l} + \bm{b}^{l} ,$$ + +meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. +This is then passed through the activation: + +$$ \bm{a}^{l} = f(\bm{z}^l) .$$ + +This is fed to the output layer: + +$$ \bm{z}^{L} = \bm{a}^{L} \bm{W}^{L} + \bm{b}^{L} .$$ + +Finally we receive our output values for each image and each category by passing it through the softmax function: + +$$ output = softmax (\bm{z}^{L}) = (n_{inputs}, n_{categories}) .$$ + + +!bc pycod +# setup the feed-forward pass, subscript h = hidden layer + +def sigmoid(x): + return 1/(1 + np.exp(-x)) + +def feed_forward(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + return probabilities + +probabilities = feed_forward(X_train) +print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) +print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) +print("probabilities sum up to: " + str(probabilities[0].sum())) +print() + +# we obtain a prediction by taking the class with the highest likelihood +def predict(X): + probabilities = feed_forward(X) + return np.argmax(probabilities, axis=1) + +predictions = predict(X_train) +print("predictions = (n_inputs) = " + str(predictions.shape)) +print("prediction for image 0: " + str(predictions[0])) +print("correct label for image 0: " + str(Y_train[0])) +!ec + +!split +===== Choose cost function and optimizer ===== + +To measure how well our neural network is doing we need to introduce a cost function. +We will call the function that gives the error of a single sample output the *loss* function, and the function +that gives the total error of our network across all samples the *cost* function. +A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. + +In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: + +$$ y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ + + +$$ y = 1 \quad \rightarrow \quad \bm{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. +We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\bm{x}_i$ in the dataset. + +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 $\bm{\theta}$ represents the parameters of our network, i.e. all the weights and biases. + + +!split +===== 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 +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 *local* minimum of the cost function. +Each parameter $\theta$ is iteratively adjusted according to the rule + +$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ + +where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. +This update can be repeated for any number of iterations, or until we are satisfied with the result. + +A simple and effective improvement is a variant called *Batch Gradient Descent*. +Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient +on a subset of the data called a *minibatch*. +If there are $N$ data points and we have a minibatch size of $M$, the total number of batches +is $N/M$. +We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: + +$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ + +i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. + +This has two important benefits: +o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. +o 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". + +!split +===== Regularization ===== + +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. +Constraining the size of the weights means that the weights cannot +grow arbitrarily large to fit the training data, and in this way +reduces *overfitting*. + +We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: + +$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad +\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \bm{w} \rvert \rvert_2^2 += \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ + +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 +the hidden layer and $(50 + 1)\times 10=510$ weights to the output +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. + + +!split +===== Matrix multiplication ===== + +To more efficently train our network these equations are implemented using matrix operations. +The error in the output layer is calculated simply as, with $\bm{t}$ being our targets, + +$$ \delta_L = \bm{t} - \bm{y} = (n_{inputs}, n_{categories}) .$$ + +The gradient for the output weights is calculated as + +$$ \nabla W_{L} = \bm{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ + +where $\bm{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. +Since we are going backwards we have to transpose the activation matrix. + +The gradient with respect to the output bias is then + +$$ \nabla \bm{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ + +The error in the hidden layer is + +$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ + +where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean +that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes +the *Hadamard product*, meaning element-wise multiplication. + +This again gives us the gradients in the hidden layer: + +$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ + +$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ + + +!bc pycod +# to categorical turns our integer vector into a onehot representation +from sklearn.metrics import accuracy_score + +# one-hot in numpy +def to_categorical_numpy(integer_vector): + n_inputs = len(integer_vector) + n_categories = np.max(integer_vector) + 1 + onehot_vector = np.zeros((n_inputs, n_categories)) + onehot_vector[range(n_inputs), integer_vector] = 1 + + return onehot_vector + +#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) +Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) + +def feed_forward_train(X): + # weighted sum of inputs to the hidden layer + z_h = np.matmul(X, hidden_weights) + hidden_bias + # activation in the hidden layer + a_h = sigmoid(z_h) + + # weighted sum of inputs to the output layer + z_o = np.matmul(a_h, output_weights) + output_bias + # softmax output + # axis 0 holds each input and axis 1 the probabilities of each category + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + # for backpropagation need activations in hidden and output layers + return a_h, probabilities + +def backpropagation(X, Y): + a_h, probabilities = feed_forward_train(X) + + # error in the output layer + error_output = probabilities - Y + # error in the hidden layer + error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) + + # gradients for the output layer + output_weights_gradient = np.matmul(a_h.T, error_output) + output_bias_gradient = np.sum(error_output, axis=0) + + # gradient for the hidden layer + hidden_weights_gradient = np.matmul(X.T, error_hidden) + hidden_bias_gradient = np.sum(error_hidden, axis=0) + + return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient + +print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) + +eta = 0.01 +lmbd = 0.01 +for i in range(1000): + # calculate gradients + dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) + + # regularization term gradients + dWo += lmbd * output_weights + dWh += lmbd * hidden_weights + + # update weights and biases + output_weights -= eta * dWo + output_bias -= eta * dBo + hidden_weights -= eta * dWh + hidden_bias -= eta * dBh + +print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) +!ec + +!split +===== Improving performance ===== + +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. +In order to obtain a network that does something useful, we will have to do a bit more work. + +The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. + +Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period +going through the entire dataset ($n/M$ batches) an *epoch*. + +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/". + +!split +===== Full object-oriented implementation ===== + +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. + + +!bc pycod +class NeuralNetwork: + def __init__( + self, + X_data, + Y_data, + n_hidden_neurons=50, + n_categories=10, + epochs=10, + batch_size=100, + eta=0.1, + lmbd=0.0): + + self.X_data_full = X_data + self.Y_data_full = Y_data + + self.n_inputs = X_data.shape[0] + self.n_features = X_data.shape[1] + self.n_hidden_neurons = n_hidden_neurons + self.n_categories = n_categories + + self.epochs = epochs + self.batch_size = batch_size + self.iterations = self.n_inputs // self.batch_size + self.eta = eta + self.lmbd = lmbd + + self.create_biases_and_weights() + + def create_biases_and_weights(self): + self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) + self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 + + self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) + self.output_bias = np.zeros(self.n_categories) + 0.01 + + def feed_forward(self): + # feed-forward for training + self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias + self.a_h = sigmoid(self.z_h) + + self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(self.z_o) + self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + + def feed_forward_out(self, X): + # feed-forward for output + z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias + a_h = sigmoid(z_h) + + z_o = np.matmul(a_h, self.output_weights) + self.output_bias + + exp_term = np.exp(z_o) + probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) + return probabilities + + def backpropagation(self): + error_output = self.probabilities - self.Y_data + error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) + + self.output_weights_gradient = np.matmul(self.a_h.T, error_output) + self.output_bias_gradient = np.sum(error_output, axis=0) + + self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) + self.hidden_bias_gradient = np.sum(error_hidden, axis=0) + + if self.lmbd > 0.0: + self.output_weights_gradient += self.lmbd * self.output_weights + self.hidden_weights_gradient += self.lmbd * self.hidden_weights + + self.output_weights -= self.eta * self.output_weights_gradient + self.output_bias -= self.eta * self.output_bias_gradient + self.hidden_weights -= self.eta * self.hidden_weights_gradient + self.hidden_bias -= self.eta * self.hidden_bias_gradient + + def predict(self, X): + probabilities = self.feed_forward_out(X) + return np.argmax(probabilities, axis=1) + + def predict_probabilities(self, X): + probabilities = self.feed_forward_out(X) + return probabilities + + def train(self): + data_indices = np.arange(self.n_inputs) + + for i in range(self.epochs): + for j in range(self.iterations): + # pick datapoints with replacement + chosen_datapoints = np.random.choice( + data_indices, size=self.batch_size, replace=False + ) + + # minibatch training data + self.X_data = self.X_data_full[chosen_datapoints] + self.Y_data = self.Y_data_full[chosen_datapoints] + + self.feed_forward() + self.backpropagation() +!ec + +!split +===== Evaluate model performance on test data ===== + +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. +We measure the performance of the network using the *accuracy* score. +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 $1$. + +$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ + +where $I$ is the indicator function, $1$ if $\tilde{y}_i = y_i$ and $0$ otherwise. + + +!bc pycod +epochs = 100 +batch_size = 100 + +dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) +dnn.train() +test_predict = dnn.predict(X_test) + +# accuracy score from scikit library +print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) + +# equivalent in numpy +def accuracy_score_numpy(Y_test, Y_pred): + return np.sum(Y_test == Y_pred) / len(Y_test) + +#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) +!ec + +!split +===== Adjust hyperparameters ===== + +We now perform a grid search to find the optimal hyperparameters for the network. +Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). + +!bc pycod +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +# grid search +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, + n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) + dnn.train() + + DNN_numpy[i][j] = dnn + + test_predict = dnn.predict(X_test) + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) + print() +!ec + +!split +===== Visualization ===== + +!bc pycod +# visual representation of grid search +# uses seaborn heatmap, you can also do this with matplotlib imshow +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)): + dnn = DNN_numpy[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +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() +!ec + +!split +===== scikit-learn implementation ===== + +_scikit-learn_ focuses more +on traditional machine learning methods, such as regression, +clustering, decision trees, etc. As such, it has only two types of +neural networks: Multi Layer Perceptron outputting continuous values, +*MPLRegressor*, and Multi Layer Perceptron outputting labels, +*MLPClassifier*. We will see how simple it is to use these classes. + +_scikit-learn_ implements a few improvements from our neural network, +such as early stopping, a varying learning rate, different +optimization methods, etc. We would therefore expect a better +performance overall. + +!bc pycod +from sklearn.neural_network import MLPClassifier +# store models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + + DNN_scikit[i][j] = dnn + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) + print() +!ec + + +!split +===== Visualization ===== +!bc pycod +# optional +# 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)): + dnn = DNN_scikit[i][j] + + train_pred = dnn.predict(X_train) + test_pred = dnn.predict(X_test) + + train_accuracy[i][j] = accuracy_score(Y_train, train_pred) + test_accuracy[i][j] = accuracy_score(Y_test, test_pred) + + +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() +!ec + + + + + + + + + +!split +===== Building neural networks in Tensorflow and Keras ===== + +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. + +In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. + +!split +===== Tensorflow ===== + +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. + +Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. + +"Tensorflow uses":"https://www.tensorflow.org/guide/graphs" so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph* +to represent your model, and then create a Tensorflow *session* to run the graph. + +In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +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. + +To install tensorflow on Unix/Linux systems, use pip as +!bc pycod +pip3 install tensorflow +!ec +and/or if you use _anaconda_, just write (or install from the graphical user interface) +(current release of CPU-only TensorFlow) +!bc pycod +conda create -n tf tensorflow +conda activate tf +!ec +To install the current release of GPU TensorFlow +!bc pycod +conda create -n tf-gpu tensorflow-gpu +conda activate tf-gpu +!ec + +!split +===== Using Keras ===== + +Keras is a high level "neural network":"https://en.wikipedia.org/wiki/Application_programming_interface" +that supports Tensorflow, CTNK and Theano as backends. +If you have Anaconda installed you may run the following command +!bc pycod +conda install keras +!ec +You can look up the "instructions here":"https://keras.io/" for more information. + +We will to a large extent use _keras_ in this course. + +!split +===== Collect and pre-process data ===== + +Let us look again at the MINST data set. + +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +import tensorflow as tf +from sklearn import datasets + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%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 + +print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# flatten the image +# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 +n_inputs = len(inputs) +inputs = inputs.reshape(n_inputs, -1) +print("X = (n_inputs, n_features) = " + str(inputs.shape)) + + +# choose some random images to display +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() +!ec + +!bc pycod +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 sklearn.model_selection import train_test_split + +# one-hot representation of labels +labels = to_categorical(labels) + +# split into train and test data +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) +!ec + + + +!bc pycod + +epochs = 100 +batch_size = 100 +n_neurons_layer1 = 100 +n_neurons_layer2 = 50 +n_categories = 10 +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd): + model = Sequential() + model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) + model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd))) + model.add(Dense(n_categories, activation='softmax')) + + sgd = optimizers.SGD(learning_rate=eta) + model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) + + return model +!ec + +!bc pycod +DNN_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): + DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, + eta=eta, lmbd=lmbd) + DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) + scores = DNN.evaluate(X_test, Y_test) + + DNN_keras[i][j] = DNN + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Test accuracy: %.3f" % scores[1]) + print() +!ec + + + +!bc pycod +# optional +# 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)): + DNN = DNN_keras[i][j] + + train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1] + test_accuracy[i][j] = DNN.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() +!ec + + + +!split +===== The Breast Cancer Data, now with Keras ===== + +!bc pycod + +import tensorflow as tf +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 +import numpy as np +import matplotlib.pyplot as plt +import seaborn as sns +from sklearn.model_selection import train_test_split as splitter +from sklearn.datasets import load_breast_cancer +import pickle +import os + + +"""Load breast cancer dataset""" + +np.random.seed(0) #create same seed for random number every time + +cancer=load_breast_cancer() #Download breast cancer dataset + +inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters) +outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant) +labels=cancer.feature_names[0:30] + +print('The content of the breast cancer dataset is:') #Print information about the datasets +print(labels) +print('-------------------------') +print("inputs = " + str(inputs.shape)) +print("outputs = " + str(outputs.shape)) +print("labels = "+ str(labels.shape)) + +x=inputs #Reassign the Feature and Label matrices to other variables +y=outputs + +#%% + +# Visualisation of dataset (for correlation analysis) + +plt.figure() +plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean radius',fontweight='bold') +plt.ylabel('Mean perimeter',fontweight='bold') +plt.show() + +plt.figure() +plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral) +plt.xlabel('Mean compactness',fontweight='bold') +plt.ylabel('Mean concavity',fontweight='bold') +plt.show() + + +plt.figure() +plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean radius',fontweight='bold') +plt.ylabel('Mean texture',fontweight='bold') +plt.show() + +plt.figure() +plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) +plt.xlabel('Mean perimeter',fontweight='bold') +plt.ylabel('Mean compactness',fontweight='bold') +plt.show() + + +# Generate training and testing datasets + +#Select features relevant to classification (texture,perimeter,compactness and symmetery) +#and add to input matrix + +temp1=np.reshape(x[:,1],(len(x[:,1]),1)) +temp2=np.reshape(x[:,2],(len(x[:,2]),1)) +X=np.hstack((temp1,temp2)) +temp=np.reshape(x[:,5],(len(x[:,5]),1)) +X=np.hstack((X,temp)) +temp=np.reshape(x[:,8],(len(x[:,8]),1)) +X=np.hstack((X,temp)) + +X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing + +y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy +y_test=to_categorical(y_test) + +del temp1,temp2,temp + +# %% + +# Define tunable parameters" + +eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser) +lamda=0.01 #Define hyperparameter +n_layers=2 #Define number of hidden layers in the model +n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer +epochs=100 #Number of reiterations over the input data +batch_size=100 #Number of samples per gradient update + +# %% + +"""Define function to return Deep Neural Network model""" + +def NN_model(inputsize,n_layers,n_neuron,eta,lamda): + model=Sequential() + for i in range(n_layers): #Run loop to add hidden layers to the model + if (i==0): #First layer requires input dimensions + model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize)) + else: #Subsequent layers are capable of automatic shape inferencing + model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda))) + model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob) + sgd=optimizers.SGD(learning_rate=eta) + model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy']) + return model + + +Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function +Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for + +for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate + for j in range(len(eta)): #accuracy scores + DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda) + DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1) + Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1] + Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1] + + +def plot_data(x,y,data,title=None): + + # plot results + fontsize=16 + + + fig = plt.figure() + ax = fig.add_subplot(111) + cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1) + + cbar=fig.colorbar(cax) + cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize) + cbar.set_ticks([0,.2,.4,0.6,0.8,1.0]) + cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%']) + + # put text on matrix elements + for i, x_val in enumerate(np.arange(len(x))): + for j, y_val in enumerate(np.arange(len(y))): + c = "${0:.1f}\\%$".format( 100*data[j,i]) + ax.text(x_val, y_val, c, va='center', ha='center') + + # convert axis vaues to to string labels + x=[str(i) for i in x] + y=[str(i) for i in y] + + + ax.set_xticklabels(['']+x) + ax.set_yticklabels(['']+y) + + ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize) + ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize) + if title is not None: + ax.set_title(title) + + plt.tight_layout() + + plt.show() + +plot_data(eta,n_neuron,Train_accuracy, 'training') +plot_data(eta,n_neuron,Test_accuracy, 'testing') + +!ec + + + + + +!split +===== Building a neural network code ===== + +Here we present a flexible object oriented codebase +for a feed forward neural network, along with a demonstration of how +to use it. Before we get into the details of the neural network, we +will first present some implementations of various schedulers, cost +functions and activation functions that can be used together with the +neural network. + +The codes here were developed by Eric Reber and Gregor Kajda during spring 2023. + +=== Learning rate methods === + +The code below shows object oriented implementations of the Constant, +Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All +of the classes belong to the shared abstract Scheduler class, and +share the update_change() and reset() methods allowing for any of the +schedulers to be seamlessly used during the training stage, as will +later be shown in the fit() method of the neural +network. Update_change() only has one parameter, the gradient +($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted +from the weights. The reset() function takes no parameters, and resets +the desired variables. For Constant and Momentum, reset does nothing. + + +!bc pycod +import autograd.numpy as np + +class Scheduler: + """ + Abstract class for Schedulers + """ + + def __init__(self, eta): + self.eta = eta + + # should be overwritten + def update_change(self, gradient): + raise NotImplementedError + + # overwritten if needed + def reset(self): + pass + + +class Constant(Scheduler): + def __init__(self, eta): + super().__init__(eta) + + def update_change(self, gradient): + return self.eta * gradient + + def reset(self): + pass + + +class Momentum(Scheduler): + def __init__(self, eta: float, momentum: float): + super().__init__(eta) + self.momentum = momentum + self.change = 0 + + def update_change(self, gradient): + self.change = self.momentum * self.change + self.eta * gradient + return self.change + + def reset(self): + pass + + +class Adagrad(Scheduler): + def __init__(self, eta): + super().__init__(eta) + self.G_t = None + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + + if self.G_t is None: + self.G_t = np.zeros((gradient.shape[0], gradient.shape[0])) + + self.G_t += gradient @ gradient.T + + G_t_inverse = 1 / ( + delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1))) + ) + return self.eta * gradient * G_t_inverse + + def reset(self): + self.G_t = None + + +class AdagradMomentum(Scheduler): + def __init__(self, eta, momentum): + super().__init__(eta) + self.G_t = None + self.momentum = momentum + self.change = 0 + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + + if self.G_t is None: + self.G_t = np.zeros((gradient.shape[0], gradient.shape[0])) + + self.G_t += gradient @ gradient.T + + G_t_inverse = 1 / ( + delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1))) + ) + self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse + return self.change + + def reset(self): + self.G_t = None + + +class RMS_prop(Scheduler): + def __init__(self, eta, rho): + super().__init__(eta) + self.rho = rho + self.second = 0.0 + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient + return self.eta * gradient / (np.sqrt(self.second + delta)) + + def reset(self): + self.second = 0.0 + + +class Adam(Scheduler): + def __init__(self, eta, rho, rho2): + super().__init__(eta) + self.rho = rho + self.rho2 = rho2 + self.moment = 0 + self.second = 0 + self.n_epochs = 1 + + def update_change(self, gradient): + delta = 1e-8 # avoid division ny zero + + self.moment = self.rho * self.moment + (1 - self.rho) * gradient + self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient + + moment_corrected = self.moment / (1 - self.rho**self.n_epochs) + second_corrected = self.second / (1 - self.rho2**self.n_epochs) + + return self.eta * moment_corrected / (np.sqrt(second_corrected + delta)) + + def reset(self): + self.n_epochs += 1 + self.moment = 0 + self.second = 0 + +!ec + +=== Usage of the above learning rate schedulers === + +To initalize a scheduler, simply create the object and pass in the +necessary parameters such as the learning rate and the momentum as +shown below. As the Scheduler class is an abstract class it should not +called directly, and will raise an error upon usage. + +!bc pycod +momentum_scheduler = Momentum(eta=1e-3, momentum=0.9) +adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) +!ec + +Here is a small example for how a segment of code using schedulers +could look. Switching out the schedulers is simple. + +!bc pycod +weights = np.ones((3,3)) +print(f"Before scheduler:\n{weights=}") + +epochs = 10 +for e in range(epochs): + gradient = np.random.rand(3, 3) + change = adam_scheduler.update_change(gradient) + weights = weights - change + adam_scheduler.reset() + +print(f"\nAfter scheduler:\n{weights=}") +!ec + + +=== Cost functions === + +Here we discuss cost functions that can be used when creating the +neural network. Every cost function takes the target vector as its +parameter, and returns a function valued only at $x$ such that it may +easily be differentiated. + + +!bc pycod +import autograd.numpy as np + +def CostOLS(target): + + def func(X): + return (1.0 / target.shape[0]) * np.sum((target - X) ** 2) + + return func + + +def CostLogReg(target): + + def func(X): + + return -(1.0 / target.shape[0]) * np.sum( + (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10)) + ) + + return func + + +def CostCrossEntropy(target): + + def func(X): + return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10)) + + return func +!ec + + +Below we give a short example of how these cost function may be used +to obtain results if you wish to test them out on your own using +AutoGrad's automatics differentiation. + +!bc pycod +from autograd import grad + +target = np.array([[1, 2, 3]]).T +a = np.array([[4, 5, 6]]).T + +cost_func = CostCrossEntropy +cost_func_derivative = grad(cost_func(target)) + +valued_at_a = cost_func_derivative(a) +print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}") +!ec + + +=== Activation functions === + +Finally, before we look at the neural network, we will look at the +activation functions which can be specified between the hidden layers +and as the output function. Each function can be valued for any given +vector or matrix X, and can be differentiated via derivate(). + +!bc pycod +import autograd.numpy as np +from autograd import elementwise_grad + +def identity(X): + return X + + +def sigmoid(X): + try: + return 1.0 / (1 + np.exp(-X)) + except FloatingPointError: + return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape)) + + +def softmax(X): + X = X - np.max(X, axis=-1, keepdims=True) + delta = 10e-10 + return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta) + + +def RELU(X): + return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape)) + + +def LRELU(X): + delta = 10e-4 + return np.where(X > np.zeros(X.shape), X, delta * X) + + +def derivate(func): + if func.__name__ == "RELU": + + def func(X): + return np.where(X > 0, 1, 0) + + return func + + elif func.__name__ == "LRELU": + + def func(X): + delta = 10e-4 + return np.where(X > 0, 1, delta) + + return func + + else: + return elementwise_grad(func) +!ec + +Below follows a short demonstration of how to use an activation +function. The derivative of the activation function will be important +when calculating the output delta term during backpropagation. Note +that derivate() can also be used for cost functions for a more +generalized approach. + +!bc pycod +z = np.array([[4, 5, 6]]).T +print(f"Input to activation function:\n{z}") + +act_func = sigmoid +a = act_func(z) +print(f"\nOutput from {act_func.__name__} activation function:\n{a}") + +act_func_derivative = derivate(act_func) +valued_at_z = act_func_derivative(a) +print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}") +!ec + +=== The Neural Network === + +Now that we have gotten a good understanding of the implementation of +some important components, we can take a look at an object oriented +implementation of a feed forward neural network. The feed forward +neural network has been implemented as a class named FFNN, which can +be initiated as a regressor or classifier dependant on the choice of +cost function. The FFNN can have any number of input nodes, hidden +layers with any amount of hidden nodes, and any amount of output nodes +meaning it can perform multiclass classification as well as binary +classification and regression problems. Although there is a lot of +code present, it makes for an easy to use and generalizeable interface +for creating many types of neural networks as will be demonstrated +below. + +!bc pycod +import math +import autograd.numpy as np +import sys +import warnings +from autograd import grad, elementwise_grad +from random import random, seed +from copy import deepcopy, copy +from typing import Tuple, Callable +from sklearn.utils import resample + +warnings.simplefilter("error") + + +class FFNN: + """ + Description: + ------------ + Feed Forward Neural Network with interface enabling flexible design of a + nerual networks architecture and the specification of activation function + in the hidden layers and output layer respectively. This model can be used + for both regression and classification problems, depending on the output function. + + Attributes: + ------------ + I dimensions (tuple[int]): A list of positive integers, which specifies the + number of nodes in each of the networks layers. The first integer in the array + defines the number of nodes in the input layer, the second integer defines number + of nodes in the first hidden layer and so on until the last number, which + specifies the number of nodes in the output layer. + II hidden_func (Callable): The activation function for the hidden layers + III output_func (Callable): The activation function for the output layer + IV cost_func (Callable): Our cost function + V seed (int): Sets random seed, makes results reproducible + """ + + def __init__( + self, + dimensions: tuple[int], + hidden_func: Callable = sigmoid, + output_func: Callable = lambda x: x, + cost_func: Callable = CostOLS, + seed: int = None, + ): + self.dimensions = dimensions + self.hidden_func = hidden_func + self.output_func = output_func + self.cost_func = cost_func + self.seed = seed + self.weights = list() + self.schedulers_weight = list() + self.schedulers_bias = list() + self.a_matrices = list() + self.z_matrices = list() + self.classification = None + + self.reset_weights() + self._set_classification() + + def fit( + self, + X: np.ndarray, + t: np.ndarray, + scheduler: Scheduler, + batches: int = 1, + epochs: int = 100, + lam: float = 0, + X_val: np.ndarray = None, + t_val: np.ndarray = None, + ): + """ + Description: + ------------ + This function performs the training the neural network by performing the feedforward and backpropagation + algorithm to update the networks weights. + + Parameters: + ------------ + I X (np.ndarray) : training data + II t (np.ndarray) : target data + III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent) + IV scheduler_args (list[int]) : list of all arguments necessary for scheduler + + Optional Parameters: + ------------ + V batches (int) : number of batches the datasets are split into, default equal to 1 + VI epochs (int) : number of iterations used to train the network, default equal to 100 + VII lam (float) : regularization hyperparameter lambda + VIII X_val (np.ndarray) : validation set + IX t_val (np.ndarray) : validation target set + + Returns: + ------------ + I scores (dict) : A dictionary containing the performance metrics of the model. + The number of the metrics depends on the parameters passed to the fit-function. + + """ + + # setup + if self.seed is not None: + np.random.seed(self.seed) + + val_set = False + if X_val is not None and t_val is not None: + val_set = True + + # creating arrays for score metrics + train_errors = np.empty(epochs) + train_errors.fill(np.nan) + val_errors = np.empty(epochs) + val_errors.fill(np.nan) + + train_accs = np.empty(epochs) + train_accs.fill(np.nan) + val_accs = np.empty(epochs) + val_accs.fill(np.nan) + + self.schedulers_weight = list() + self.schedulers_bias = list() + + batch_size = X.shape[0] // batches + + X, t = resample(X, t) + + # this function returns a function valued only at X + cost_function_train = self.cost_func(t) + if val_set: + cost_function_val = self.cost_func(t_val) + + # create schedulers for each weight matrix + for i in range(len(self.weights)): + self.schedulers_weight.append(copy(scheduler)) + self.schedulers_bias.append(copy(scheduler)) + + print(f"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}") + + try: + for e in range(epochs): + for i in range(batches): + # allows for minibatch gradient descent + if i == batches - 1: + # If the for loop has reached the last batch, take all thats left + X_batch = X[i * batch_size :, :] + t_batch = t[i * batch_size :, :] + else: + X_batch = X[i * batch_size : (i + 1) * batch_size, :] + t_batch = t[i * batch_size : (i + 1) * batch_size, :] + + self._feedforward(X_batch) + self._backpropagate(X_batch, t_batch, lam) + + # reset schedulers for each epoch (some schedulers pass in this call) + for scheduler in self.schedulers_weight: + scheduler.reset() + + for scheduler in self.schedulers_bias: + scheduler.reset() + + # computing performance metrics + pred_train = self.predict(X) + train_error = cost_function_train(pred_train) + + train_errors[e] = train_error + if val_set: + + pred_val = self.predict(X_val) + val_error = cost_function_val(pred_val) + val_errors[e] = val_error + + if self.classification: + train_acc = self._accuracy(self.predict(X), t) + train_accs[e] = train_acc + if val_set: + val_acc = self._accuracy(pred_val, t_val) + val_accs[e] = val_acc + + # printing progress bar + progression = e / epochs + print_length = self._progress_bar( + progression, + train_error=train_errors[e], + train_acc=train_accs[e], + val_error=val_errors[e], + val_acc=val_accs[e], + ) + except KeyboardInterrupt: + # allows for stopping training at any point and seeing the result + pass + + # visualization of training progression (similiar to tensorflow progression bar) + sys.stdout.write("\r" + " " * print_length) + sys.stdout.flush() + self._progress_bar( + 1, + train_error=train_errors[e], + train_acc=train_accs[e], + val_error=val_errors[e], + val_acc=val_accs[e], + ) + sys.stdout.write("") + + # return performance metrics for the entire run + scores = dict() + + scores["train_errors"] = train_errors + + if val_set: + scores["val_errors"] = val_errors + + if self.classification: + scores["train_accs"] = train_accs + + if val_set: + scores["val_accs"] = val_accs + + return scores + + def predict(self, X: np.ndarray, *, threshold=0.5): + """ + Description: + ------------ + Performs prediction after training of the network has been finished. + + Parameters: + ------------ + I X (np.ndarray): The design matrix, with n rows of p features each + + Optional Parameters: + ------------ + II threshold (float) : sets minimal value for a prediction to be predicted as the positive class + in classification problems + + Returns: + ------------ + I z (np.ndarray): A prediction vector (row) for each row in our design matrix + This vector is thresholded if regression=False, meaning that classification results + in a vector of 1s and 0s, while regressions in an array of decimal numbers + + """ + + predict = self._feedforward(X) + + if self.classification: + return np.where(predict > threshold, 1, 0) + else: + return predict + + def reset_weights(self): + """ + Description: + ------------ + Resets/Reinitializes the weights in order to train the network for a new problem. + + """ + if self.seed is not None: + np.random.seed(self.seed) + + self.weights = list() + for i in range(len(self.dimensions) - 1): + weight_array = np.random.randn( + self.dimensions[i] + 1, self.dimensions[i + 1] + ) + weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01 + + self.weights.append(weight_array) + + def _feedforward(self, X: np.ndarray): + """ + Description: + ------------ + Calculates the activation of each layer starting at the input and ending at the output. + Each following activation is calculated from a weighted sum of each of the preceeding + activations (except in the case of the input layer). + + Parameters: + ------------ + I X (np.ndarray): The design matrix, with n rows of p features each + + Returns: + ------------ + I z (np.ndarray): A prediction vector (row) for each row in our design matrix + """ + + # reset matrices + self.a_matrices = list() + self.z_matrices = list() + + # if X is just a vector, make it into a matrix + if len(X.shape) == 1: + X = X.reshape((1, X.shape[0])) + + # Add a coloumn of zeros as the first coloumn of the design matrix, in order + # to add bias to our data + bias = np.ones((X.shape[0], 1)) * 0.01 + X = np.hstack([bias, X]) + + # a^0, the nodes in the input layer (one a^0 for each row in X - where the + # exponent indicates layer number). + a = X + self.a_matrices.append(a) + self.z_matrices.append(a) + + # The feed forward algorithm + for i in range(len(self.weights)): + if i < len(self.weights) - 1: + z = a @ self.weights[i] + self.z_matrices.append(z) + a = self.hidden_func(z) + # bias column again added to the data here + bias = np.ones((a.shape[0], 1)) * 0.01 + a = np.hstack([bias, a]) + self.a_matrices.append(a) + else: + try: + # a^L, the nodes in our output layers + z = a @ self.weights[i] + a = self.output_func(z) + self.a_matrices.append(a) + self.z_matrices.append(z) + except Exception as OverflowError: + print( + "OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling" + ) + + # this will be a^L + return a + + def _backpropagate(self, X, t, lam): + """ + Description: + ------------ + Performs the backpropagation algorithm. In other words, this method + calculates the gradient of all the layers starting at the + output layer, and moving from right to left accumulates the gradient until + the input layer is reached. Each layers respective weights are updated while + the algorithm propagates backwards from the output layer (auto-differentation in reverse mode). + + Parameters: + ------------ + I X (np.ndarray): The design matrix, with n rows of p features each. + II t (np.ndarray): The target vector, with n rows of p targets. + III lam (float32): regularization parameter used to punish the weights in case of overfitting + + Returns: + ------------ + No return value. + + """ + out_derivative = derivate(self.output_func) + hidden_derivative = derivate(self.hidden_func) + + for i in range(len(self.weights) - 1, -1, -1): + # delta terms for output + if i == len(self.weights) - 1: + # for multi-class classification + if ( + self.output_func.__name__ == "softmax" + ): + delta_matrix = self.a_matrices[i + 1] - t + # for single class classification + else: + cost_func_derivative = grad(self.cost_func(t)) + delta_matrix = out_derivative( + self.z_matrices[i + 1] + ) * cost_func_derivative(self.a_matrices[i + 1]) + + # delta terms for hidden layer + else: + delta_matrix = ( + self.weights[i + 1][1:, :] @ delta_matrix.T + ).T * hidden_derivative(self.z_matrices[i + 1]) + + # calculate gradient + gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix + gradient_bias = np.sum(delta_matrix, axis=0).reshape( + 1, delta_matrix.shape[1] + ) + + # regularization term + gradient_weights += self.weights[i][1:, :] * lam + + # use scheduler + update_matrix = np.vstack( + [ + self.schedulers_bias[i].update_change(gradient_bias), + self.schedulers_weight[i].update_change(gradient_weights), + ] + ) + + # update weights and bias + self.weights[i] -= update_matrix + + def _accuracy(self, prediction: np.ndarray, target: np.ndarray): + """ + Description: + ------------ + Calculates accuracy of given prediction to target + + Parameters: + ------------ + I prediction (np.ndarray): vector of predicitons output network + (1s and 0s in case of classification, and real numbers in case of regression) + II target (np.ndarray): vector of true values (What the network ideally should predict) + + Returns: + ------------ + A floating point number representing the percentage of correctly classified instances. + """ + assert prediction.size == target.size + return np.average((target == prediction)) + def _set_classification(self): + """ + Description: + ------------ + Decides if FFNN acts as classifier (True) og regressor (False), + sets self.classification during init() + """ + self.classification = False + if ( + self.cost_func.__name__ == "CostLogReg" + or self.cost_func.__name__ == "CostCrossEntropy" + ): + self.classification = True + + def _progress_bar(self, progression, **kwargs): + """ + Description: + ------------ + Displays progress of training + """ + print_length = 40 + num_equals = int(progression * print_length) + num_not = print_length - num_equals + arrow = ">" if num_equals > 0 else "" + bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]" + perc_print = self._format(progression * 100, decimals=5) + line = f" {bar} {perc_print}% " + + for key in kwargs: + if not np.isnan(kwargs[key]): + value = self._format(kwargs[key], decimals=4) + line += f"| {key}: {value} " + sys.stdout.write("\r" + line) + sys.stdout.flush() + return len(line) + + def _format(self, value, decimals=4): + """ + Description: + ------------ + Formats decimal numbers for progress bar + """ + if value > 0: + v = value + elif value < 0: + v = -10 * value + else: + v = 1 + n = 1 + math.floor(math.log10(v)) + if n >= decimals - 1: + return str(round(value)) + return f"{value:.{decimals-n-1}f}" +!ec + +Before we make a model, we will quickly generate a dataset we can use +for our linear regression problem as shown below + +!bc pycod +import autograd.numpy as np +from sklearn.model_selection import train_test_split + +def SkrankeFunction(x, y): + return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2) + +def create_X(x, y, n): + if len(x.shape) > 1: + x = np.ravel(x) + y = np.ravel(y) + + N = len(x) + l = int((n + 1) * (n + 2) / 2) # Number of elements in beta + X = np.ones((N, l)) + + for i in range(1, n + 1): + q = int((i) * (i + 1) / 2) + for k in range(i + 1): + X[:, q + k] = (x ** (i - k)) * (y**k) + + return X + +step=0.5 +x = np.arange(0, 1, step) +y = np.arange(0, 1, step) +x, y = np.meshgrid(x, y) +target = SkrankeFunction(x, y) +target = target.reshape(target.shape[0], 1) + +poly_degree=3 +X = create_X(x, y, poly_degree) + +X_train, X_test, t_train, t_test = train_test_split(X, target) + +!ec + +Now that we have our dataset ready for the regression, we can create +our regressor. Note that with the seed parameter, we can make sure our +results stay the same every time we run the neural network. For +inititialization, we simply specify the dimensions (we wish the amount +of input nodes to be equal to the datapoints, and the output to +predict one value). + + +!bc pycod +input_nodes = X_train.shape[1] +output_nodes = 1 + +linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023) + +!ec + +We then fit our model with our training data using the scheduler of our choice. + +!bc pycod +linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Constant(eta=1e-3) +scores = linear_regression.fit(X_train, t_train, scheduler) + + +!ec + +Due to the progress bar we can see the MSE (train_error) throughout +the FFNN's training. Note that the fit() function has some optional +parameters with defualt arguments. For example, the regularization +hyperparameter can be left ignored if not needed, and equally the FFNN +will by default run for 100 epochs. These can easily be changed, such +as for example: + +!bc pycod +linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000) + +!ec + +We see that given more epochs to train on, the regressor reaches a lower MSE. + +Let us then switch to a binary classification. We use a binary +classification dataset, and follow a similar setup to the regression +case. + + + +!bc pycod +from sklearn.datasets import load_breast_cancer +from sklearn.preprocessing import MinMaxScaler + +wisconsin = load_breast_cancer() +X = wisconsin.data +target = wisconsin.target +target = target.reshape(target.shape[0], 1) + +X_train, X_val, t_train, t_val = train_test_split(X, target) + +scaler = MinMaxScaler() +scaler.fit(X_train) +X_train = scaler.transform(X_train) +X_val = scaler.transform(X_val) + + +!ec + +!bc pycod +input_nodes = X_train.shape[1] +output_nodes = 1 + +logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023) + +!ec + +We will now make use of our validation data by passing it into our fit function as a keyword argument + +!bc pycod +logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) +scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val) + + +!ec + +Finally, we will create a neural network with 2 hidden layers with activation functions. +!bc pycod +input_nodes = X_train.shape[1] +hidden_nodes1 = 100 +hidden_nodes2 = 30 +output_nodes = 1 + +dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes) + +neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023) + + +!ec + +!bc pycod +neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999) +scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val) + +!ec + +=== Multiclass classification === + +Finally, we will demonstrate the use case of multiclass classification +using our FFNN with the famous MNIST dataset, which contain images of +digits between the range of 0 to 9. + + +!bc pycod +from sklearn.datasets import load_digits + +def onehot(target: np.ndarray): + onehot = np.zeros((target.size, target.max() + 1)) + onehot[np.arange(target.size), target] = 1 + return onehot + +digits = load_digits() + +X = digits.data +target = digits.target +target = onehot(target) + +input_nodes = 64 +hidden_nodes1 = 100 +hidden_nodes2 = 30 +output_nodes = 10 + +dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes) + +multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy) + +multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights + +scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999) +scores = multiclass.fit(X, target, scheduler, epochs=1000) + +!ec + + + +!split +===== Testing the XOR gate and other gates ===== + +Let us now use our code to test the XOR gate. + +!bc pycod +X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) + +# The XOR gate +yXOR = np.array( [[ 0], [1] ,[1], [0]]) + +input_nodes = X.shape[1] +output_nodes = 1 + +logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023) +logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights +scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999) +scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000) +!ec +Not bad, but the results depend strongly on the learning reate. Try different learning rates. + + + + + + +!split +===== Solving differential equations with Deep Learning ===== + +!bblock +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. +!eblock + +!bblock Book on solving differential equations with ML methods +"An Introduction to Neural Network Methods for Differential Equations":"https://www.springer.com/gp/book/9789401798150", by Yadav and Kumar. +!eblock + +!bblock Physics informed neural networks +"Scientific Machine Learning Through Physics–Informed Neural Networks: Where we are and What’s Next":"https://link.springer.com/article/10.1007/s10915-022-01939-z", by Cuomo et al +!eblock + + + +!bblock Thanks to Kristine Baluka Hein +The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI. +A great thanks to Kristine. +!eblock + +!split +===== Ordinary Differential Equations first ===== + +An ordinary differential equation (ODE) is an equation involving functions having one variable. + +In general, an ordinary differential equation looks like + +!bt +\begin{equation} \label{ode} +f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) = 0 +\end{equation} +!et + +where $g(x)$ is the function to find, and $g^{(n)}(x)$ is the $n$-th derivative of $g(x)$. + +The $f\left(x, g(x), g'(x), g''(x), \, \dots \, , g^{(n)}(x)\right)$ is just a way to write that there is an expression involving $x$ and $g(x), \ g'(x), \ g''(x), \, \dots \, , \text{ and } g^{(n)}(x)$ on the left side of the equality sign in (ref{ode}). +The highest order of derivative, that is the value of $n$, determines to the order of the equation. +The equation is referred to as a $n$-th order ODE. +Along with (ref{ode}), some additional conditions of the function $g(x)$ are typically given +for the solution to be unique. + +!split +===== The trial solution ===== + +Let the trial solution $g_t(x)$ be + +!bt +\begin{equation} + g_t(x) = h_1(x) + h_2(x,N(x,P)) +\end{equation} +!et + + +where $h_1(x)$ is a function that makes $g_t(x)$ satisfy a given set +of conditions, $N(x,P)$ a neural network with weights and biases +described by $P$ and $h_2(x, N(x,P))$ some expression involving the +neural network. The role of the function $h_2(x, N(x,P))$, is to +ensure that the output from $N(x,P)$ is zero when $g_t(x)$ is +evaluated at the values of $x$ where the given conditions must be +satisfied. The function $h_1(x)$ should alone make $g_t(x)$ satisfy +the conditions. + +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. + + +!split +===== Minimization process ===== + +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 (ref{ode}). +We can choose to consider the mean squared error as the cost function for an input $x$. +Since we are looking at one input, the cost function is just $f$ squared. +The cost function $c\left(x, P \right)$ can therefore be expressed as + +!bt +C\left(x, P\right) = \big(f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)\big)^2 +!et + +If $N$ inputs are given as a vector $\bm{x}$ with elements $x_i$ for $i = 1,\dots,N$, +the cost function becomes + +!bt +\begin{equation} \label{cost} + C\left(\bm{x}, P\right) = \frac{1}{N} \sum_{i=1}^N \big(f\left(x_i, \, g(x_i), \, g'(x_i), \, g''(x_i), \, \dots \, , \, g^{(n)}(x_i)\right)\big)^2 +\end{equation} +!et + +The neural net should then find the parameters $P$ that minimizes the cost function in +(ref{cost}) for a set of $N$ training samples $x_i$. + +!split +===== Minimizing the cost function using gradient descent and automatic differentiation ===== + +To perform the minimization using gradient descent, the gradient of $C\left(\bm{x}, P\right)$ is needed. +It might happen so that finding an analytical expression of the gradient of $C(\bm{x}, P)$ from (ref{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. + + +!split +===== Example: Exponential decay ===== + +An exponential decay of a quantity $g(x)$ is described by the equation + +!bt +\begin{equation} \label{solve_expdec} + g'(x) = -\gamma g(x) +\end{equation} +!et + +with $g(0) = g_0$ for some chosen initial value $g_0$. + +The analytical solution of (ref{solve_expdec}) is + +!bt +\begin{equation} + g(x) = g_0 \exp\left(-\gamma x\right) +\end{equation} +!et + +Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of (ref{solve_expdec}). + + +!split +===== The function to solve for ===== + +The program will use a neural network to solve + +!bt +\begin{equation} \label{solveode} +g'(x) = -\gamma g(x) +\end{equation} +!et + +where $g(0) = g_0$ with $\gamma$ and $g_0$ being some chosen values. + +In this example, $\gamma = 2$ and $g_0 = 10$. + +!split +===== The trial solution ===== +To begin with, a trial solution $g_t(t)$ must be chosen. A general trial solution for ordinary differential equations could be + +!bt +g_t(x, P) = h_1(x) + h_2(x, N(x, P)) +!et + +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. + +!split +===== Setup of Network ===== + +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. + +The first column in $P_{\text{hidden} }$ represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer. +If there are $N_{\text{output} }$ neurons in the output layer, then $P_{\text{output}} $ is a $N_{\text{output} } \times (1 + N_{\text{hidden} })$ matrix. + +Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron. + +It is given that $g(0) = g_0$. The trial solution must fulfill this condition to be a proper solution of (ref{solveode}). A possible way to ensure that $g_t(0, P) = g_0$, is to let $F(N(x,P)) = x \cdot N(x,P)$ and $A(x) = g_0$. This gives the following trial solution: + +!bt +\begin{equation} \label{trial} +g_t(x, P) = g_0 + x \cdot N(x, P) +\end{equation} +!et + +!split +===== Reformulating the problem ===== + +We wish that our neural network manages to minimize a given cost function. + +A reformulation of out equation, (ref{solveode}), must therefore be done, +such that it describes the problem a neural network can solve for. + +The neural network must find the set of weights and biases $P$ such that the trial solution in (ref{trial}) satisfies (ref{solveode}). + +The trial solution + +!bt +g_t(x, P) = g_0 + x \cdot N(x, P) +!et + +has been chosen such that it already solves the condition $g(0) = g_0$. What remains, is to find $P$ such that + +!bt +\begin{equation} \label{nnmin} +g_t'(x, P) = - \gamma g_t(x, P) +\end{equation} +!et + +is fulfilled as *best as possible*. + +!split +===== More technicalities ===== + +The left hand side and right hand side of (ref{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. + +This gives the following cost function our neural network must solve for: + +!bt +\min_{P}\Big\{ \big(g_t'(x, P) - ( -\gamma g_t(x, P) \big)^2 \Big\} +!et + +(the notation $\min_{P}\{ f(x, P) \}$ means that we desire to find $P$ that yields the minimum of $f(x, P)$) + +or, in terms of weights and biases for the hidden and output layer in our network: + +!bt +\min_{P_{\text{hidden} }, \ P_{\text{output} }}\Big\{ \big(g_t'(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) - ( -\gamma g_t(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) \big)^2 \Big\} +!et + +for an input value $x$. + +!split +===== More details ===== + +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 + +!bt +\begin{equation} \label{min} +\min_{P}\Big\{\frac{1}{N} \sum_{i=1}^N \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \Big\} +\end{equation} +!et + +Letting $\bm{x}$ be a vector with elements $x_i$ and $C(\bm{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2$ denote the cost function, the minimization problem that our network must solve, becomes + +!bt +\min_{P} C(\bm{x}, P) +!et + +In terms of $P_{\text{hidden} }$ and $P_{\text{output} }$, this could also be expressed as + +$$ +\min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\bm{x}, \{P_{\text{hidden} }, P_{\text{output} }\}) +$$ + +!split +===== A possible implementation of a neural network ===== + +For simplicity, it is assumed that the input is an array $\bm{x} = (x_1, \dots, x_N)$ with $N$ elements. It is at these points the neural network should find $P$ such that it fulfills (ref{min}). + +First, the neural network must feed forward the inputs. +This means that $\bm{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} }$. + +!split +===== Technicalities ===== + +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: + +!bt +\begin{aligned} +z_{i,j}^{\text{hidden}} &= b_i^{\text{hidden}} + w_i^{\text{hidden}}x_j \\ +&= +\begin{pmatrix} +b_i^{\text{hidden}} & w_i^{\text{hidden}} +\end{pmatrix} +\begin{pmatrix} +1 \\ +x_j +\end{pmatrix} +\end{aligned} +!et + +!split +===== Final technicalities I ===== + +The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector: + +!bt +\begin{aligned} +\bm{z}_{i}^{\text{hidden}} &= \Big( b_i^{\text{hidden}} + w_i^{\text{hidden}}x_1 , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_2, \ \dots \, , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_N\Big) \\ +&= +\begin{pmatrix} + b_i^{\text{hidden}} & w_i^{\text{hidden}} +\end{pmatrix} +\begin{pmatrix} +1 & 1 & \dots & 1 \\ +x_1 & x_2 & \dots & x_N +\end{pmatrix} \\ +&= \bm{p}_{i, \text{hidden}}^T X +\end{aligned} +!et + +!split +===== Final technicalities II ===== + +The vector $\bm{p}_{i, \text{hidden}}^T$ constitutes each row in $P_{\text{hidden} }$, which contains the weights for the neural network to minimize according to (ref{min}). + +After having found $\bm{z}_{i}^{\text{hidden}} $ for every $i$-th neuron within the hidden layer, the vector will be sent to an activation function $a_i(\bm{z})$. + +In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron: + +!bt +f(z) = \frac{1}{1 + \exp{(-z)}} +!et + +It is possible to use other activations functions for the hidden layer also. + +The output $\bm{x}_i^{\text{hidden}}$ from each $i$-th hidden neuron is: + +$$ +\bm{x}_i^{\text{hidden} } = f\big( \bm{z}_{i}^{\text{hidden}} \big) +$$ + +The outputs $\bm{x}_i^{\text{hidden} } $ are then sent to the output layer. + +The output layer consists of one neuron in this case, and combines the +output from each of the neurons in the hidden layers. The output layer +combines the results from the hidden layer using some weights $w_i^{\text{output}}$ +and biases $b_i^{\text{output}}$. In this case, +it is assumes that the number of neurons in the output layer is one. + +!split +===== Final technicalities III ===== + + +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. + +!bt +\begin{aligned} +z_{1,j}^{\text{output}} & = +\begin{pmatrix} +b_1^{\text{output}} & \bm{w}_1^{\text{output}} +\end{pmatrix} +\begin{pmatrix} +1 \\ +\bm{x}_j^{\text{hidden}} +\end{pmatrix} +\end{aligned} +!et + +!split +===== Final technicalities IV ===== + +Expressing $z_{1,j}^{\text{output}}$ as a vector gives the following way of weighting the inputs from the hidden layer: + +!bt +\bm{z}_{1}^{\text{output}} = +\begin{pmatrix} +b_1^{\text{output}} & \bm{w}_1^{\text{output}} +\end{pmatrix} +\begin{pmatrix} +1 & 1 & \dots & 1 \\ +\bm{x}_1^{\text{hidden}} & \bm{x}_2^{\text{hidden}} & \dots & \bm{x}_N^{\text{hidden}} +\end{pmatrix} +!et + +In this case we seek a continuous range of values since we are approximating a function. This means that after computing $\bm{z}_{1}^{\text{output}}$ the neural network has finished its feed forward step, and $\bm{z}_{1}^{\text{output}}$ is the final output of the network. + +!split +===== Back propagation ===== + +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 + +!bt +C(\bm{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 +!et + +In order to minimize the cost function, an optimization method must be chosen. + +Here, gradient descent with a constant step size has been chosen. + +!split +===== Gradient descent ===== + +The idea of the gradient descent algorithm is to update parameters in +a direction where the cost function decreases goes to a minimum. + +In general, the update of some parameters $\bm{\omega}$ given a cost +function defined by some weights $\bm{\omega}$, $C(\bm{x}, +\bm{\omega})$, goes as follows: + +!bt +\bm{\omega}_{\text{new} } = \bm{\omega} - \lambda \nabla_{\bm{\omega}} C(\bm{x}, \bm{\omega}) +!et + +for a number of iterations or until $ \big|\big| \bm{\omega}_{\text{new} } - \bm{\omega} \big|\big|$ becomes smaller than some given tolerance. + +The value of $\lambda$ decides how large steps the algorithm must take +in the direction of $ \nabla_{\bm{\omega}} C(\bm{x}, \bm{\omega})$. +The notation $\nabla_{\bm{\omega}}$ express the gradient with respect +to the elements in $\bm{\omega}$. + +In our case, we have to minimize the cost function $C(\bm{x}, P)$ with +respect to the two sets of weights and biases, that is for the hidden +layer $P_{\text{hidden} }$ and for the output layer $P_{\text{output} +}$ . + +This means that $P_{\text{hidden} }$ and $P_{\text{output} }$ is updated by + +!bt +\begin{aligned} +P_{\text{hidden},\text{new}} &= P_{\text{hidden}} - \lambda \nabla_{P_{\text{hidden}}} C(\bm{x}, P) \\ +P_{\text{output},\text{new}} &= P_{\text{output}} - \lambda \nabla_{P_{\text{output}}} C(\bm{x}, P) +\end{aligned} +!et + +!split +===== The code for solving the ODE ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +# Assuming one input, hidden, and output layer +def neural_network(params, x): + + # Find the weights (including and biases) for the hidden and output layer. + # Assume that params is a list of parameters for each layer. + # The biases are the first element for each array in params, + # and the weights are the remaning elements in each array in params. + + w_hidden = params[0] + w_output = params[1] + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + ## Hidden layer: + + # Add a row of ones to include bias + x_input = np.concatenate((np.ones((1,num_values)), x_input ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_input) + x_hidden = sigmoid(z_hidden) + + ## Output layer: + + # Include bias: + x_hidden = np.concatenate((np.ones((1,num_values)), x_hidden ), axis = 0) + + z_output = np.matmul(w_output, x_hidden) + x_output = z_output + + return x_output + +# The trial solution using the deep neural network: +def g_trial(x,params, g0 = 10): + return g0 + x*neural_network(params,x) + +# The right side of the ODE: +def g(x, g_trial, gamma = 2): + return -gamma*g_trial + +# The cost function: +def cost_function(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial(x,P) + + # Find the derivative w.r.t x of the neural network + d_net_out = elementwise_grad(neural_network,1)(P,x) + + # Find the derivative w.r.t x of the trial function + d_g_t = elementwise_grad(g_trial,0)(x,P) + + # The right side of the ODE + func = g(x, g_t) + + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum / np.size(err_sqr) + +# Solve the exponential decay ODE using neural network with one input, hidden, and output layer +def solve_ode_neural_network(x, num_neurons_hidden, num_iter, lmb): + ## Set up initial weights and biases + + # For the hidden layer + p0 = npr.randn(num_neurons_hidden, 2 ) + + # For the output layer + p1 = npr.randn(1, num_neurons_hidden + 1 ) # +1 since bias is included + + P = [p0, p1] + + print('Initial cost: %g'%cost_function(P, x)) + + ## Start finding the optimal weights using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_grad = grad(cost_function,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of two arrays; + # one for the gradient w.r.t P_hidden and + # one for the gradient w.r.t P_output + cost_grad = cost_function_grad(P, x) + + P[0] = P[0] - lmb * cost_grad[0] + P[1] = P[1] - lmb * cost_grad[1] + + print('Final cost: %g'%cost_function(P, x)) + + return P + +def g_analytic(x, gamma = 2, g0 = 10): + return g0*np.exp(-gamma*x) + +# Solve the given problem +if __name__ == '__main__': + # Set seed such that the weight are initialized + # with same weights and biases for every run. + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + N = 10 + x = np.linspace(0, 1, N) + + ## Set up the initial parameters + num_hidden_neurons = 10 + num_iter = 10000 + lmb = 0.001 + + # Use the network + P = solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb) + + # Print the deviation from the trial solution and true solution + res = g_trial(x,P) + res_analytical = g_analytic(x) + + print('Max absolute difference: %g'%np.max(np.abs(res - res_analytical))) + + # Plot the results + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(x, res_analytical) + plt.plot(x, res[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('x') + plt.ylabel('g(x)') + plt.show() +!ec + + +!split +===== The network with one input layer, specified number of hidden layers, and one output layer ===== + +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. + +The number of neurons within each hidden layer are given as a list of integers in the program below. + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +# The neural network with one input layer and one output layer, +# but with number of hidden layers specified by the user. +def deep_neural_network(deep_params, x): + # N_hidden is the number of hidden layers + # deep_params is a list, len() should be used + N_hidden = len(deep_params) - 1 # -1 since params consists of + # parameters to all the hidden + # layers AND the output layer. + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + +# The trial solution using the deep neural network: +def g_trial_deep(x,params, g0 = 10): + return g0 + x*deep_neural_network(params, x) + +# The right side of the ODE: +def g(x, g_trial, gamma = 2): + return -gamma*g_trial + +# The same cost function as before, but calls deep_neural_network instead. +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the neural network + d_net_out = elementwise_grad(deep_neural_network,1)(P,x) + + # Find the derivative w.r.t x of the trial function + d_g_t = elementwise_grad(g_trial_deep,0)(x,P) + + # The right side of the ODE + func = g(x, g_t) + + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum / np.size(err_sqr) + +# Solve the exponential decay ODE using neural network with one input and one output layer, +# but with specified number of hidden layers from the user. +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # The number of elements in the list num_hidden_neurons thus represents + # the number of hidden layers. + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weights and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weights using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +def g_analytic(x, gamma = 2, g0 = 10): + return g0*np.exp(-gamma*x) + +# Solve the given problem +if __name__ == '__main__': + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + N = 10 + x = np.linspace(0, 1, N) + + ## Set up the initial parameters + num_hidden_neurons = np.array([10,10]) + num_iter = 10000 + lmb = 0.001 + + P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb) + + res = g_trial_deep(x,P) + res_analytical = g_analytic(x) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of a deep neural network solving an ODE compared to the analytical solution') + plt.plot(x, res_analytical) + plt.plot(x, res[0,:]) + plt.legend(['analytical','dnn']) + plt.ylabel('g(x)') + plt.show() +!ec + + +!split +===== Example: Population growth ===== + +A logistic model of population growth assumes that a population converges toward an equilibrium. +The population growth can be modeled by + +!bt +\begin{equation} \label{log} + g'(t) = \alpha g(t)(A - g(t)) +\end{equation} +!et + +where $g(t)$ is the population density at time $t$, $\alpha > 0$ the growth rate and $A > 0$ is the maximum population number in the environment. +Also, at $t = 0$ the population has the size $g(0) = g_0$, where $g_0$ is some chosen constant. + +In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability +and high execution time (this might be more apparent in the examples solving PDEs), +using a library like TensorFlow is recommended. +Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method. + +!split +===== Setting up the problem ===== + +Here, we will model a population $g(t)$ in an environment having carrying capacity $A$. +The population follows the model + +!bt +\begin{equation} \label{solveode_population} +g'(t) = \alpha g(t)(A - g(t)) +\end{equation} +!et + +where $g(0) = g_0$. + +In this example, we let $\alpha = 2$, $A = 1$, and $g_0 = 1.2$. + +!split +===== The trial solution ===== + +We will get a slightly different trial solution, as the boundary conditions are different +compared to the case for exponential decay. + +A possible trial solution satisfying the condition $g(0) = g_0$ could be + +$$ +h_1(t) = g_0 + t \cdot N(t,P) +$$ + +with $N(t,P)$ being the output from the neural network with weights and biases for each layer collected in the set $P$. + +The analytical solution is + +$$ +g(t) = \frac{Ag_0}{g_0 + (A - g_0)\exp(-\alpha A t)} +$$ + +!split +===== The program using Autograd ===== + +The network will be the similar as for the exponential decay example, but with some small modifications for our problem. + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +# Function to get the parameters. +# Done such that one can easily change the paramaters after one's liking. +def get_parameters(): + alpha = 2 + A = 1 + g0 = 1.2 + return alpha, A, g0 + +def deep_neural_network(deep_params, x): + # N_hidden is the number of hidden layers + # deep_params is a list, len() should be used + N_hidden = len(deep_params) - 1 # -1 since params consists of + # parameters to all the hidden + # layers AND the output layer. + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + + + + +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the trial function + d_g_t = elementwise_grad(g_trial_deep,0)(x,P) + + # The right side of the ODE + func = f(x, g_t) + + err_sqr = (d_g_t - func)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum / np.size(err_sqr) + +# The right side of the ODE: +def f(x, g_trial): + alpha,A, g0 = get_parameters() + return alpha*g_trial*(A - g_trial) + +# The trial solution using the deep neural network: +def g_trial_deep(x, params): + alpha,A, g0 = get_parameters() + return g0 + x*deep_neural_network(params,x) + +# The analytical solution: +def g_analytic(t): + alpha,A, g0 = get_parameters() + return A*g0/(g0 + (A - g0)*np.exp(-alpha*A*t)) + +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weigths using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nt = 10 + T = 1 + t = np.linspace(0,T, Nt) + + ## Set up the initial parameters + num_hidden_neurons = [100, 50, 25] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(t,P) + g_analytical = g_analytic(t) + + # Find the maximum absolute difference between the solutons: + diff_ag = np.max(np.abs(g_dnn_ag - g_analytical)) + print("The max absolute difference between the solutions is: %g"%diff_ag) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(t, g_analytical) + plt.plot(t, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('t') + plt.ylabel('g(t)') + + plt.show() +!ec + +!split +===== Using forward Euler to solve the ODE ===== + +A straightforward way of solving an ODE numerically, is to use Euler's method. + +Euler's method uses Taylor series to approximate the value at a function $f$ at a step $\Delta x$ from $x$: + +$$ +f(x + \Delta x) \approx f(x) + \Delta x f'(x) +$$ + +In our case, using Euler's method to approximate the value of $g$ at a step $\Delta t$ from $t$ yields + +!bt +\begin{aligned} + g(t + \Delta t) &\approx g(t) + \Delta t g'(t) \\ + &= g(t) + \Delta t \big(\alpha g(t)(A - g(t))\big) +\end{aligned} +!et +along with the condition that $g(0) = g_0$. + +Let $t_i = i \cdot \Delta t$ where $\Delta t = \frac{T}{N_t-1}$ where $T$ is the final time our solver must solve for and $N_t$ the number of values for $t \in [0, T]$ for $i = 0, \dots, N_t-1$. + +For $i \geq 1$, we have that +!bt +\begin{aligned} +t_i &= i\Delta t \\ +&= (i - 1)\Delta t + \Delta t \\ +&= t_{i-1} + \Delta t +\end{aligned} +!et + +Now, if $g_i = g(t_i)$ then + +!bt +\begin{equation} + \begin{aligned} + g_i &= g(t_i) \\ + &= g(t_{i-1} + \Delta t) \\ + &\approx g(t_{i-1}) + \Delta t \big(\alpha g(t_{i-1})(A - g(t_{i-1}))\big) \\ + &= g_{i-1} + \Delta t \big(\alpha g_{i-1}(A - g_{i-1})\big) + \end{aligned} +\end{equation} \label{odenum} +!et +for $i \geq 1$ and $g_0 = g(t_0) = g(0) = g_0$. + +Equation (ref{odenum}) could be implemented in the following way, +extending the program that uses the network using Autograd: + +!bc pycod +# Assume that all function definitions from the example program using Autograd +# are located here. + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nt = 10 + T = 1 + t = np.linspace(0,T, Nt) + + ## Set up the initial parameters + num_hidden_neurons = [100,50,25] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(t,P) + g_analytical = g_analytic(t) + + # Find the maximum absolute difference between the solutons: + diff_ag = np.max(np.abs(g_dnn_ag - g_analytical)) + print("The max absolute difference between the solutions is: %g"%diff_ag) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(t, g_analytical) + plt.plot(t, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('t') + plt.ylabel('g(t)') + + ## Find an approximation to the funtion using forward Euler + + alpha, A, g0 = get_parameters() + dt = T/(Nt - 1) + + # Perform forward Euler to solve the ODE + g_euler = np.zeros(Nt) + g_euler[0] = g0 + + for i in range(1,Nt): + g_euler[i] = g_euler[i-1] + dt*(alpha*g_euler[i-1]*(A - g_euler[i-1])) + + # Print the errors done by each method + diff1 = np.max(np.abs(g_euler - g_analytical)) + diff2 = np.max(np.abs(g_dnn_ag[0,:] - g_analytical)) + + print('Max absolute difference between Euler method and analytical: %g'%diff1) + print('Max absolute difference between deep neural network and analytical: %g'%diff2) + + # Plot results + plt.figure(figsize=(10,10)) + + plt.plot(t,g_euler) + plt.plot(t,g_analytical) + plt.plot(t,g_dnn_ag[0,:]) + + plt.legend(['euler','analytical','dnn']) + plt.xlabel('Time t') + plt.ylabel('g(t)') + + plt.show() +!ec + + + +!split +===== Example: Solving the one dimensional Poisson equation ===== + +The Poisson equation for $g(x)$ in one dimension is + +!bt +\begin{equation} \label{poisson} + -g''(x) = f(x) +\end{equation} +!et + +where $f(x)$ is a given function for $x \in (0,1)$. + +The conditions that $g(x)$ is chosen to fulfill, are +!bt +\begin{align*} + g(0) &= 0 \\ + g(1) &= 0 +\end{align*} +!et + +This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used. +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. + +!split +===== The specific equation to solve for ===== + +Here, the function $g(x)$ to solve for follows the equation + +!bt +-g''(x) = f(x),\qquad x \in (0,1) +!et + +where $f(x)$ is a given function, along with the chosen conditions + +!bt +\begin{aligned} +g(0) = g(1) = 0 +\end{aligned}\label{cond} +!et + +In this example, we consider the case when $f(x) = (3x + x^2)\exp(x)$. + +For this case, a possible trial solution satisfying the conditions could be + +!bt +g_t(x) = x \cdot (1-x) \cdot N(P,x) +!et + +The analytical solution for this problem is + +!bt +g(x) = x(1 - x)\exp(x) +!et + +!split +===== Solving the equation using Autograd ===== + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # N_hidden is the number of hidden layers + # deep_params is a list, len() should be used + N_hidden = len(deep_params) - 1 # -1 since params consists of + # parameters to all the hidden + # layers AND the output layer. + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + + +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weigths using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +## Set up the cost function specified for this Poisson equation: + +# The right side of the ODE +def f(x): + return (3*x + x**2)*np.exp(x) + +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the trial function + d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P) + + right_side = f(x) + + err_sqr = (-d2_g_t - right_side)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum/np.size(err_sqr) + +# The trial solution: +def g_trial_deep(x,P): + return x*(1-x)*deep_neural_network(P,x) + +# The analytic solution; +def g_analytic(x): + return x*(1-x)*np.exp(x) + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nx = 10 + x = np.linspace(0,1, Nx) + + ## Set up the initial parameters + num_hidden_neurons = [200,100] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(x,P) + g_analytical = g_analytic(x) + + # Find the maximum absolute difference between the solutons: + max_diff = np.max(np.abs(g_dnn_ag - g_analytical)) + print("The max absolute difference between the solutions is: %g"%max_diff) + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(x, g_analytical) + plt.plot(x, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('x') + plt.ylabel('g(x)') + plt.show() +!ec + +!split +===== Comparing with a numerical scheme ===== + +The Poisson equation is possible to solve using Taylor series to approximate the second derivative. + +Using Taylor series, the second derivative can be expressed as + +$$ +g''(x) = \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} + E_{\Delta x}(x) +$$ + +where $\Delta x$ is a small step size and $E_{\Delta x}(x)$ being the error term. + +Looking away from the error terms gives an approximation to the second derivative: + +!bt +\begin{equation} \label{approx} +g''(x) \approx \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} +\end{equation} +!et + +If $x_i = i \Delta x = x_{i-1} + \Delta x$ and $g_i = g(x_i)$ for $i = 1,\dots N_x - 2$ with $N_x$ being the number of values for $x$, (ref{approx}) becomes + +!bt +\begin{aligned} +g''(x_i) &\approx \frac{g(x_i + \Delta x) - 2g(x_i) + g(x_i -\Delta x)}{\Delta x^2} \\ +&= \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2} +\end{aligned} +!et + +Since we know from our problem that + +!bt +\begin{aligned} +-g''(x) &= f(x) \\ +&= (3x + x^2)\exp(x) +\end{aligned} +!et + +along with the conditions $g(0) = g(1) = 0$, +the following scheme can be used to find an approximate solution for $g(x)$ numerically: + +!bt +\begin{equation} + \begin{aligned} + -\Big( \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2} \Big) &= f(x_i) \\ + -g_{i+1} + 2g_i - g_{i-1} &= \Delta x^2 f(x_i) + \end{aligned} +\end{equation} \label{odesys} +!et + +for $i = 1, \dots, N_x - 2$ where $g_0 = g_{N_x - 1} = 0$ and $f(x_i) = (3x_i + x_i^2)\exp(x_i)$, which is given for our specific problem. + +The equation can be rewritten into a matrix equation: + +!bt +\begin{aligned} +\begin{pmatrix} +2 & -1 & 0 & \dots & 0 \\ +-1 & 2 & -1 & \dots & 0 \\ +\vdots & & \ddots & & \vdots \\ +0 & \dots & -1 & 2 & -1 \\ +0 & \dots & 0 & -1 & 2\\ +\end{pmatrix} +\begin{pmatrix} +g_1 \\ +g_2 \\ +\vdots \\ +g_{N_x - 3} \\ +g_{N_x - 2} +\end{pmatrix} +&= +\Delta x^2 +\begin{pmatrix} +f(x_1) \\ +f(x_2) \\ +\vdots \\ +f(x_{N_x - 3}) \\ +f(x_{N_x - 2}) +\end{pmatrix} \\ +\bm{A}\bm{g} &= \bm{f}, +\end{aligned} +!et + +which makes it possible to solve for the vector $\bm{g}$. + +!split +===== Setting up the code ===== + +We can then compare the result from this numerical scheme with the output from our network using Autograd: + +!bc pycod +import autograd.numpy as np +from autograd import grad, elementwise_grad +import autograd.numpy.random as npr +from matplotlib import pyplot as plt + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # N_hidden is the number of hidden layers + # deep_params is a list, len() should be used + N_hidden = len(deep_params) - 1 # -1 since params consists of + # parameters to all the hidden + # layers AND the output layer. + + # Assumes input x being an one-dimensional array + num_values = np.size(x) + x = x.reshape(-1, num_values) + + # Assume that the input layer does nothing to the input x + x_input = x + + # Due to multiple hidden layers, define a variable referencing to the + # output of the previous layer: + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output + + +def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb): + # num_hidden_neurons is now a list of number of neurons within each hidden layer + + # Find the number of hidden layers: + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 ) + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: %g'%cost_function_deep(P, x)) + + ## Start finding the optimal weigths using gradient descent + + # Find the Python function that represents the gradient of the cost function + # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer + cost_function_deep_grad = grad(cost_function_deep,0) + + # Let the update be done num_iter times + for i in range(num_iter): + # Evaluate the gradient at the current weights and biases in P. + # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases + # in the hidden layers and output layers evaluated at x. + cost_deep_grad = cost_function_deep_grad(P, x) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_deep_grad[l] + + print('Final cost: %g'%cost_function_deep(P, x)) + + return P + +## Set up the cost function specified for this Poisson equation: + +# The right side of the ODE +def f(x): + return (3*x + x**2)*np.exp(x) + +def cost_function_deep(P, x): + + # Evaluate the trial function with the current parameters P + g_t = g_trial_deep(x,P) + + # Find the derivative w.r.t x of the trial function + d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P) + + right_side = f(x) + + err_sqr = (-d2_g_t - right_side)**2 + cost_sum = np.sum(err_sqr) + + return cost_sum/np.size(err_sqr) + +# The trial solution: +def g_trial_deep(x,P): + return x*(1-x)*deep_neural_network(P,x) + +# The analytic solution; +def g_analytic(x): + return x*(1-x)*np.exp(x) + +if __name__ == '__main__': + npr.seed(4155) + + ## Decide the vales of arguments to the function to solve + Nx = 10 + x = np.linspace(0,1, Nx) + + ## Set up the initial parameters + num_hidden_neurons = [200,100] + num_iter = 1000 + lmb = 1e-3 + + P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb) + + g_dnn_ag = g_trial_deep(x,P) + g_analytical = g_analytic(x) + + # Find the maximum absolute difference between the solutons: + + plt.figure(figsize=(10,10)) + + plt.title('Performance of neural network solving an ODE compared to the analytical solution') + plt.plot(x, g_analytical) + plt.plot(x, g_dnn_ag[0,:]) + plt.legend(['analytical','nn']) + plt.xlabel('x') + plt.ylabel('g(x)') + + ## Perform the computation using the numerical scheme + + dx = 1/(Nx - 1) + + # Set up the matrix A + A = np.zeros((Nx-2,Nx-2)) + + A[0,0] = 2 + A[0,1] = -1 + + for i in range(1,Nx-3): + A[i,i-1] = -1 + A[i,i] = 2 + A[i,i+1] = -1 + + A[Nx - 3, Nx - 4] = -1 + A[Nx - 3, Nx - 3] = 2 + + # Set up the vector f + f_vec = dx**2 * f(x[1:-1]) + + # Solve the equation + g_res = np.linalg.solve(A,f_vec) + + g_vec = np.zeros(Nx) + g_vec[1:-1] = g_res + + # Print the differences between each method + max_diff1 = np.max(np.abs(g_dnn_ag - g_analytical)) + max_diff2 = np.max(np.abs(g_vec - g_analytical)) + print("The max absolute difference between the analytical solution and DNN Autograd: %g"%max_diff1) + print("The max absolute difference between the analytical solution and numerical scheme: %g"%max_diff2) + + # Plot the results + plt.figure(figsize=(10,10)) + + plt.plot(x,g_vec) + plt.plot(x,g_analytical) + plt.plot(x,g_dnn_ag[0,:]) + + plt.legend(['numerical scheme','analytical','dnn']) + plt.show() + +!ec + + + +!split +===== Partial Differential Equations ===== + +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 +respect to. + +In general, a partial differential equation for a function $g(x_1,\dots,x_N)$ with $N$ variables may be expressed as + +!bt +\begin{equation} \label{PDE} + f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) = 0 +\end{equation} +!et + +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. + +!split +===== Type of problem ===== + +The problem our network must solve for, is similar to the ODE case. +We must have a trial solution $g_t$ at hand. + +For instance, the trial solution could be expressed as +!bt +\begin{align*} + g_t(x_1,\dots,x_N) = h_1(x_1,\dots,x_N) + h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) +\end{align*} +!et +where $h_1(x_1,\dots,x_N)$ is a function that ensures $g_t(x_1,\dots,x_N)$ satisfies some given conditions. +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. + + +!split +===== Network requirements ===== + +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 +of parameters $P$ such that the expression $f$ in (ref{PDE}) is as +close to zero as possible. + +As for the ODE case, the cost function is the mean squared error that +the network must try to minimize. The cost function for the network to +minimize is + +!bt +\begin{equation*} +C\left(x_1, \dots, x_N, P\right) = \left( f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) \right)^2 +\end{equation*} +!et + +!split +===== More details ===== + +If we let $\bm{x} = \big( x_1, \dots, x_N \big)$ be an array containing the values for $x_1, \dots, x_N$ respectively, the cost function can be reformulated into the following: +!bt +\[ + C\left(\bm{x}, P\right) = f\left( \left( \bm{x}, \frac{\partial g(\bm{x}) }{\partial x_1}, \dots , \frac{\partial g(\bm{x}) }{\partial x_N}, \frac{\partial g(\bm{x}) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\bm{x}) }{\partial x_N^n} \right) \right)^2 +\] +!et + +If we also have $M$ different sets of values for $x_1, \dots, x_N$, that is $\bm{x}_i = \big(x_1^{(i)}, \dots, x_N^{(i)}\big)$ for $i = 1,\dots,M$ being the rows in matrix $X$, the cost function can be generalized into +!bt +\begin{equation*} +C\left(X, P \right) = \sum_{i=1}^M f\left( \left( \bm{x}_i, \frac{\partial g(\bm{x}_i) }{\partial x_1}, \dots , \frac{\partial g(\bm{x}_i) }{\partial x_N}, \frac{\partial g(\bm{x}_i) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\bm{x}_i) }{\partial x_N^n} \right) \right)^2. +\end{equation*} +!et + +!split +===== Example: The diffusion equation ===== + +In one spatial dimension, the equation reads +!bt +\begin{equation*} + \frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation*} +!et + +where a possible choice of conditions are +!bt +\begin{align*} +g(0,t) &= 0 ,\qquad t \geq 0 \\ +g(1,t) &= 0, \qquad t \geq 0 \\ +g(x,0) &= u(x),\qquad x\in [0,1] +\end{align*} +!et +with $u(x)$ being some given function. + +!split +===== Defining the problem ===== + +For this case, we want to find $g(x,t)$ such that + +!bt +\begin{equation} + \frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation} \label{diffonedim} +!et + +and + +!bt +\begin{align*} +g(0,t) &= 0 ,\qquad t \geq 0 \\ +g(1,t) &= 0, \qquad t \geq 0 \\ +g(x,0) &= u(x),\qquad x\in [0,1] +\end{align*} +!et +with $u(x) = \sin(\pi x)$. + +First, let us set up the deep neural network. +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. + + + +!split +===== Setting up the network using Autograd ===== + +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$ +and position $x$. The variables will be represented by a +one-dimensional array in the program. The program will evaluate the +network at each possible pair $(x,t)$, given an array for the desired +$x$-values and $t$-values to approximate the solution at. + +!bc pycod +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # x is now a point and a 1D numpy array; make it a column vector + num_coordinates = np.size(x,0) + x = x.reshape(num_coordinates,-1) + + num_points = np.size(x,1) + + # N_hidden is the number of hidden layers + N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assume that the input layer does nothing to the input x + x_input = x + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output[0][0] +!ec + +!split +===== Setting up the network using Autograd; The trial solution ===== + +The cost function must then iterate through the given arrays +containing values for $x$ and $t$, defines a point $(x,t)$ the deep +neural network and the trial solution is evaluated at, and then finds +the Jacobian of the trial solution. + +A possible trial solution for this PDE is + +$$ +g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P) +$$ + +with $A(x,t)$ being a function ensuring that $g_t(x,t)$ satisfies our given conditions, and $N(x,t,P)$ being the output from the deep neural network using weights and biases for each layer from $P$. + +To fulfill the conditions, $A(x,t)$ could be: + +$$ +h_1(x,t) = (1-t)\Big(u(x) - \big((1-x)u(0) + x u(1)\big)\Big) = (1-t)u(x) = (1-t)\sin(\pi x) +$$ +since $(0) = u(1) = 0$ and $u(x) = \sin(\pi x)$. + +!split +===== Why the jacobian? ===== + +The Jacobian is used because the program must find the derivative of +the trial solution with respect to $x$ and $t$. + +This gives the necessity of computing the Jacobian matrix, as we want +to evaluate the gradient with respect to $x$ and $t$ (note that the +Jacobian of a scalar-valued multivariate function is simply its +gradient). + +In Autograd, the differentiation is by default done with respect to +the first input argument of your Python function. Since the points is +an array representing $x$ and $t$, the Jacobian is calculated using +the values of $x$ and $t$. + +To find the second derivative with respect to $x$ and $t$, the +Jacobian can be found for the second time. The result is a Hessian +matrix, which is the matrix containing all the possible second order +mixed derivatives of $g(x,t)$. + +!bc pycod +# Set up the trial function: +def u(x): + return np.sin(np.pi*x) + +def g_trial(point,P): + x,t = point + return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point) + +# The right side of the ODE: +def f(point): + return 0. + +# The cost function: +def cost_function(P, x, t): + cost_sum = 0 + + g_t_jacobian_func = jacobian(g_trial) + g_t_hessian_func = hessian(g_trial) + + for x_ in x: + for t_ in t: + point = np.array([x_,t_]) + + g_t = g_trial(point,P) + g_t_jacobian = g_t_jacobian_func(point,P) + g_t_hessian = g_t_hessian_func(point,P) + + g_t_dt = g_t_jacobian[1] + g_t_d2x = g_t_hessian[0][0] + + func = f(point) + + err_sqr = ( (g_t_dt - g_t_d2x) - func)**2 + cost_sum += err_sqr + + return cost_sum +!ec + +!split +===== Setting up the network using Autograd; The full program ===== + +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. + +The analytical solution of our problem is + +$$ +g(x,t) = \exp(-\pi^2 t)\sin(\pi x) +$$ + +A possible way to implement a neural network solving the PDE, is given below. +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! + +!bc pycod +import autograd.numpy as np +from autograd import jacobian,hessian,grad +import autograd.numpy.random as npr +from matplotlib import cm +from matplotlib import pyplot as plt +from mpl_toolkits.mplot3d import axes3d + +## Set up the network + +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # x is now a point and a 1D numpy array; make it a column vector + num_coordinates = np.size(x,0) + x = x.reshape(num_coordinates,-1) + + num_points = np.size(x,1) + + # N_hidden is the number of hidden layers + N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assume that the input layer does nothing to the input x + x_input = x + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output[0][0] + +## Define the trial solution and cost function +def u(x): + return np.sin(np.pi*x) + +def g_trial(point,P): + x,t = point + return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point) + +# The right side of the ODE: +def f(point): + return 0. + +# The cost function: +def cost_function(P, x, t): + cost_sum = 0 + + g_t_jacobian_func = jacobian(g_trial) + g_t_hessian_func = hessian(g_trial) + + for x_ in x: + for t_ in t: + point = np.array([x_,t_]) + + g_t = g_trial(point,P) + g_t_jacobian = g_t_jacobian_func(point,P) + g_t_hessian = g_t_hessian_func(point,P) + + g_t_dt = g_t_jacobian[1] + g_t_d2x = g_t_hessian[0][0] + + func = f(point) + + err_sqr = ( (g_t_dt - g_t_d2x) - func)**2 + cost_sum += err_sqr + + return cost_sum /( np.size(x)*np.size(t) ) + +## For comparison, define the analytical solution +def g_analytic(point): + x,t = point + return np.exp(-np.pi**2*t)*np.sin(np.pi*x) + +## Set up a function for training the network to solve for the equation +def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb): + ## Set up initial weigths and biases + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: ',cost_function(P, x, t)) + + cost_function_grad = grad(cost_function,0) + + # Let the update be done num_iter times + for i in range(num_iter): + cost_grad = cost_function_grad(P, x , t) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_grad[l] + + print('Final cost: ',cost_function(P, x, t)) + + return P + +if __name__ == '__main__': + ### Use the neural network: + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + Nx = 10; Nt = 10 + x = np.linspace(0, 1, Nx) + t = np.linspace(0,1,Nt) + + ## Set up the parameters for the network + num_hidden_neurons = [100, 25] + num_iter = 250 + lmb = 0.01 + + P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb) + + ## Store the results + g_dnn_ag = np.zeros((Nx, Nt)) + G_analytical = np.zeros((Nx, Nt)) + for i,x_ in enumerate(x): + for j, t_ in enumerate(t): + point = np.array([x_, t_]) + g_dnn_ag[i,j] = g_trial(point,P) + + G_analytical[i,j] = g_analytic(point) + + # Find the map difference between the analytical and the computed solution + diff_ag = np.abs(g_dnn_ag - G_analytical) + print('Max absolute difference between the analytical solution and the network: %g'%np.max(diff_ag)) + + ## Plot the solutions in two dimensions, that being in position and time + + T,X = np.meshgrid(t,x) + + fig = plt.figure(figsize=(10,10)) + ax = fig.add_suplot(projection='3d') + ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons)) + s = ax.plot_surface(T,X,g_dnn_ag,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + + fig = plt.figure(figsize=(10,10)) + ax = fig.add_suplot(projection='3d') + ax.set_title('Analytical solution') + s = ax.plot_surface(T,X,G_analytical,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + fig = plt.figure(figsize=(10,10)) + ax = fig.add_suplot(projection='3d') + ax.set_title('Difference') + s = ax.plot_surface(T,X,diff_ag,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + ## Take some slices of the 3D plots just to see the solutions at particular times + indx1 = 0 + indx2 = int(Nt/2) + indx3 = Nt-1 + + t1 = t[indx1] + t2 = t[indx2] + t3 = t[indx3] + + # Slice the results from the DNN + res1 = g_dnn_ag[:,indx1] + res2 = g_dnn_ag[:,indx2] + res3 = g_dnn_ag[:,indx3] + + # Slice the analytical results + res_analytical1 = G_analytical[:,indx1] + res_analytical2 = G_analytical[:,indx2] + res_analytical3 = G_analytical[:,indx3] + + # Plot the slices + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t1) + plt.plot(x, res1) + plt.plot(x,res_analytical1) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t2) + plt.plot(x, res2) + plt.plot(x,res_analytical2) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t3) + plt.plot(x, res3) + plt.plot(x,res_analytical3) + plt.legend(['dnn','analytical']) + + plt.show() +!ec + +!split +===== Example: Solving the wave equation with Neural Networks ===== + +The wave equation is +!bt +\begin{equation*} + \frac{\partial^2 g(x,t)}{\partial t^2} = c^2\frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation*} +!et + +with $c$ being the specified wave speed. + +Here, the chosen conditions are +!bt +\begin{align*} + g(0,t) &= 0 \\ + g(1,t) &= 0 \\ + g(x,0) &= u(x) \\ + \frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} &= v(x) +\end{align*} +!et +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. + +!split +===== The problem to solve for ===== + +The wave equation to solve for, is + +!bt +\begin{equation} \label{wave} +\frac{\partial^2 g(x,t)}{\partial t^2} = c^2 \frac{\partial^2 g(x,t)}{\partial x^2} +\end{equation} +!et + +where $c$ is the given wave speed. +The chosen conditions for this equation are + +!bt +\begin{aligned} +g(0,t) &= 0, &t \geq 0 \\ +g(1,t) &= 0, &t \geq 0 \\ +g(x,0) &= u(x), &x\in[0,1] \\ +\frac{\partial g(x,t)}{\partial t}\Big |_{t = 0} &= v(x), &x \in [0,1] +\end{aligned} \label{condwave} +!et + +In this example, let $c = 1$ and $u(x) = \sin(\pi x)$ and $v(x) = -\pi\sin(\pi x)$. + + +!split +===== The trial solution ===== +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 (ref{condwave}) and the cost function. + +The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution $g_t(x,t)$ is + +$$ +g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P) +$$ + +where + +$$ +h_1(x,t) = (1-t^2)u(x) + tv(x) +$$ + +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. + +!split +===== The analytical solution ===== + +The analytical solution for our specific problem, is + +$$ +g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t) +$$ + +!split +===== Solving the wave equation - the full program using Autograd ===== + +!bc pycod +import autograd.numpy as np +from autograd import hessian,grad +import autograd.numpy.random as npr +from matplotlib import cm +from matplotlib import pyplot as plt +from mpl_toolkits.mplot3d import axes3d + +## Set up the trial function: +def u(x): + return np.sin(np.pi*x) + +def v(x): + return -np.pi*np.sin(np.pi*x) + +def h1(point): + x,t = point + return (1 - t**2)*u(x) + t*v(x) + +def g_trial(point,P): + x,t = point + return h1(point) + x*(1-x)*t**2*deep_neural_network(P,point) + +## Define the cost function +def cost_function(P, x, t): + cost_sum = 0 + + g_t_hessian_func = hessian(g_trial) + + for x_ in x: + for t_ in t: + point = np.array([x_,t_]) + + g_t_hessian = g_t_hessian_func(point,P) + + g_t_d2x = g_t_hessian[0][0] + g_t_d2t = g_t_hessian[1][1] + + err_sqr = ( (g_t_d2t - g_t_d2x) )**2 + cost_sum += err_sqr + + return cost_sum / (np.size(t) * np.size(x)) + +## The neural network +def sigmoid(z): + return 1/(1 + np.exp(-z)) + +def deep_neural_network(deep_params, x): + # x is now a point and a 1D numpy array; make it a column vector + num_coordinates = np.size(x,0) + x = x.reshape(num_coordinates,-1) + + num_points = np.size(x,1) + + # N_hidden is the number of hidden layers + N_hidden = len(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer + + # Assume that the input layer does nothing to the input x + x_input = x + x_prev = x_input + + ## Hidden layers: + + for l in range(N_hidden): + # From the list of parameters P; find the correct weigths and bias for this layer + w_hidden = deep_params[l] + + # Add a row of ones to include bias + x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0) + + z_hidden = np.matmul(w_hidden, x_prev) + x_hidden = sigmoid(z_hidden) + + # Update x_prev such that next layer can use the output from this layer + x_prev = x_hidden + + ## Output layer: + + # Get the weights and bias for this layer + w_output = deep_params[-1] + + # Include bias: + x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0) + + z_output = np.matmul(w_output, x_prev) + x_output = z_output + + return x_output[0][0] + +## The analytical solution +def g_analytic(point): + x,t = point + return np.sin(np.pi*x)*np.cos(np.pi*t) - np.sin(np.pi*x)*np.sin(np.pi*t) + +def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb): + ## Set up initial weigths and biases + N_hidden = np.size(num_neurons) + + ## Set up initial weigths and biases + + # Initialize the list of parameters: + P = [None]*(N_hidden + 1) # + 1 to include the output layer + + P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias + for l in range(1,N_hidden): + P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias + + # For the output layer + P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included + + print('Initial cost: ',cost_function(P, x, t)) + + cost_function_grad = grad(cost_function,0) + + # Let the update be done num_iter times + for i in range(num_iter): + cost_grad = cost_function_grad(P, x , t) + + for l in range(N_hidden+1): + P[l] = P[l] - lmb * cost_grad[l] + + + print('Final cost: ',cost_function(P, x, t)) + + return P + +if __name__ == '__main__': + ### Use the neural network: + npr.seed(15) + + ## Decide the vales of arguments to the function to solve + Nx = 10; Nt = 10 + x = np.linspace(0, 1, Nx) + t = np.linspace(0,1,Nt) + + ## Set up the parameters for the network + num_hidden_neurons = [50,20] + num_iter = 1000 + lmb = 0.01 + + P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb) + + ## Store the results + res = np.zeros((Nx, Nt)) + res_analytical = np.zeros((Nx, Nt)) + for i,x_ in enumerate(x): + for j, t_ in enumerate(t): + point = np.array([x_, t_]) + res[i,j] = g_trial(point,P) + + res_analytical[i,j] = g_analytic(point) + + diff = np.abs(res - res_analytical) + print("Max difference between analytical and solution from nn: %g"%np.max(diff)) + + ## Plot the solutions in two dimensions, that being in position and time + + T,X = np.meshgrid(t,x) + + fig = plt.figure(figsize=(10,10)) + ax = fig.add_suplot(projection='3d') + ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons)) + s = ax.plot_surface(T,X,res,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + + fig = plt.figure(figsize=(10,10)) + ax = fig.add_suplot(projection='3d') + ax.set_title('Analytical solution') + s = ax.plot_surface(T,X,res_analytical,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + + fig = plt.figure(figsize=(10,10)) + ax = fig.add_suplot(projection='3d') + ax.set_title('Difference') + s = ax.plot_surface(T,X,diff,linewidth=0,antialiased=False,cmap=cm.viridis) + ax.set_xlabel('Time $t$') + ax.set_ylabel('Position $x$'); + + ## Take some slices of the 3D plots just to see the solutions at particular times + indx1 = 0 + indx2 = int(Nt/2) + indx3 = Nt-1 + + t1 = t[indx1] + t2 = t[indx2] + t3 = t[indx3] + + # Slice the results from the DNN + res1 = res[:,indx1] + res2 = res[:,indx2] + res3 = res[:,indx3] + + # Slice the analytical results + res_analytical1 = res_analytical[:,indx1] + res_analytical2 = res_analytical[:,indx2] + res_analytical3 = res_analytical[:,indx3] + + # Plot the slices + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t1) + plt.plot(x, res1) + plt.plot(x,res_analytical1) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t2) + plt.plot(x, res2) + plt.plot(x,res_analytical2) + plt.legend(['dnn','analytical']) + + plt.figure(figsize=(10,10)) + plt.title("Computed solutions at time = %g"%t3) + plt.plot(x, res3) + plt.plot(x,res_analytical3) + plt.legend(['dnn','analytical']) + + plt.show() +!ec + +!split +===== Resources on differential equations and deep learning ===== + +o "Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al":"https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf" +o "Neural networks for solving differential equations by A. Honchar":"https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c" +o "Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener":"http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf" +o "Introduction to Partial Differential Equations by A. Tveito, R. Winther":"https://www.springer.com/us/book/9783540225515" + + + + + + diff --git a/doc/src/week43/exercisesweek43.do.txt b/doc/src/week43/exercisesweek43.do.txt index 105d59dd8..a82a92316 100644 --- a/doc/src/week43/exercisesweek43.do.txt +++ b/doc/src/week43/exercisesweek43.do.txt @@ -1,1284 +1,283 @@ -TITLE: Exercises weeks 43 and 44 -AUTHOR: October 23-27, 2023 -DATE: Deadline is Sunday November 5 at midnight +TITLE: Exercises week 43 +AUTHOR: October 20-24, 2025 +DATE: Deadline Friday October 24 at midnight -You can hand in the exercises from week 43 and week 44 as one exercise and get a total score of two additional points. ======= Overarching aims of the exercises weeks 43 and 44 ======= -The aim of the exercises this week and next week is to get started with writing a neural network code -of relevance for project 2. +The aim of the exercises this week is to gain some confidence with +ways to visualize the results of a classification problem. We will +target three ways of setting up the analysis. The first and simplest +one is the +o so-called confusion matrix, and the next is the +o ROC curve and finally the +o Cumulative gain curve. +We will use Logistic Regression as method for the classification in +this exercise. You can compare these results with those obtained with +your neural network code from project 2 without a hidden layer. -During week 41 we discussed three different types of gates, the -so-called XOR, the OR and the AND gates. In order to develop a code -for neural networks, it can be useful to set up a simpler system with -only two inputs and one output. This can make it easier to debug and -study the feed forward pass and the back propagation part. In the -exercise this and next week, we propose to study this system with just -one hidden layer and two hidden nodes. There is only one output node -and we can choose to use either a simple regression case (fitting a -line) or just a binary classification case with the cross-entropy as -cost function. +In these exercises we will use binary and multi-class data sets +(the Iris data set from week 41). +The underlying mathematics is described here. -Their inputs and outputs can be -summarized using the following tables, first for the OR gate with -inputs $x_1$ and $x_2$ and outputs $y$: - -|---------------------| -| $x_1$ | $x_2$ | $y$ | -|---------------------| -| 0 | 0 | 0 | -| 0 | 1 | 1 | -| 1 | 0 | 1 | -| 1 | 1 | 1 | -|---------------------| - -!split -===== The AND and XOR Gates ===== - -The AND gate is defined as - -|---------------------| -| $x_1$ | $x_2$ | $y$ | -|---------------------| -| 0 | 0 | 0 | -| 0 | 1 | 0 | -| 1 | 0 | 0 | -| 1 | 1 | 1 | -|---------------------| - -And finally we have the XOR gate - -|---------------------| -| $x_1$ | $x_2$ | $y$ | -|---------------------| -| 0 | 0 | 0 | -| 0 | 1 | 1 | -| 1 | 0 | 1 | -| 1 | 1 | 0 | -|---------------------| - -!split -===== Representing the Data Sets ===== - -Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads +=== Confusion Matrix === +A _confusion matrix_ summarizes a classifier’s performance by +tabulating predictions versus true labels. For binary classification, +it is a $2\times2$ table whose entries are counts of outcomes: !bt -\bm{X}=\begin{bmatrix} 0 & 0 \\ - 0 & 1 \\ - 1 & 0 \\ - 1 & 1 \end{bmatrix}, +\[ +\begin{array}{l|cc} & \text{Predicted Positive} & \text{Predicted Negative} \\ \hline \text{Actual Positive} & TP & FN \\ \text{Actual Negative} & FP & TN \end{array}. +\] !et -while the vector of outputs is $\bm{y}^T=[0,1,1,0]$ for the XOR gate, $\bm{y}^T=[0,0,0,1]$ for the AND gate and $\bm{y}^T=[0,1,1,1]$ for the OR gate. - - - -Your tasks here are - -o Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs. -o Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function. -o Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output. -o Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets. -o Set up the cost function (cross entropy for classification of binary cases). -o Calculate the gradients needed for the back propagation part. -o Use the gradients to train the network in the back propagation part. Think of using automatic differentiation. -o Train the network and study your results and compare with results obtained either with _scikit-learn_ or _TensorFlow_. - -Everything you develop here can be used directly into the code for the project. - - -!split -===== Setting up dimensionalities by hand ===== - -It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by -!bt -\bm{W_h}=\begin{bmatrix} 1 & 1 \\ - 1 & 1 \end{bmatrix}, -!et - -Multiplying $\bm{X}$ and $\bm{W}$ gives +Here TP (true positives) is the number of cases correctly predicted as +positive, FP (false positives) is the number incorrectly predicted as +positive, TN (true negatives) is correctly predicted negative, and FN +(false negatives) is incorrectly predicted negative . In other words, +“positive” means class 1 and “negative” means class 0; for example, TP +occurs when the prediction and actual are both positive. Formally: !bt -\bm{X}{W}_h=\begin{bmatrix} 0 & 0 \\ - 1 & 1 \\ - 1 & 1 \\ - 2 & 2 \end{bmatrix}, +\[ +\text{TPR} = \frac{\text{TP}}{\text{TP} + \text{FN}}, \quad \text{FPR} = \frac{\text{FP}}{\text{FP} + \text{TN}}, +\] !et -Assume also that the bias vector for the hidden layer is +where TPR and FPR are the true and false positive rates defined below. + +In multiclass classification with $K$ classes, the confusion matrix +generalizes to a $K\times K$ table. Entry $N_{ij}$ in the table is +the count of instances whose true class is $i$ and whose predicted +class is $j$. For example, a three-class confusion matrix can be written +as: + !bt -\bm{b}_h=\begin{bmatrix} 0 \\ - -1\end{bmatrix}, +\[ +\begin{array}{c|ccc} & \text{Pred Class 1} & \text{Pred Class 2} & \text{Pred Class 3} \\ \hline \text{Act Class 1} & N_{11} & N_{12} & N_{13} \\ \text{Act Class 2} & N_{21} & N_{22} & N_{23} \\ \text{Act Class 3} & N_{31} & N_{32} & N_{33} \end{array}. +\] !et -Adding it gives us the input to the activation function of the hidden layer + +Here the diagonal entries $N_{ii}$ are the true positives for each +class, and off-diagonal entries are misclassifications. This matrix +allows computation of per-class metrics: e.g. for class $i$, +$\mathrm{TP}_i=N_{ii}$, $\mathrm{FN}_i=\sum_{j\neq i}N_{ij}$, +$\mathrm{FP}_i=\sum_{j\neq i}N_{ji}$, and $\mathrm{TN}_i$ is the sum of +all remaining entries. + +As defined above, TPR and FPR come from the binary case. In binary +terms with $P$ actual positives and $N$ actual negatives, one has !bt -\bm{z}_h=\bm{X}\bm{W}_h+\bm{b}_h=\begin{bmatrix} 0 & -1 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, +\[ +\text{TPR} = \frac{TP}{P} = \frac{TP}{TP+FN}, \quad \text{FPR} = +\frac{FP}{N} = \frac{FP}{FP+TN}, +\] !et +as used in standard confusion-matrix +formulations. These rates will be used in constructing ROC curves. -Let us then assume that our activation function is the RELU function, which simply means that we take the max of $0$ and the elements of the input argument $\bm{z}_h$, that is we have +=== ROC Curve === + +The Receiver Operating Characteristic (ROC) curve plots the trade-off +between true positives and false positives as a discrimination +threshold varies. Specifically, for a binary classifier that outputs +a score or probability, one varies the threshold $t$ for declaring +_positive_, and computes at each $t$ the true positive rate +$\mathrm{TPR}(t)$ and false positive rate $\mathrm{FPR}(t)$ using the +confusion matrix at that threshold. The ROC curve is then the graph +of TPR versus FPR. By definition, !bt -\bm{a}_h=\mathrm{RELU}(\bm{z}_h=\bm{X}\bm{W}_h+\bm{b}_h)=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}, +\[ +\mathrm{TPR} = \frac{TP}{TP+FN}, \qquad \mathrm{FPR} = \frac{FP}{FP+TN}, +\] !et -Assume also that the bias of the output layer is zero and that the weights of the output layer are + +where $TP,FP,TN,FN$ are counts determined by threshold $t$. A perfect +classifier would reach the point (FPR=0, TPR=1) at some threshold. + +Formally, the ROC curve is obtained by plotting +$(\mathrm{FPR}(t),\mathrm{TPR}(t))$ for all $t\in[0,1]$ (or as $t$ +sweeps through the sorted scores). The Area Under the ROC Curve (AUC) +quantifies the average performance over all thresholds. It can be +interpreted probabilistically: $\mathrm{AUC} = +\Pr\bigl(s(X^+)>s(X^-)\bigr)$, the probability that a random positive +instance $X^+$ receives a higher score $s$ than a random negative +instance $X^-$ . Equivalently, the AUC is the integral under the ROC +curve: + !bt -\bm{w}_o=\begin{bmatrix} 1 \\ - -2\end{bmatrix}, +\[ +\mathrm{AUC} \;=\; \int_{0}^{1} \mathrm{TPR}(f)\,df, +\] !et -and multiplying with $\bm{a}_h$ gives the output +where $f$ ranges over FPR (or fraction of negatives). A model that guesses at random yields a diagonal ROC (AUC=0.5), whereas a perfect model yields AUC=1.0. + +=== Cumulative Gain === + +The cumulative gain curve (or gains chart) evaluates how many +positives are captured as one targets an increasing fraction of the +population, sorted by model confidence. To construct it, sort all +instances by decreasing predicted probability of the positive class. +Then, for the top $\alpha$ fraction of instances, compute the fraction +of all actual positives that fall in this subset. In formula form, if +$P$ is the total number of positive instances and $P(\alpha)$ is the +number of positives among the top $\alpha$ of the data, the cumulative +gain at level $\alpha$ is !bt -\bm{a}_o=\begin{bmatrix} 0 & 0 \\ - 1 & 0 \\ - 1 & 0 \\ - 2 & 1 \end{bmatrix}\begin{bmatrix} 1 \\ - -2\end{bmatrix}=\begin{bmatrix} 0 \\ 1 \\ 1 \\0\end{bmatrix}, +\[ +\mathrm{Gain}(\alpha) \;=\; \frac{P(\alpha)}{P}. +\] !et -the wanted result. Pay attention to the dimensionalities as well. + +For example, cutting off at the top 10% of predictions yields a gain +equal to (positives in top 10%) divided by (total positives) . +Plotting $\mathrm{Gain}(\alpha)$ versus $\alpha$ (often in percent) +gives the gain curve. The baseline (random) curve is the diagonal +$\mathrm{Gain}(\alpha)=\alpha$, while an ideal model has a steep climb +toward 1. + +A related measure is the {\em lift}, often called the gain ratio. It is the ratio of the model’s capture rate to that of random selection. Equivalently, +!bt +\[ +\mathrm{Lift}(\alpha) \;=\; \frac{\mathrm{Gain}(\alpha)}{\alpha}. +\] +!et + +A lift $>1$ indicates better-than-random targeting. In practice, gain +and lift charts (used e.g.\ in marketing or imbalanced classification) +show how many positives can be “gained” by focusing on a fraction of +the population . + +=== Other measures: Precision, Recall, and the F$_1$ Measure === + +Precision and recall (sensitivity) quantify binary classification +accuracy in terms of positive predictions. They are defined from the +confusion matrix as: +!bt +\[ +\text{Precision} = \frac{TP}{TP + FP}, \qquad \text{Recall} = \frac{TP}{TP + FN}. +\] +!et + +Precision is the fraction of predicted positives that are correct, and +recall is the fraction of actual positives that are correctly +identified . A high-precision classifier makes few false-positive +errors, while a high-recall classifier makes few false-negative +errors. + +The F$_1$ score (balanced F-measure) combines precision and recall into a single metric via their harmonic mean. The usual formula is: +!bt +\[ +F_1 =2\frac{\text{Precision}\times\text{Recall}}{\text{Precision} + \text{Recall}}. +\] +!et +This can be shown to equal +!bt +\[ +\frac{2\,TP}{2\,TP + FP + FN}. +\] +!et + +The F$_1$ score ranges from 0 (worst) to 1 (best), and balances the +trade-off between precision and recall. + +For multi-class classification, one computes per-class +precision/recall/F$_1$ (treating each class as “positive” in a +one-vs-rest manner) and then averages. Common averaging methods are: + +Micro-averaging: Sum all true positives, false positives, and false negatives across classes, then compute precision/recall/F$_1$ from these totals. +Macro-averaging: Compute the F$1$ score $F{1,i}$ for each class $i$ separately, then take the unweighted mean: $F_{1,\mathrm{macro}} = \frac{1}{K}\sum_{i=1}^K F_{1,i}$ . This treats all classes equally regardless of size. +Weighted-averaging: Like macro-average, but weight each class’s $F_{1,i}$ by its support $n_i$ (true count): $F_{1,\mathrm{weighted}} = \frac{1}{N}\sum_{i=1}^K n_i F_{1,i}$, where $N=\sum_i n_i$. This accounts for class imbalance by giving more weight to larger classes . -!split -===== Setting up the Neural Network ===== +Each of these averages has different use-cases. Micro-average is +dominated by common classes, macro-average highlights performance on +rare classes, and weighted-average is a compromise. These formulas +and concepts allow rigorous evaluation of classifier performance in +both binary and multi-class settings. -We define first our design matrix and the various output vectors for the different gates. +===== Exercises ===== -!bc pycod -""" -Simple code that tests XOR, OR and AND gates with linear regression -""" -# import necessary packages -import numpy as np +Here is a simple code example which uses the Logistic regression machinery from _scikit-learn_. +At the end it sets up the confusion matrix and the ROC and cumulative gain curves. +Feel free to use these functionalities (we don't expect you to write your own code for say the confusion matrix). +!bc pycod import matplotlib.pyplot as plt -from sklearn import datasets - -def sigmoid(x): - return 1/(1 + np.exp(-x)) - -def feed_forward(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - probabilities = sigmoid(z_o) - return probabilities - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# Design matrix -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) - -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -# The AND gate -yAND = np.array( [ 0, 0 ,0, 1]) - -# Defining the neural network -n_inputs, n_features = X.shape -n_hidden_neurons = 2 -n_categories = 1 -n_features = 2 - -# we make the weights normally distributed using numpy.random.randn - -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 - -probabilities = feed_forward(X) -print(probabilities) - -!ec - -Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above. - -!split -===== The Code using Scikit-Learn ===== - -!bc pycod -# import necessary packages import numpy as np -import matplotlib.pyplot as plt -from sklearn.neural_network import MLPClassifier -from sklearn.metrics import accuracy_score -import seaborn as sns +from sklearn.model_selection import train_test_split +# from sklearn.datasets import fill in the data set +from sklearn.linear_model import LogisticRegression -# ensure the same random numbers appear every time -np.random.seed(0) +# Load the data, fill inn +mydata.data = ? -# Design matrix -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) +X_train, X_test, y_train, y_test = train_test_split(mydata.data,cancer.target,random_state=0) +print(X_train.shape) +print(X_test.shape) +# Logistic Regression +# define which type of problem, binary or multiclass +logreg = LogisticRegression(solver='lbfgs') +logreg.fit(X_train, y_train) -# The XOR gate -yXOR = np.array( [ 0, 1 ,1, 0]) -# The OR gate -yOR = np.array( [ 0, 1 ,1, 1]) -# The AND gate -yAND = np.array( [ 0, 0 ,0, 1]) +from sklearn.preprocessing import LabelEncoder +from sklearn.model_selection import cross_validate +#Cross validation +accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score'] +print(accuracy) +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) -# Defining the neural network -n_hidden_neurons = 2 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -# store models for later use -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) -epochs = 100 - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', - alpha=lmbd, learning_rate_init=eta, max_iter=epochs) - dnn.fit(X, yXOR) - DNN_scikit[i][j] = dnn - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on data set: ", dnn.score(X, yXOR)) - print() - -sns.set() -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - dnn = DNN_scikit[i][j] - test_pred = dnn.predict(X) - test_accuracy[i][j] = accuracy_score(yXOR, test_pred) - -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$") +import scikitplot as skplt +y_pred = logreg.predict(X_test) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +plt.show() +y_probas = logreg.predict_proba(X_test) +skplt.metrics.plot_roc(y_test, y_probas) +plt.show() +skplt.metrics.plot_cumulative_gain(y_test, y_probas) plt.show() !ec -!split -===== Building a neural network code ===== - -Here we present a flexible object oriented codebase -for a feed forward neural network, along with a demonstration of how -to use it. Before we get into the details of the neural network, we -will first present some implementations of various schedulers, cost -functions and activation functions that can be used together with the -neural network. - -The codes here were developed by Eric Reber and Gregor Kajda during spring 2023. - -=== Learning rate methods === - -The code below shows object oriented implementations of the Constant, -Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All -of the classes belong to the shared abstract Scheduler class, and -share the update_change() and reset() methods allowing for any of the -schedulers to be seamlessly used during the training stage, as will -later be shown in the fit() method of the neural -network. Update_change() only has one parameter, the gradient -($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted -from the weights. The reset() function takes no parameters, and resets -the desired variables. For Constant and Momentum, reset does nothing. - - -!bc pycod -import autograd.numpy as np - -class Scheduler: - """ - Abstract class for Schedulers - """ - - def __init__(self, eta): - self.eta = eta - - # should be overwritten - def update_change(self, gradient): - raise NotImplementedError - - # overwritten if needed - def reset(self): - pass - - -class Constant(Scheduler): - def __init__(self, eta): - super().__init__(eta) - - def update_change(self, gradient): - return self.eta * gradient - - def reset(self): - pass - - -class Momentum(Scheduler): - def __init__(self, eta: float, momentum: float): - super().__init__(eta) - self.momentum = momentum - self.change = 0 - - def update_change(self, gradient): - self.change = self.momentum * self.change + self.eta * gradient - return self.change - - def reset(self): - pass - - -class Adagrad(Scheduler): - def __init__(self, eta): - super().__init__(eta) - self.G_t = None - - def update_change(self, gradient): - delta = 1e-8 # avoid division ny zero - - if self.G_t is None: - self.G_t = np.zeros((gradient.shape[0], gradient.shape[0])) - - self.G_t += gradient @ gradient.T - - G_t_inverse = 1 / ( - delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1))) - ) - return self.eta * gradient * G_t_inverse - - def reset(self): - self.G_t = None - - -class AdagradMomentum(Scheduler): - def __init__(self, eta, momentum): - super().__init__(eta) - self.G_t = None - self.momentum = momentum - self.change = 0 - - def update_change(self, gradient): - delta = 1e-8 # avoid division ny zero - - if self.G_t is None: - self.G_t = np.zeros((gradient.shape[0], gradient.shape[0])) - - self.G_t += gradient @ gradient.T - - G_t_inverse = 1 / ( - delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1))) - ) - self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse - return self.change - - def reset(self): - self.G_t = None - - -class RMS_prop(Scheduler): - def __init__(self, eta, rho): - super().__init__(eta) - self.rho = rho - self.second = 0.0 - - def update_change(self, gradient): - delta = 1e-8 # avoid division ny zero - self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient - return self.eta * gradient / (np.sqrt(self.second + delta)) - - def reset(self): - self.second = 0.0 - - -class Adam(Scheduler): - def __init__(self, eta, rho, rho2): - super().__init__(eta) - self.rho = rho - self.rho2 = rho2 - self.moment = 0 - self.second = 0 - self.n_epochs = 1 - - def update_change(self, gradient): - delta = 1e-8 # avoid division ny zero - - self.moment = self.rho * self.moment + (1 - self.rho) * gradient - self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient - - moment_corrected = self.moment / (1 - self.rho**self.n_epochs) - second_corrected = self.second / (1 - self.rho2**self.n_epochs) - - return self.eta * moment_corrected / (np.sqrt(second_corrected + delta)) - - def reset(self): - self.n_epochs += 1 - self.moment = 0 - self.second = 0 - -!ec - -=== Usage of the above learning rate schedulers === - -To initalize a scheduler, simply create the object and pass in the -necessary parameters such as the learning rate and the momentum as -shown below. As the Scheduler class is an abstract class it should not -called directly, and will raise an error upon usage. - -!bc pycod -momentum_scheduler = Momentum(eta=1e-3, momentum=0.9) -adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) -!ec - -Here is a small example for how a segment of code using schedulers -could look. Switching out the schedulers is simple. - -!bc pycod -weights = np.ones((3,3)) -print(f"Before scheduler:\n{weights=}") - -epochs = 10 -for e in range(epochs): - gradient = np.random.rand(3, 3) - change = adam_scheduler.update_change(gradient) - weights = weights - change - adam_scheduler.reset() - -print(f"\nAfter scheduler:\n{weights=}") -!ec - - -=== Cost functions === - -Here we discuss cost functions that can be used when creating the -neural network. Every cost function takes the target vector as its -parameter, and returns a function valued only at $x$ such that it may -easily be differentiated. - - -!bc pycod -import autograd.numpy as np - -def CostOLS(target): - - def func(X): - return (1.0 / target.shape[0]) * np.sum((target - X) ** 2) - - return func - - -def CostLogReg(target): - - def func(X): - - return -(1.0 / target.shape[0]) * np.sum( - (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10)) - ) - - return func - - -def CostCrossEntropy(target): - - def func(X): - return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10)) - - return func -!ec - - -Below we give a short example of how these cost function may be used -to obtain results if you wish to test them out on your own using -AutoGrad's automatics differentiation. - -!bc pycod -from autograd import grad - -target = np.array([[1, 2, 3]]).T -a = np.array([[4, 5, 6]]).T - -cost_func = CostCrossEntropy -cost_func_derivative = grad(cost_func(target)) - -valued_at_a = cost_func_derivative(a) -print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}") -!ec - - -=== Activation functions === - -Finally, before we look at the neural network, we will look at the -activation functions which can be specified between the hidden layers -and as the output function. Each function can be valued for any given -vector or matrix X, and can be differentiated via derivate(). - -!bc pycod -import autograd.numpy as np -from autograd import elementwise_grad - -def identity(X): - return X - - -def sigmoid(X): - try: - return 1.0 / (1 + np.exp(-X)) - except FloatingPointError: - return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape)) - - -def softmax(X): - X = X - np.max(X, axis=-1, keepdims=True) - delta = 10e-10 - return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta) - - -def RELU(X): - return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape)) - - -def LRELU(X): - delta = 10e-4 - return np.where(X > np.zeros(X.shape), X, delta * X) - - -def derivate(func): - if func.__name__ == "RELU": - - def func(X): - return np.where(X > 0, 1, 0) - - return func - - elif func.__name__ == "LRELU": - - def func(X): - delta = 10e-4 - return np.where(X > 0, 1, delta) - - return func - - else: - return elementwise_grad(func) -!ec - -Below follows a short demonstration of how to use an activation -function. The derivative of the activation function will be important -when calculating the output delta term during backpropagation. Note -that derivate() can also be used for cost functions for a more -generalized approach. - -!bc pycod -z = np.array([[4, 5, 6]]).T -print(f"Input to activation function:\n{z}") - -act_func = sigmoid -a = act_func(z) -print(f"\nOutput from {act_func.__name__} activation function:\n{a}") - -act_func_derivative = derivate(act_func) -valued_at_z = act_func_derivative(a) -print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}") -!ec - -=== The Neural Network === - -Now that we have gotten a good understanding of the implementation of -some important components, we can take a look at an object oriented -implementation of a feed forward neural network. The feed forward -neural network has been implemented as a class named FFNN, which can -be initiated as a regressor or classifier dependant on the choice of -cost function. The FFNN can have any number of input nodes, hidden -layers with any amount of hidden nodes, and any amount of output nodes -meaning it can perform multiclass classification as well as binary -classification and regression problems. Although there is a lot of -code present, it makes for an easy to use and generalizeable interface -for creating many types of neural networks as will be demonstrated -below. - -!bc pycod -import math -import autograd.numpy as np -import sys -import warnings -from autograd import grad, elementwise_grad -from random import random, seed -from copy import deepcopy, copy -from typing import Tuple, Callable -from sklearn.utils import resample - -warnings.simplefilter("error") - - -class FFNN: - """ - Description: - ------------ - Feed Forward Neural Network with interface enabling flexible design of a - nerual networks architecture and the specification of activation function - in the hidden layers and output layer respectively. This model can be used - for both regression and classification problems, depending on the output function. - - Attributes: - ------------ - I dimensions (tuple[int]): A list of positive integers, which specifies the - number of nodes in each of the networks layers. The first integer in the array - defines the number of nodes in the input layer, the second integer defines number - of nodes in the first hidden layer and so on until the last number, which - specifies the number of nodes in the output layer. - II hidden_func (Callable): The activation function for the hidden layers - III output_func (Callable): The activation function for the output layer - IV cost_func (Callable): Our cost function - V seed (int): Sets random seed, makes results reproducible - """ - - def __init__( - self, - dimensions: tuple[int], - hidden_func: Callable = sigmoid, - output_func: Callable = lambda x: x, - cost_func: Callable = CostOLS, - seed: int = None, - ): - self.dimensions = dimensions - self.hidden_func = hidden_func - self.output_func = output_func - self.cost_func = cost_func - self.seed = seed - self.weights = list() - self.schedulers_weight = list() - self.schedulers_bias = list() - self.a_matrices = list() - self.z_matrices = list() - self.classification = None - - self.reset_weights() - self._set_classification() - - def fit( - self, - X: np.ndarray, - t: np.ndarray, - scheduler: Scheduler, - batches: int = 1, - epochs: int = 100, - lam: float = 0, - X_val: np.ndarray = None, - t_val: np.ndarray = None, - ): - """ - Description: - ------------ - This function performs the training the neural network by performing the feedforward and backpropagation - algorithm to update the networks weights. - - Parameters: - ------------ - I X (np.ndarray) : training data - II t (np.ndarray) : target data - III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent) - IV scheduler_args (list[int]) : list of all arguments necessary for scheduler - - Optional Parameters: - ------------ - V batches (int) : number of batches the datasets are split into, default equal to 1 - VI epochs (int) : number of iterations used to train the network, default equal to 100 - VII lam (float) : regularization hyperparameter lambda - VIII X_val (np.ndarray) : validation set - IX t_val (np.ndarray) : validation target set - - Returns: - ------------ - I scores (dict) : A dictionary containing the performance metrics of the model. - The number of the metrics depends on the parameters passed to the fit-function. - - """ - - # setup - if self.seed is not None: - np.random.seed(self.seed) - - val_set = False - if X_val is not None and t_val is not None: - val_set = True - - # creating arrays for score metrics - train_errors = np.empty(epochs) - train_errors.fill(np.nan) - val_errors = np.empty(epochs) - val_errors.fill(np.nan) - - train_accs = np.empty(epochs) - train_accs.fill(np.nan) - val_accs = np.empty(epochs) - val_accs.fill(np.nan) - - self.schedulers_weight = list() - self.schedulers_bias = list() - - batch_size = X.shape[0] // batches - - X, t = resample(X, t) - - # this function returns a function valued only at X - cost_function_train = self.cost_func(t) - if val_set: - cost_function_val = self.cost_func(t_val) - - # create schedulers for each weight matrix - for i in range(len(self.weights)): - self.schedulers_weight.append(copy(scheduler)) - self.schedulers_bias.append(copy(scheduler)) - - print(f"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}") - - try: - for e in range(epochs): - for i in range(batches): - # allows for minibatch gradient descent - if i == batches - 1: - # If the for loop has reached the last batch, take all thats left - X_batch = X[i * batch_size :, :] - t_batch = t[i * batch_size :, :] - else: - X_batch = X[i * batch_size : (i + 1) * batch_size, :] - t_batch = t[i * batch_size : (i + 1) * batch_size, :] - - self._feedforward(X_batch) - self._backpropagate(X_batch, t_batch, lam) - - # reset schedulers for each epoch (some schedulers pass in this call) - for scheduler in self.schedulers_weight: - scheduler.reset() - - for scheduler in self.schedulers_bias: - scheduler.reset() - - # computing performance metrics - pred_train = self.predict(X) - train_error = cost_function_train(pred_train) - - train_errors[e] = train_error - if val_set: - - pred_val = self.predict(X_val) - val_error = cost_function_val(pred_val) - val_errors[e] = val_error - - if self.classification: - train_acc = self._accuracy(self.predict(X), t) - train_accs[e] = train_acc - if val_set: - val_acc = self._accuracy(pred_val, t_val) - val_accs[e] = val_acc - - # printing progress bar - progression = e / epochs - print_length = self._progress_bar( - progression, - train_error=train_errors[e], - train_acc=train_accs[e], - val_error=val_errors[e], - val_acc=val_accs[e], - ) - except KeyboardInterrupt: - # allows for stopping training at any point and seeing the result - pass - - # visualization of training progression (similiar to tensorflow progression bar) - sys.stdout.write("\r" + " " * print_length) - sys.stdout.flush() - self._progress_bar( - 1, - train_error=train_errors[e], - train_acc=train_accs[e], - val_error=val_errors[e], - val_acc=val_accs[e], - ) - sys.stdout.write("") - - # return performance metrics for the entire run - scores = dict() - - scores["train_errors"] = train_errors - - if val_set: - scores["val_errors"] = val_errors - - if self.classification: - scores["train_accs"] = train_accs - - if val_set: - scores["val_accs"] = val_accs - - return scores - - def predict(self, X: np.ndarray, *, threshold=0.5): - """ - Description: - ------------ - Performs prediction after training of the network has been finished. - - Parameters: - ------------ - I X (np.ndarray): The design matrix, with n rows of p features each - - Optional Parameters: - ------------ - II threshold (float) : sets minimal value for a prediction to be predicted as the positive class - in classification problems - - Returns: - ------------ - I z (np.ndarray): A prediction vector (row) for each row in our design matrix - This vector is thresholded if regression=False, meaning that classification results - in a vector of 1s and 0s, while regressions in an array of decimal numbers - - """ - - predict = self._feedforward(X) - - if self.classification: - return np.where(predict > threshold, 1, 0) - else: - return predict - - def reset_weights(self): - """ - Description: - ------------ - Resets/Reinitializes the weights in order to train the network for a new problem. - - """ - if self.seed is not None: - np.random.seed(self.seed) - - self.weights = list() - for i in range(len(self.dimensions) - 1): - weight_array = np.random.randn( - self.dimensions[i] + 1, self.dimensions[i + 1] - ) - weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01 - - self.weights.append(weight_array) - - def _feedforward(self, X: np.ndarray): - """ - Description: - ------------ - Calculates the activation of each layer starting at the input and ending at the output. - Each following activation is calculated from a weighted sum of each of the preceeding - activations (except in the case of the input layer). - - Parameters: - ------------ - I X (np.ndarray): The design matrix, with n rows of p features each - - Returns: - ------------ - I z (np.ndarray): A prediction vector (row) for each row in our design matrix - """ - - # reset matrices - self.a_matrices = list() - self.z_matrices = list() - - # if X is just a vector, make it into a matrix - if len(X.shape) == 1: - X = X.reshape((1, X.shape[0])) - - # Add a coloumn of zeros as the first coloumn of the design matrix, in order - # to add bias to our data - bias = np.ones((X.shape[0], 1)) * 0.01 - X = np.hstack([bias, X]) - - # a^0, the nodes in the input layer (one a^0 for each row in X - where the - # exponent indicates layer number). - a = X - self.a_matrices.append(a) - self.z_matrices.append(a) - - # The feed forward algorithm - for i in range(len(self.weights)): - if i < len(self.weights) - 1: - z = a @ self.weights[i] - self.z_matrices.append(z) - a = self.hidden_func(z) - # bias column again added to the data here - bias = np.ones((a.shape[0], 1)) * 0.01 - a = np.hstack([bias, a]) - self.a_matrices.append(a) - else: - try: - # a^L, the nodes in our output layers - z = a @ self.weights[i] - a = self.output_func(z) - self.a_matrices.append(a) - self.z_matrices.append(z) - except Exception as OverflowError: - print( - "OverflowError in fit() in FFNN\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling" - ) - - # this will be a^L - return a - - def _backpropagate(self, X, t, lam): - """ - Description: - ------------ - Performs the backpropagation algorithm. In other words, this method - calculates the gradient of all the layers starting at the - output layer, and moving from right to left accumulates the gradient until - the input layer is reached. Each layers respective weights are updated while - the algorithm propagates backwards from the output layer (auto-differentation in reverse mode). - - Parameters: - ------------ - I X (np.ndarray): The design matrix, with n rows of p features each. - II t (np.ndarray): The target vector, with n rows of p targets. - III lam (float32): regularization parameter used to punish the weights in case of overfitting - - Returns: - ------------ - No return value. - - """ - out_derivative = derivate(self.output_func) - hidden_derivative = derivate(self.hidden_func) - - for i in range(len(self.weights) - 1, -1, -1): - # delta terms for output - if i == len(self.weights) - 1: - # for multi-class classification - if ( - self.output_func.__name__ == "softmax" - ): - delta_matrix = self.a_matrices[i + 1] - t - # for single class classification - else: - cost_func_derivative = grad(self.cost_func(t)) - delta_matrix = out_derivative( - self.z_matrices[i + 1] - ) * cost_func_derivative(self.a_matrices[i + 1]) - - # delta terms for hidden layer - else: - delta_matrix = ( - self.weights[i + 1][1:, :] @ delta_matrix.T - ).T * hidden_derivative(self.z_matrices[i + 1]) - - # calculate gradient - gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix - gradient_bias = np.sum(delta_matrix, axis=0).reshape( - 1, delta_matrix.shape[1] - ) - - # regularization term - gradient_weights += self.weights[i][1:, :] * lam - - # use scheduler - update_matrix = np.vstack( - [ - self.schedulers_bias[i].update_change(gradient_bias), - self.schedulers_weight[i].update_change(gradient_weights), - ] - ) - - # update weights and bias - self.weights[i] -= update_matrix - - def _accuracy(self, prediction: np.ndarray, target: np.ndarray): - """ - Description: - ------------ - Calculates accuracy of given prediction to target - - Parameters: - ------------ - I prediction (np.ndarray): vector of predicitons output network - (1s and 0s in case of classification, and real numbers in case of regression) - II target (np.ndarray): vector of true values (What the network ideally should predict) - - Returns: - ------------ - A floating point number representing the percentage of correctly classified instances. - """ - assert prediction.size == target.size - return np.average((target == prediction)) - def _set_classification(self): - """ - Description: - ------------ - Decides if FFNN acts as classifier (True) og regressor (False), - sets self.classification during init() - """ - self.classification = False - if ( - self.cost_func.__name__ == "CostLogReg" - or self.cost_func.__name__ == "CostCrossEntropy" - ): - self.classification = True - - def _progress_bar(self, progression, **kwargs): - """ - Description: - ------------ - Displays progress of training - """ - print_length = 40 - num_equals = int(progression * print_length) - num_not = print_length - num_equals - arrow = ">" if num_equals > 0 else "" - bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]" - perc_print = self._format(progression * 100, decimals=5) - line = f" {bar} {perc_print}% " - - for key in kwargs: - if not np.isnan(kwargs[key]): - value = self._format(kwargs[key], decimals=4) - line += f"| {key}: {value} " - sys.stdout.write("\r" + line) - sys.stdout.flush() - return len(line) - - def _format(self, value, decimals=4): - """ - Description: - ------------ - Formats decimal numbers for progress bar - """ - if value > 0: - v = value - elif value < 0: - v = -10 * value - else: - v = 1 - n = 1 + math.floor(math.log10(v)) - if n >= decimals - 1: - return str(round(value)) - return f"{value:.{decimals-n-1}f}" -!ec - -Before we make a model, we will quickly generate a dataset we can use -for our linear regression problem as shown below - -!bc pycod -import autograd.numpy as np -from sklearn.model_selection import train_test_split - -def SkrankeFunction(x, y): - return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2) - -def create_X(x, y, n): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n + 1) * (n + 2) / 2) # Number of elements in beta - X = np.ones((N, l)) - - for i in range(1, n + 1): - q = int((i) * (i + 1) / 2) - for k in range(i + 1): - X[:, q + k] = (x ** (i - k)) * (y**k) - - return X - -step=0.5 -x = np.arange(0, 1, step) -y = np.arange(0, 1, step) -x, y = np.meshgrid(x, y) -target = SkrankeFunction(x, y) -target = target.reshape(target.shape[0], 1) - -poly_degree=3 -X = create_X(x, y, poly_degree) - -X_train, X_test, t_train, t_test = train_test_split(X, target) - -!ec - -Now that we have our dataset ready for the regression, we can create -our regressor. Note that with the seed parameter, we can make sure our -results stay the same every time we run the neural network. For -inititialization, we simply specify the dimensions (we wish the amount -of input nodes to be equal to the datapoints, and the output to -predict one value). - - -!bc pycod -input_nodes = X_train.shape[1] -output_nodes = 1 - -linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023) - -!ec - -We then fit our model with our training data using the scheduler of our choice. - -!bc pycod -linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights - -scheduler = Constant(eta=1e-3) -scores = linear_regression.fit(X_train, t_train, scheduler) - - -!ec - -Due to the progress bar we can see the MSE (train_error) throughout -the FFNN's training. Note that the fit() function has some optional -parameters with defualt arguments. For example, the regularization -hyperparameter can be left ignored if not needed, and equally the FFNN -will by default run for 100 epochs. These can easily be changed, such -as for example: - -!bc pycod -linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights - -scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000) - -!ec - -We see that given more epochs to train on, the regressor reaches a lower MSE. - -Let us then switch to a binary classification. We use a binary -classification dataset, and follow a similar setup to the regression -case. - - - -!bc pycod -from sklearn.datasets import load_breast_cancer -from sklearn.preprocessing import MinMaxScaler - -wisconsin = load_breast_cancer() -X = wisconsin.data -target = wisconsin.target -target = target.reshape(target.shape[0], 1) - -X_train, X_val, t_train, t_val = train_test_split(X, target) - -scaler = MinMaxScaler() -scaler.fit(X_train) -X_train = scaler.transform(X_train) -X_val = scaler.transform(X_val) - - -!ec - -!bc pycod -input_nodes = X_train.shape[1] -output_nodes = 1 - -logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023) - -!ec - -We will now make use of our validation data by passing it into our fit function as a keyword argument - -!bc pycod -logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights - -scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) -scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val) - - -!ec - -Finally, we will create a neural network with 2 hidden layers with activation functions. -!bc pycod -input_nodes = X_train.shape[1] -hidden_nodes1 = 100 -hidden_nodes2 = 30 -output_nodes = 1 - -dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes) - -neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023) - - -!ec - -!bc pycod -neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights - -scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999) -scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val) - -!ec - -=== Multiclass classification === - -Finally, we will demonstrate the use case of multiclass classification -using our FFNN with the famous MNIST dataset, which contain images of -digits between the range of 0 to 9. - +=== Exercise a) === +Convince yourself about the mathematics for the confusion matrix, the ROC and the cumlative gain curves for both a binary and a multiclass classification problem. +=== Exercise b) === +Use a binary classification data available from _scikit-learn_. As an example you can use +the MNIST data set and just specialize to two numbers. To do so you can use the following code lines !bc pycod from sklearn.datasets import load_digits - -def onehot(target: np.ndarray): - onehot = np.zeros((target.size, target.max() + 1)) - onehot[np.arange(target.size), target] = 1 - return onehot - -digits = load_digits() - -X = digits.data -target = digits.target -target = onehot(target) - -input_nodes = 64 -hidden_nodes1 = 100 -hidden_nodes2 = 30 -output_nodes = 10 - -dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes) - -multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy) - -multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights - -scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999) -scores = multiclass.fit(X, target, scheduler, epochs=1000) - +digits = load_digits(n_class=2) # Load only two classes, e.g., 0 and 1 +X, y = digits.data, digits.target !ec - - -!split -===== Testing the XOR gate and other gates ===== - -Let us now use our code to test the XOR gate. - +Alternatively, you can use the _make$\_$classification_ +functionality. This function generates a random $n$-class classification +dataset, which can be configured for binary classification by setting +n_classes=2. You can also control the number of samples, features, +informative features, redundant features, and more. !bc pycod -X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64) - -# The XOR gate -yXOR = np.array( [[ 0], [1] ,[1], [0]]) - -input_nodes = X.shape[1] -output_nodes = 1 - -logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023) -logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights -scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999) -scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000) +from sklearn.datasets import make_classification +X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, n_redundant=5, n_classes=2, random_state=42) !ec -Not bad, but the results depend strongly on the learning reate. Try different learning rates. +You can use this option for the multiclass case as well, see the next exercise. +If you prefer to study other binary classification datasets, feel free +to replace the above suggestions with your own dataset. + +Make plots of the confusion matrix, the ROC curve and the cumulative gain curve. + +=== Exercise c) week 43 === + +As a multiclass problem, we will use the Iris data set discussed in +the exercises from weeks 41 and 42. This is a three-class data set and +you can set it up using _scikit-learn_, +!bc pycod +from sklearn.datasets import load_iris +iris = load_iris() +X = iris.data # Features +y = iris.target # Target labels +!ec + +Make plots of the confusion matrix, the ROC curve and the cumulative +gain curve for this (or other) multiclass data set. diff --git a/doc/src/week43/week43.do.txt b/doc/src/week43/week43.do.txt index 4fb97b4f8..c7701fa35 100644 --- a/doc/src/week43/week43.do.txt +++ b/doc/src/week43/week43.do.txt @@ -6,11 +6,12 @@ DATE: October 20, 2025 ===== Plans for week 43 ===== !bblock Material for the lecture on Monday October 20, 2025 - * Building our own Feed-forward Neural Network with intro to Tensorflow - * Solving differential equations with Neural Networks -# * Video of lecture at URL:"https://youtu.be/vkBNTn-MLqs" -# * Video os second part, solving differential equations with neural networks at URL:"https://youtu.be/2N8To65I2wQ" -# * Whiteboard notes on solving differential equations at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesOct21.pdf" +o Reminder from last week, see also lecture notes from week 42 at URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html" as well as those from week 41, see see URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html". +o Building our own Feed-forward Neural Network. +o Coding examples using Tensorflow/Keras and Pytorch examples. The Pytorch examples are adapted from Rashcka's text, see chapters 11-13.. +o Start discussions on how to use neural networks for solving differential equations (ordinary and partial ones). This topic continues next week as well. +o Video of lecture at URL:"https://youtu.be/Gi6mzxAT0Ew" +o Whiteboard notes at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2025/FYSSTKweek43.pdf" !eblock @@ -18,42 +19,18 @@ DATE: October 20, 2025 !split ===== Exercises and lab session week 43 ===== !bblock Lab sessions on Tuesday and Wednesday - * Exercise on writing your own neural network code - * The exercises this week will be continued next week as well - * Discussion of project 2 +o Work on writing your own neural network code and discussions of project 2. If you didn't get time to do the exercises from the two last weeks, we recommend doing so as these exercises give you the basic elements of a neural network code. +o The exercises this week are tailored to the optional part of project 2, and deal with studying ways to display results from classification problems !eblock -!split -===== Mathematics of deep learning ===== - -!bblock Two recent books online -o The Modern Mathematics of Deep Learning, by Julius Berner, Philipp Grohs, Gitta Kutyniok, Philipp Petersen at URL:"https://arxiv.org/abs/2105.04026", published as "Mathematical Aspects of Deep Learning, pp. 1-111. Cambridge University Press, 2022":"https://doi.org/10.1017/9781009025096.002" - -o Mathematical Introduction to Deep Learning: Methods, Implementations, and Theory, Arnulf Jentzen, Benno Kuckuck, Philippe von Wurstemberger at URL:"https://doi.org/10.48550/arXiv.2310.20360" -!eblock - - -!split -===== Reminder on books with hands-on material and codes ===== -!bblock -* Sebastian Rashcka et al, Machine learning with Scikit-Learn and PyTorch at URL:"https://sebastianraschka.com/blog/2022/ml-pytorch-book.html" -!eblock - - -!split -===== Reading recommendations ===== - -o Rashkca et al., chapter 11, jupyter-notebook sent separately, from GitHub site at URL:"https://github.com/rasbt/machine-learning-book". See also chapters 12 and 13 on using Pytorch to make a Neural network code. -o Goodfellow et al, chapter 6 and 7 contain most of the neural network background. - !split ===== Using Automatic differentiation ===== In our discussions of ordinary differential equations and neural network codes -we will also study the usage of Autograd, see for example URL:"https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from "week 39":"https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html" and the Autograd documentation at URL:"https://github.com/HIPS/autograd". +we will also study the usage of Autograd, see for example URL:"https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" in computing gradients for deep learning. For the documentation of Autograd and examples see the Autograd documentation at URL:"https://github.com/HIPS/autograd" and the lecture slides from week 41, see URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html". !split @@ -67,12 +44,12 @@ o Slides 12-44 at URL:"http://cs231n.stanford.edu/slides/2017/cs231n_2017_lectur !split -===== Lecture Monday October 21 ===== +===== Lecture Monday October 20 ===== !split ===== Setting up the back propagation algorithm and algorithm for a feed forward NN, initalizations ===== -This is a reminder from where we ended last week. +This is a reminder from last week. !bblock The architecture (our model) o Set up your inputs and outputs (scalars, vectors, matrices or higher-order arrays) @@ -260,996 +237,6 @@ _For the output layer:_ -!split -===== Setting up a Multi-layer perceptron model for classification ===== - -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 -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. - -In binary classification with two classes $(0, 1)$ we define the -logistic/sigmoid function as the probability that a particular input -is in class $0$ or $1$. This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. - -For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$ -is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$ -represents our activation values $z$. We have -!bt -\[ -P(y = 0 \mid \bm{x}, \bm{\theta}) = \frac{1}{1 + \exp{(- \bm{x}})} , -\] -!et -and -!bt -\[ -P(y = 1 \mid \bm{x}, \bm{\theta}) = 1 - P(y = 0 \mid \bm{x}, \bm{\theta}) , -\] -!et - -where $y \in \{0, 1\}$ and $\bm{\theta}$ represents the weights and biases -of our network. - - -!split -===== Defining the cost function ===== - -Our cost function is given as (see the Logistic regression lectures) -!bt -\[ -\mathcal{C}(\bm{\theta}) = - \ln P(\mathcal{D} \mid \bm{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\bm{\theta}) . -\] -!et - -This last equality means that we can interpret our *cost* function as a sum over the *loss* function -for each point in the dataset $\mathcal{L}_i(\bm{\theta})$. -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. - -In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: - -$y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and - - -$y = 1 \quad \rightarrow \quad \bm{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 $\bm{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th -output vector $\bm{y}_i$. -The probability of $\bm{x}_i$ being in class $c$ will be given by the softmax function: - -!bt -\[ -P(y_{ic} = 1 \mid \bm{x}_i, \bm{\theta}) = \frac{\exp{((\bm{a}_i^{hidden})^T \bm{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\bm{a}_i^{hidden})^T \bm{w}_{c'})}} , -\] -!et - -which reduces to the logistic function in the binary case. -The likelihood of this $C$-class classifier -is now given as: - -!bt -\[ -P(\mathcal{D} \mid \bm{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -\] -!et -Again we take the negative log-likelihood to define our cost function: - -!bt -\[ -\mathcal{C}(\bm{\theta}) = - \log{P(\mathcal{D} \mid \bm{\theta})}. -\] -!et -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! - -!split -===== 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 -!bt -\[ -\mathcal{C}(\bm{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\bm{\beta})}+(1-y_i)\log{1-p(y_i \vert x_i,\bm{\beta})}\right), -\] -!et -where we had defined the logistic (sigmoid) function -!bt -\[ -p(y_i =1\vert x_i,\bm{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, -\] -!et -and -!bt -\[ -p(y_i =0\vert x_i,\bm{\beta})=1-p(y_i =1\vert x_i,\bm{\beta}). -\] -!et -The parameters $\bm{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. - -Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. -We have then -!bt -\[ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -\] -!et -with -!bt -\[ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -\] -!et -where the superscript $l-1$ indicates that these are the outputs from layer $l-1$. -Our cost function at the final layer $l=L$ is now -!bt -\[ -\mathcal{C}(\bm{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(1-t_i)\log{(1-a_i^L)}\right), -\] -!et -where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get -!bt -\[ -\frac{\partial \mathcal{C}(\bm{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. -\] -!et -In case we use another activation function than the logistic one, we need to evaluate other derivatives. - - -!split -===== 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 -!bt -\[ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -\] -!et -For the Softmax function we have -!bt -\[ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -\] -!et -Its derivative with respect to $z_j^l$ gives -!bt -\[ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), -\] -!et -which in case of the simply binary model reduces to having $i=j$. - -!split -===== 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: - -o Collect and pre-process data -o Define model and architecture -o Choose cost function and optimizer -o Train the model -o Evaluate model performance on test data -o Adjust hyperparameters (if necessary, network architecture) - -!split -===== Collect and pre-process data ===== - -Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ -package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". -The *MNIST* (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size $28\times 28$ pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. - -To feed data into a feed-forward neural network we need to represent -the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each -row represents an *input*, in this case a handwritten digit, and -each column represents a *feature*, in this case a pixel. The -correct answers, also known as *labels* or *targets* are -represented as a 1D array of integers -$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. - -As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: - -$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ - -and the targets would be: - -$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ - -Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -design/feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. - - -!bc pycod -# 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 -%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 - -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# flatten the image -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 -n_inputs = len(inputs) -inputs = inputs.reshape(n_inputs, -1) -print("X = (n_inputs, n_features) = " + str(inputs.shape)) - - -# choose some random images to display -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() -!ec - -!split -===== Train and test datasets ===== - -Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. - -We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. - -It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. - - -!bc pycod -from sklearn.model_selection import train_test_split - -# 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) - -# equivalently in numpy -def train_test_split_numpy(inputs, labels, train_size, test_size): - n_inputs = len(inputs) - inputs_shuffled = inputs.copy() - labels_shuffled = labels.copy() - - np.random.shuffle(inputs_shuffled) - np.random.shuffle(labels_shuffled) - - train_end = int(n_inputs*train_size) - X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] - Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] - - return X_train, X_test, Y_train, Y_test - -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) - -print("Number of training images: " + str(len(X_train))) -print("Number of test images: " + str(len(X_test))) -!ec - -!split -===== Define model and architecture ===== - -Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have - -$$ z = \sum_{i=1}^n w_i a_i ,$$ - -$$ y = f(z) ,$$ - -where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer -and $w_i$ is the weight to input $i$. -The activation of the neurons in the input layer is just the features (e.g. a pixel value). - -The simplest activation function for a neuron is the *Heaviside* function: - -$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ - -A feed-forward neural network with this activation is known as a *perceptron*. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), -and we call these architectures *multiclass perceptrons*. - -However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. - -Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function $\sigma(x)$: - -$$ 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. - -!split -===== Layers ===== - -* Input -Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. - -* Hidden layer -We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. - -* Output -If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. - -For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. - -Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: - -$$ P(\text{class $j$} \mid \text{input $\bm{a}$}) = \frac{\exp{(\bm{a}^T \bm{w}_j)}} -{\sum_{c=0}^{9} \exp{(\bm{a}^T \bm{w}_c)}} ,$$ - -i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\bm{a}$, with $\bm{w}_j$ the weights of neuron $j$ to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ - -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. - -!split -===== Weights and biases ===== - -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. - -Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ - -The bias weights $\bm{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. -!bc pycod -# building our neural network - -n_inputs, n_features = X_train.shape -n_hidden_neurons = 50 -n_categories = 10 - -# we make the weights normally distributed using numpy.random.randn - -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 -!ec - -!split -===== Feed-forward pass ===== - -Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: - -$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ - -this is then passed through our activation function - -$$ a_{j}^{l} = f(z_{j}^{l}) .$$ - -We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: - -$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ - -Finally we calculate the output of neuron $j$ in the output layer using the softmax function: - -$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ - -!split -===== Matrix multiplications ===== - -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})$, -we can easily feed the network all our training data in one go by taking the matrix product - -$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ - -and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: - -$$ \bm{z}^{l} = \bm{X} \bm{W}^{l} + \bm{b}^{l} ,$$ - -meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: - -$$ \bm{a}^{l} = f(\bm{z}^l) .$$ - -This is fed to the output layer: - -$$ \bm{z}^{L} = \bm{a}^{L} \bm{W}^{L} + \bm{b}^{L} .$$ - -Finally we receive our output values for each image and each category by passing it through the softmax function: - -$$ output = softmax (\bm{z}^{L}) = (n_{inputs}, n_{categories}) .$$ - - -!bc pycod -# setup the feed-forward pass, subscript h = hidden layer - -def sigmoid(x): - return 1/(1 + np.exp(-x)) - -def feed_forward(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - return probabilities - -probabilities = feed_forward(X_train) -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) -print("probabilities sum up to: " + str(probabilities[0].sum())) -print() - -# we obtain a prediction by taking the class with the highest likelihood -def predict(X): - probabilities = feed_forward(X) - return np.argmax(probabilities, axis=1) - -predictions = predict(X_train) -print("predictions = (n_inputs) = " + str(predictions.shape)) -print("prediction for image 0: " + str(predictions[0])) -print("correct label for image 0: " + str(Y_train[0])) -!ec - -!split -===== Choose cost function and optimizer ===== - -To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the *loss* function, and the function -that gives the total error of our network across all samples the *cost* function. -A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. - -In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: - -$$ y = 5 \quad \rightarrow \quad \bm{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ - - -$$ y = 1 \quad \rightarrow \quad \bm{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. -We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\bm{x}_i$ in the dataset. - -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 $\bm{\theta}$ represents the parameters of our network, i.e. all the weights and biases. - - -!split -===== 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 -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 *local* minimum of the cost function. -Each parameter $\theta$ is iteratively adjusted according to the rule - -$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ - -where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. - -A simple and effective improvement is a variant called *Batch Gradient Descent*. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a *minibatch*. -If there are $N$ data points and we have a minibatch size of $M$, the total number of batches -is $N/M$. -We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: - -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ - -i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. - -This has two important benefits: -o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. -o 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". - -!split -===== Regularization ===== - -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. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces *overfitting*. - -We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: - -$$ \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \mathcal{L}_i(\theta) + \lambda \lvert \lvert \bm{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ - -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 -the hidden layer and $(50 + 1)\times 10=510$ weights to the output -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. - - -!split -===== Matrix multiplication ===== - -To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with $\bm{t}$ being our targets, - -$$ \delta_L = \bm{t} - \bm{y} = (n_{inputs}, n_{categories}) .$$ - -The gradient for the output weights is calculated as - -$$ \nabla W_{L} = \bm{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ - -where $\bm{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. - -The gradient with respect to the output bias is then - -$$ \nabla \bm{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ - -The error in the hidden layer is - -$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ - -where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes -the *Hadamard product*, meaning element-wise multiplication. - -This again gives us the gradients in the hidden layer: - -$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ - -$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ - - -!bc pycod -# to categorical turns our integer vector into a onehot representation -from sklearn.metrics import accuracy_score - -# one-hot in numpy -def to_categorical_numpy(integer_vector): - n_inputs = len(integer_vector) - n_categories = np.max(integer_vector) + 1 - onehot_vector = np.zeros((n_inputs, n_categories)) - onehot_vector[range(n_inputs), integer_vector] = 1 - - return onehot_vector - -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) - -def feed_forward_train(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - # for backpropagation need activations in hidden and output layers - return a_h, probabilities - -def backpropagation(X, Y): - a_h, probabilities = feed_forward_train(X) - - # error in the output layer - error_output = probabilities - Y - # error in the hidden layer - error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) - - # gradients for the output layer - output_weights_gradient = np.matmul(a_h.T, error_output) - output_bias_gradient = np.sum(error_output, axis=0) - - # gradient for the hidden layer - hidden_weights_gradient = np.matmul(X.T, error_hidden) - hidden_bias_gradient = np.sum(error_hidden, axis=0) - - return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient - -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) - -eta = 0.01 -lmbd = 0.01 -for i in range(1000): - # calculate gradients - dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) - - # regularization term gradients - dWo += lmbd * output_weights - dWh += lmbd * hidden_weights - - # update weights and biases - output_weights -= eta * dWo - output_bias -= eta * dBo - hidden_weights -= eta * dWh - hidden_bias -= eta * dBh - -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) -!ec - -!split -===== Improving performance ===== - -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. -In order to obtain a network that does something useful, we will have to do a bit more work. - -The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. - -Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period -going through the entire dataset ($n/M$ batches) an *epoch*. - -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/". - -!split -===== Full object-oriented implementation ===== - -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. - - -!bc pycod -class NeuralNetwork: - def __init__( - self, - X_data, - Y_data, - n_hidden_neurons=50, - n_categories=10, - epochs=10, - batch_size=100, - eta=0.1, - lmbd=0.0): - - self.X_data_full = X_data - self.Y_data_full = Y_data - - self.n_inputs = X_data.shape[0] - self.n_features = X_data.shape[1] - self.n_hidden_neurons = n_hidden_neurons - self.n_categories = n_categories - - self.epochs = epochs - self.batch_size = batch_size - self.iterations = self.n_inputs // self.batch_size - self.eta = eta - self.lmbd = lmbd - - self.create_biases_and_weights() - - def create_biases_and_weights(self): - self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) - self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 - - self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) - self.output_bias = np.zeros(self.n_categories) + 0.01 - - def feed_forward(self): - # feed-forward for training - self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias - self.a_h = sigmoid(self.z_h) - - self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(self.z_o) - self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - def feed_forward_out(self, X): - # feed-forward for output - z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias - a_h = sigmoid(z_h) - - z_o = np.matmul(a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - return probabilities - - def backpropagation(self): - error_output = self.probabilities - self.Y_data - error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) - - self.output_weights_gradient = np.matmul(self.a_h.T, error_output) - self.output_bias_gradient = np.sum(error_output, axis=0) - - self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) - self.hidden_bias_gradient = np.sum(error_hidden, axis=0) - - if self.lmbd > 0.0: - self.output_weights_gradient += self.lmbd * self.output_weights - self.hidden_weights_gradient += self.lmbd * self.hidden_weights - - self.output_weights -= self.eta * self.output_weights_gradient - self.output_bias -= self.eta * self.output_bias_gradient - self.hidden_weights -= self.eta * self.hidden_weights_gradient - self.hidden_bias -= self.eta * self.hidden_bias_gradient - - def predict(self, X): - probabilities = self.feed_forward_out(X) - return np.argmax(probabilities, axis=1) - - def predict_probabilities(self, X): - probabilities = self.feed_forward_out(X) - return probabilities - - def train(self): - data_indices = np.arange(self.n_inputs) - - for i in range(self.epochs): - for j in range(self.iterations): - # pick datapoints with replacement - chosen_datapoints = np.random.choice( - data_indices, size=self.batch_size, replace=False - ) - - # minibatch training data - self.X_data = self.X_data_full[chosen_datapoints] - self.Y_data = self.Y_data_full[chosen_datapoints] - - self.feed_forward() - self.backpropagation() -!ec - -!split -===== Evaluate model performance on test data ===== - -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. -We measure the performance of the network using the *accuracy* score. -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 $1$. - -$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\tilde{y}_i = y_i)}{n} ,$$ - -where $I$ is the indicator function, $1$ if $\tilde{y}_i = y_i$ and $0$ otherwise. - - -!bc pycod -epochs = 100 -batch_size = 100 - -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) -dnn.train() -test_predict = dnn.predict(X_test) - -# accuracy score from scikit library -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - -# equivalent in numpy -def accuracy_score_numpy(Y_test, Y_pred): - return np.sum(Y_test == Y_pred) / len(Y_test) - -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) -!ec - -!split -===== Adjust hyperparameters ===== - -We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). - -!bc pycod -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -# store the models for later use -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -# grid search -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) - dnn.train() - - DNN_numpy[i][j] = dnn - - test_predict = dnn.predict(X_test) - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - print() -!ec - -!split -===== Visualization ===== - -!bc pycod -# visual representation of grid search -# uses seaborn heatmap, you can also do this with matplotlib imshow -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)): - dnn = DNN_numpy[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -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() -!ec - -!split -===== scikit-learn implementation ===== - -_scikit-learn_ focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -*MPLRegressor*, and Multi Layer Perceptron outputting labels, -*MLPClassifier*. We will see how simple it is to use these classes. - -_scikit-learn_ implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. - -!bc pycod -from sklearn.neural_network import MLPClassifier -# store models for later use -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', - alpha=lmbd, learning_rate_init=eta, max_iter=epochs) - dnn.fit(X_train, Y_train) - - DNN_scikit[i][j] = dnn - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) - print() -!ec - - -!split -===== Visualization ===== -!bc pycod -# optional -# 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)): - dnn = DNN_scikit[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -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() -!ec - - - - - @@ -1468,186 +455,148 @@ plt.show() !ec - !split -===== The Breast Cancer Data, now with Keras ===== +===== Using Pytorch with the full MNIST data set ===== !bc pycod +import torch +import torch.nn as nn +import torch.optim as optim +import torchvision +import torchvision.transforms as transforms -import tensorflow as tf -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 -import numpy as np -import matplotlib.pyplot as plt -import seaborn as sns -from sklearn.model_selection import train_test_split as splitter -from sklearn.datasets import load_breast_cancer -import pickle -import os +# Device configuration: use GPU if available +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +# MNIST dataset (downloads if not already present) +transform = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize((0.5,), (0.5,)) # normalize to mean=0.5, std=0.5 (approx. [-1,1] pixel range) +]) +train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) +test_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) + +train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True) +test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False) -"""Load breast cancer dataset""" +class NeuralNet(nn.Module): + def __init__(self): + super(NeuralNet, self).__init__() + self.fc1 = nn.Linear(28*28, 100) # first hidden layer (784 -> 100) + self.fc2 = nn.Linear(100, 100) # second hidden layer (100 -> 100) + self.fc3 = nn.Linear(100, 10) # output layer (100 -> 10 classes) + def forward(self, x): + x = x.view(x.size(0), -1) # flatten images into vectors of size 784 + x = torch.relu(self.fc1(x)) # hidden layer 1 + ReLU activation + x = torch.relu(self.fc2(x)) # hidden layer 2 + ReLU activation + x = self.fc3(x) # output layer (logits for 10 classes) + return x -np.random.seed(0) #create same seed for random number every time - -cancer=load_breast_cancer() #Download breast cancer dataset - -inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters) -outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant) -labels=cancer.feature_names[0:30] - -print('The content of the breast cancer dataset is:') #Print information about the datasets -print(labels) -print('-------------------------') -print("inputs = " + str(inputs.shape)) -print("outputs = " + str(outputs.shape)) -print("labels = "+ str(labels.shape)) - -x=inputs #Reassign the Feature and Label matrices to other variables -y=outputs - -#%% - -# Visualisation of dataset (for correlation analysis) - -plt.figure() -plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral) -plt.xlabel('Mean radius',fontweight='bold') -plt.ylabel('Mean perimeter',fontweight='bold') -plt.show() - -plt.figure() -plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral) -plt.xlabel('Mean compactness',fontweight='bold') -plt.ylabel('Mean concavity',fontweight='bold') -plt.show() +model = NeuralNet().to(device) -plt.figure() -plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) -plt.xlabel('Mean radius',fontweight='bold') -plt.ylabel('Mean texture',fontweight='bold') -plt.show() +criterion = nn.CrossEntropyLoss() +optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4) -plt.figure() -plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral) -plt.xlabel('Mean perimeter',fontweight='bold') -plt.ylabel('Mean compactness',fontweight='bold') -plt.show() +num_epochs = 10 +for epoch in range(num_epochs): + model.train() # set model to training mode + running_loss = 0.0 + for images, labels in train_loader: + # Move data to device (GPU if available, else CPU) + images, labels = images.to(device), labels.to(device) + + optimizer.zero_grad() # reset gradients to zero + outputs = model(images) # forward pass: compute predictions + loss = criterion(outputs, labels) # compute cross-entropy loss + loss.backward() # backpropagate to compute gradients + optimizer.step() # update weights using SGD step + + running_loss += loss.item() + # Compute average loss over all batches in this epoch + avg_loss = running_loss / len(train_loader) + print(f"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}") + +#Evaluation on the Test Set -# Generate training and testing datasets -#Select features relevant to classification (texture,perimeter,compactness and symmetery) -#and add to input matrix +model.eval() # set model to evaluation mode +correct = 0 +total = 0 +with torch.no_grad(): # disable gradient calculation for evaluation + for images, labels in test_loader: + images, labels = images.to(device), labels.to(device) + outputs = model(images) + _, predicted = torch.max(outputs, dim=1) # class with highest score + total += labels.size(0) + correct += (predicted == labels).sum().item() -temp1=np.reshape(x[:,1],(len(x[:,1]),1)) -temp2=np.reshape(x[:,2],(len(x[:,2]),1)) -X=np.hstack((temp1,temp2)) -temp=np.reshape(x[:,5],(len(x[:,5]),1)) -X=np.hstack((X,temp)) -temp=np.reshape(x[:,8],(len(x[:,8]),1)) -X=np.hstack((X,temp)) - -X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing - -y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy -y_test=to_categorical(y_test) - -del temp1,temp2,temp - -# %% - -# Define tunable parameters" - -eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser) -lamda=0.01 #Define hyperparameter -n_layers=2 #Define number of hidden layers in the model -n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer -epochs=100 #Number of reiterations over the input data -batch_size=100 #Number of samples per gradient update - -# %% - -"""Define function to return Deep Neural Network model""" - -def NN_model(inputsize,n_layers,n_neuron,eta,lamda): - model=Sequential() - for i in range(n_layers): #Run loop to add hidden layers to the model - if (i==0): #First layer requires input dimensions - model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize)) - else: #Subsequent layers are capable of automatic shape inferencing - model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda))) - model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob) - sgd=optimizers.SGD(learning_rate=eta) - model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy']) - return model - - -Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function -Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for - -for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate - for j in range(len(eta)): #accuracy scores - DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda) - DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1) - Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1] - Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1] - - -def plot_data(x,y,data,title=None): - - # plot results - fontsize=16 - - - fig = plt.figure() - ax = fig.add_subplot(111) - cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1) - - cbar=fig.colorbar(cax) - cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize) - cbar.set_ticks([0,.2,.4,0.6,0.8,1.0]) - cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%']) - - # put text on matrix elements - for i, x_val in enumerate(np.arange(len(x))): - for j, y_val in enumerate(np.arange(len(y))): - c = "${0:.1f}\\%$".format( 100*data[j,i]) - ax.text(x_val, y_val, c, va='center', ha='center') - - # convert axis vaues to to string labels - x=[str(i) for i in x] - y=[str(i) for i in y] - - - ax.set_xticklabels(['']+x) - ax.set_yticklabels(['']+y) - - ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize) - ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize) - if title is not None: - ax.set_title(title) - - plt.tight_layout() - - plt.show() - -plot_data(eta,n_neuron,Train_accuracy, 'training') -plot_data(eta,n_neuron,Test_accuracy, 'testing') +accuracy = 100 * correct / total +print(f"Test Accuracy: {accuracy:.2f}%") !ec +!split +===== And a similar example using Tensorflow with Keras ===== +!bc pycod +import tensorflow as tf +from tensorflow import keras +from tensorflow.keras import layers, regularizers + +# Check for GPU (TensorFlow will use it automatically if available) +gpus = tf.config.list_physical_devices('GPU') +print(f"GPUs available: {gpus}") + +# 1) Load and preprocess MNIST +(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() +# Normalize to [0, 1] +x_train = (x_train.astype("float32") / 255.0) +x_test = (x_test.astype("float32") / 255.0) + +# 2) Build the model: 784 -> 100 -> 100 -> 10 +l2_reg = 1e-4 # L2 regularization strength + +model = keras.Sequential([ + layers.Input(shape=(28, 28)), + layers.Flatten(), + layers.Dense(100, activation="relu", + kernel_regularizer=regularizers.l2(l2_reg)), + layers.Dense(100, activation="relu", + kernel_regularizer=regularizers.l2(l2_reg)), + layers.Dense(10, activation="softmax") # output probabilities for 10 classes +]) + +# 3) Compile with SGD + weight decay via L2 regularizers +model.compile( + optimizer=keras.optimizers.SGD(learning_rate=0.01), + loss="sparse_categorical_crossentropy", + metrics=["accuracy"], +) + +model.summary() + +# 4) Train +history = model.fit( + x_train, y_train, + epochs=10, + batch_size=64, + validation_split=0.1, # optional: monitor validation during training + verbose=1 +) + +# 5) Evaluate on test set +test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0) +print(f"Test accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}") + +!ec !split -===== Building a neural network code ===== +===== Building our own neural network code ===== Here we present a flexible object oriented codebase for a feed forward neural network, along with a demonstration of how