diff --git a/doc/pub/week41/html/week41-bs.html b/doc/pub/week41/html/week41-bs.html index 0232fecde..608f3ab70 100644 --- a/doc/pub/week41/html/week41-bs.html +++ b/doc/pub/week41/html/week41-bs.html @@ -36,23 +36,30 @@ doconce format html week41.do.txt --html_style=bootstrap --pygments_html_style=d
@@ -396,118 +328,90 @@ MathJax.Hub.Config({
Let us first try to fit various gates using standard linear -regression. The gates we are thinking of are the classical XOR, OR and -AND gates, well-known elements in computer science. The tables here -show how we can set up the inputs \( x_1 \) and \( x_2 \) in order to yield a -specific target \( y_i \). -
- - - -"""
-Simple code that tests XOR, OR and AND gates with linear regression
-"""
-
-import numpy as np
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX matrix:{Xinv}")
-
-# The XOR gate
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}")
-
-What is happening here?
- - -"""
-Simple code that tests XOR and OR gates with linear regression
-and logistic regression
-"""
-
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LogisticRegression
-import numpy as np
-
-# Design matrix
-X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)
-print(f"The X.TX matrix:{X.T @ X}")
-Xinv = np.linalg.pinv(X.T @ X)
-print(f"The invers of X.TX matrix:{Xinv}")
-
-# The XOR gate
-yXOR = np.array( [ 0, 1 ,1, 0])
-ThetaXOR = Xinv @ X.T @ yXOR
-print(f"The values of theta for the XOR gate:{ThetaXOR}")
-print(f"The linear regression prediction for the XOR gate:{X @ ThetaXOR}")
-
-
-# The OR gate
-yOR = np.array( [ 0, 1 ,1, 1])
-ThetaOR = Xinv @ X.T @ yOR
-print(f"The values of theta for the OR gate:{ThetaOR}")
-print(f"The linear regression prediction for the OR gate:{X @ ThetaOR}")
-
-
-# The OR gate
-yAND = np.array( [ 0, 0 ,0, 1])
-ThetaAND = Xinv @ X.T @ yAND
-print(f"The values of theta for the AND gate:{ThetaAND}")
-print(f"The linear regression prediction for the AND gate:{X @ ThetaAND}")
-
-# Now we change to logistic regression
-
-
-# Logistic Regression
-logreg = LogisticRegression()
-logreg.fit(X, yOR)
-print("Test set accuracy with Logistic Regression for OR gate: {:.2f}".format(logreg.score(X,yOR)))
-
-logreg.fit(X, yXOR)
-print("Test set accuracy with Logistic Regression for XOR gate: {:.2f}".format(logreg.score(X,yXOR)))
-
-
-logreg.fit(X, yAND)
-print("Test set accuracy with Logistic Regression for AND gate: {:.2f}".format(logreg.score(X,yAND)))
-
-Not exactly impressive, but somewhat better.
- - -# and now neural networks with Scikit-Learn and the XOR
-
-from sklearn.neural_network import MLPClassifier
-from sklearn.datasets import make_classification
-X, yXOR = make_classification(n_samples=100, random_state=1)
-FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)
-FFNN.predict_proba(X)
-print(f"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}")
-
-In order to understand the back propagation algorithm and its derivation (an implementation of the chain rule), let us first digress with some simple examples. These examples are also meant to motivate -the link with back propagation and automatic differentiation. +the link with back propagation and automatic differentiation. We will discuss these topics next week (week 42).
@@ -1345,7 +1064,9 @@ $$A great introduction to automatic differentiation is given by Baydin et al., see https://arxiv.org/abs/1502.05767.
+A great introduction to automatic differentiation is given by Baydin et al., see https://arxiv.org/abs/1502.05767. +See also the video at https://www.youtube.com/watch?v=wG_nF1awSSY. +
Automatic differentiation is a represented by a repeated application of the chain rule on well-known functions and allows for the @@ -2385,484 +2106,6 @@ b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta $$ - -
A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). As described -in, the following restrictions are imposed on an activation function -for a FFNN to fulfill the universal approximation theorem -
- -The second requirement excludes all linear functions. Furthermore, in -a MLP with only linear activation functions, each layer simply -performs a linear transformation of its inputs. -
- -Regardless of the number of layers, the output of the NN will be -nothing but a linear function of the inputs. Thus we need to introduce -some kind of non-linearity to the NN to be able to fit non-linear -functions Typical examples are the logistic Sigmoid -
- -$$ - f(x) = \frac{1}{1 + e^{-x}}, -$$ - -and the hyperbolic tangent function
-$$ - f(x) = \tanh(x) -$$ - - - -The sigmoid function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called one-sided. However, it has been shown that the hyperbolic -tangent performs better than the sigmoid for training MLPs. has -become the most popular for deep neural networks -
- - - -"""The sigmoid function (or the logistic curve) is a
-function that takes any real number, z, and outputs a number (0,1).
-It is useful in neural networks for assigning weights on a relative scale.
-The value z is the weighted sum of parameters involved in the learning algorithm."""
-
-import numpy
-import matplotlib.pyplot as plt
-import math as mt
-
-z = numpy.arange(-5, 5, .1)
-sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
-sigma = sigma_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, sigma)
-ax.set_ylim([-0.1, 1.1])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sigmoid function')
-
-plt.show()
-
-"""Step Function"""
-z = numpy.arange(-5, 5, .02)
-step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
-step = step_fn(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, step)
-ax.set_ylim([-0.5, 1.5])
-ax.set_xlim([-5,5])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('step function')
-
-plt.show()
-
-"""Sine Function"""
-z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
-t = numpy.sin(z)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, t)
-ax.set_ylim([-1.0, 1.0])
-ax.set_xlim([-2*mt.pi,2*mt.pi])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('sine function')
-
-plt.show()
-
-"""Plots a graph of the squashing function used by a rectified linear
-unit"""
-z = numpy.arange(-2, 2, .1)
-zero = numpy.zeros(len(z))
-y = numpy.max([zero, z], axis=0)
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-ax.plot(z, y)
-ax.set_ylim([-2.0, 2.0])
-ax.set_xlim([-2.0, 2.0])
-ax.grid(True)
-ax.set_xlabel('z')
-ax.set_title('Rectified linear unit')
-
-plt.show()
-
-The flexibility of neural networks is also one of their main -drawbacks: there are many hyperparameters to tweak. Not only can you -use any imaginable network topology (how neurons/nodes are -interconnected), but even in a simple FFNN you can change the number -of layers, the number of neurons per layer, the type of activation -function to use in each layer, the weight initialization logic, the -stochastic gradient optmized and much more. How do you know what -combination of hyperparameters is the best for your task? -
- -However,since there are many hyperparameters to tune, and since -training a neural network on a large dataset takes a lot of time, you -will only be able to explore a tiny part of the hyperparameter space. -
- -For many problems you can start with just one or two hidden layers and -it will work just fine. For the MNIST data set you ca easily get a -high accuracy using just one hidden layer with a few hundred neurons. -You can reach for this data set above 98% accuracy using two hidden -layers with the same total amount of neurons, in roughly the same -amount of training time. -
- -For more complex problems, you can gradually ramp up the number of -hidden layers, until you start overfitting the training set. Very -complex tasks, such as large image classification or speech -recognition, typically require networks with dozens of layers and they -need a huge amount of training data. However, you will rarely have to -train such networks from scratch: it is much more common to reuse -parts of a pretrained state-of-the-art network that performs a similar -task. -
- - -The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. -
- -Unfortunately for us, the gradients often get smaller and smaller as -the algorithm progresses down to the first hidden layers. As a result, -the GD update leaves the lower layer connection weights virtually -unchanged, and training never converges to a good solution. This is -known in the literature as the vanishing gradients problem. -
- - -In other cases, the opposite can happen, namely the the gradients can -grow bigger and bigger. The result is that many of the layers get -large updates of the weights the algorithm diverges. This is the -exploding gradients problem, which is mostly encountered in -recurrent neural networks. More generally, deep neural networks suffer -from unstable gradients, different layers may learn at widely -different speeds -
- - -Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. -
- -A paper titled Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. -
- - -They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). -
- - -Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. -
- -In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. -
- - -One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). -
- - -The ReLU 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. -
- - -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 -
- -$$ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -$$ - - - -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. -
- - -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: - -Batch Normalization aims to address the vanishing/exploding gradients -problems, and more generally the problem that the distribution of each -layer’s inputs changes during training, as the parameters of the -previous layers change. -
- -The technique consists of adding an operation in the model just before -the activation function of each layer, simply zero-centering and -normalizing the inputs, then scaling and shifting the result using two -new parameters per layer (one for scaling, the other for shifting). In -other words, this operation lets the model learn the optimal scale and -mean of the inputs for each layer. In order to zero-center and -normalize the inputs, the algorithm needs to estimate the inputs’ mean -and standard deviation. It does so by evaluating the mean and standard -deviation of the inputs over the current mini-batch, from this the -name batch normalization. -
- - -It is a fairly simple algorithm: at every training step, every neuron -(including the input neurons but excluding the output neurons) has a -probability \( p \) of being temporarily dropped out, meaning it will be -entirely ignored during this training step, but it may be active -during the next step. -
- -The hyperparameter \( p \) is called the dropout rate, and it is typically -set to 50%. After training, the neurons are not dropped anymore. It -is viewed as one of the most popular regularization techniques. -
- - -A popular technique to lessen the exploding gradients problem is to -simply clip the gradients during backpropagation so that they never -exceed some threshold (this is mostly useful for recurrent neural -networks). -
- -This technique is called Gradient Clipping.
- -In general however, Batch -Normalization is preferred. -
- - -The first thing we would like to do is divide the data into two or -three parts. A training set, a validation or dev (development) set, -and a test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: -
- -If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. -
- -However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. -
- - -Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). -
- - -Here we list some of the important limitations of supervised neural network based models.
- -Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.
-