%matplotlib inline
from d2l import torch as d2l
import torch
import numpy as onp4.1 Multilayer Perceptrons
In Section 3.1, we introduced softmax regression, implementing the algorithm from scratch (Section 3.4) and using high-level APIs (Section 3.5). This allowed us to train classifiers capable of recognizing 10 categories of clothing from low-resolution images. Along the way, we learned how to wrangle data, coerce our outputs into a valid probability distribution, apply an appropriate loss function, and minimize it with respect to our model’s parameters. Now that we have mastered these mechanics in the context of simple linear models, we can launch our exploration of deep neural networks, the comparatively rich class of models with which this book is primarily concerned.
%matplotlib inline
from d2l import tensorflow as d2l
import tensorflow as tf
import numpy as onp%matplotlib inline
from d2l import jax as d2l
import jax
from jax import numpy as jnp
from jax import grad, vmap
import numpy as onp%matplotlib inline
from d2l import mxnet as d2l
from mxnet import autograd, np, npx
import numpy as onp
npx.set_np()4.1.2 Activation Functions
Activation functions are (almost everywhere) differentiable operators for transforming pre-activation signals to outputs, introducing nonlinearity into the network. Because activation functions are fundamental to deep learning, let’s briefly survey some common ones.
4.1.2.1 ReLU Function
The most popular choice, due to both simplicity of implementation and its good performance on a variety of predictive tasks, is the rectified linear unit (ReLU) (Nair and Hinton 2010). ReLU provides a very simple nonlinear transformation. Given an element \(x\), the function is defined as the maximum of that element and \(0\):
\[\operatorname{ReLU}(x) = \max(x, 0). \tag{4.1.2}\]
Informally, the ReLU function retains only positive elements and discards all negative elements by setting the corresponding activations to 0. To gain some intuition, we can plot the function. As you can see, the activation function is piecewise linear.
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = torch.relu(x)
d2l.plot(x.detach(), y.detach(), 'x', 'relu(x)', figsize=(5, 2.5))x = tf.Variable(tf.range(-8.0, 8.0, 0.1), dtype=tf.float32)
y = tf.nn.relu(x)
d2l.plot(x.numpy(), y.numpy(), 'x', 'relu(x)', figsize=(5, 2.5))x = jnp.arange(-8.0, 8.0, 0.1)
y = jax.nn.relu(x)
d2l.plot(x, y, 'x', 'relu(x)', figsize=(5, 2.5))x = np.arange(-8.0, 8.0, 0.1)
x.attach_grad()
with autograd.record():
y = npx.relu(x)
d2l.plot(x, y, 'x', 'relu(x)', figsize=(5, 2.5))When the input is negative, the derivative of the ReLU function is 0, and when the input is positive, the derivative of the ReLU function is 1. Note that the ReLU function is not differentiable when the input takes value precisely equal to 0. The libraries used here return a derivative of 0 at the origin, one valid subgradient convention. For continuously distributed preactivations the choice affects a probability-zero event. Exact zeros do occur in computation, for example from zero-initialized biases or a preceding ReLU, and in such degenerate cases the convention can change whether a unit begins to move. We plot the derivative of the ReLU function below.
y.backward(torch.ones_like(x), retain_graph=True)
d2l.plot(x.detach(), x.grad, 'x', 'grad of relu', figsize=(5, 2.5))with tf.GradientTape() as t:
y = tf.nn.relu(x)
d2l.plot(x.numpy(), t.gradient(y, x).numpy(), 'x', 'grad of relu',
figsize=(5, 2.5))grad_relu = vmap(grad(jax.nn.relu))
d2l.plot(x, grad_relu(x), 'x', 'grad of relu', figsize=(5, 2.5))y.backward()
d2l.plot(x, x.grad, 'x', 'grad of relu', figsize=(5, 2.5))The reason for using ReLU is that its derivatives are particularly well behaved: either they vanish or they just let the argument through. This makes optimization better behaved and it mitigated the well-documented problem of vanishing gradients that plagued previous versions of neural networks (more on this later).
This same flatness has a downside, however. Because the gradient is exactly zero for negative inputs, a unit whose pre-activation is pushed negative for every training example receives no gradient and stops updating: it becomes a permanently silent dead ReLU. To keep gradient flowing in that regime, a number of variants let a little signal through on the left. The best known is the parametrized ReLU (pReLU) (He et al. 2015), which adds a linear term so some information still gets through, even when the argument is negative:
\[\operatorname{pReLU}(x) = \max(0, x) + \alpha \min(0, x). \tag{4.1.3}\]
Here \(\alpha\) is a small slope (fixed for leaky ReLU, learned for pReLU).
4.1.2.2 Sigmoid Function
The sigmoid function transforms those inputs whose values lie in the domain \(\mathbb{R}\), to outputs that lie on the interval (0, 1). For that reason, the sigmoid is often called a squashing function: it squashes any input in the range (-inf, inf) to some value in the range (0, 1):
\[\operatorname{sigmoid}(x) = \frac{1}{1 + \exp(-x)}. \tag{4.1.4}\]
In the earliest neural networks, scientists were interested in modeling biological neurons that either fire or do not fire. Thus the pioneers of this field, going all the way back to McCulloch and Pitts, the inventors of the artificial neuron, focused on thresholding units (McCulloch and Pitts 1943). A thresholding activation takes value 0 when its input is below some threshold and value 1 when the input exceeds the threshold.
When attention shifted to gradient-based learning, the sigmoid function was a natural choice because it is a smooth, differentiable approximation to a thresholding unit. Sigmoids are still widely used as activation functions on the output units when we want to interpret the outputs as probabilities for binary classification problems: you can think of the sigmoid as a special case of the softmax, namely the softmax over the two logits \(\{x, 0\}\). However, the sigmoid has largely been replaced by the simpler and more easily trainable ReLU for most use in hidden layers. Much of this has to do with the fact that the sigmoid poses challenges for optimization (LeCun et al. 1998) since its gradient vanishes for large positive and negative arguments. This can lead to plateaus that are difficult to escape from. Nonetheless sigmoids are important. In later chapters (e.g., Section 12.1) on recurrent neural networks, we will describe architectures that use sigmoid units to control the flow of information across time.
Below, we plot the sigmoid function. Note that when the input is close to 0, the sigmoid function approaches a linear transformation.
y = torch.sigmoid(x)
d2l.plot(x.detach(), y.detach(), 'x', 'sigmoid(x)', figsize=(5, 2.5))y = tf.nn.sigmoid(x)
d2l.plot(x.numpy(), y.numpy(), 'x', 'sigmoid(x)', figsize=(5, 2.5))y = jax.nn.sigmoid(x)
d2l.plot(x, y, 'x', 'sigmoid(x)', figsize=(5, 2.5))with autograd.record():
y = npx.sigmoid(x)
d2l.plot(x, y, 'x', 'sigmoid(x)', figsize=(5, 2.5))The derivative of the sigmoid function is given by the following equation:
\[\frac{d}{dx} \operatorname{sigmoid}(x) = \frac{\exp(-x)}{(1 + \exp(-x))^2} = \operatorname{sigmoid}(x)\left(1-\operatorname{sigmoid}(x)\right). \tag{4.1.5}\]
The derivative of the sigmoid function is plotted below. Note that when the input is 0, the derivative of the sigmoid function reaches a maximum of 0.25. As the input diverges from 0 in either direction, the derivative approaches 0.
# Clear out previous gradients
x.grad.zero_()
y.backward(torch.ones_like(x),retain_graph=True)
d2l.plot(x.detach(), x.grad, 'x', 'grad of sigmoid', figsize=(5, 2.5))with tf.GradientTape() as t:
y = tf.nn.sigmoid(x)
d2l.plot(x.numpy(), t.gradient(y, x).numpy(), 'x', 'grad of sigmoid',
figsize=(5, 2.5))grad_sigmoid = vmap(grad(jax.nn.sigmoid))
d2l.plot(x, grad_sigmoid(x), 'x', 'grad of sigmoid', figsize=(5, 2.5))y.backward()
d2l.plot(x, x.grad, 'x', 'grad of sigmoid', figsize=(5, 2.5))4.1.2.3 Tanh Function
Like the sigmoid function, the tanh (hyperbolic tangent) function also squashes its inputs, transforming them into elements on the interval between \(-1\) and \(1\):
\[\operatorname{tanh}(x) = \frac{1 - \exp(-2x)}{1 + \exp(-2x)}. \tag{4.1.6}\]
We plot the tanh function below. Note that as input nears 0, the tanh function approaches a linear transformation. Although the shape of the function is similar to that of the sigmoid function, the tanh function exhibits point symmetry about the origin of the coordinate system.
y = torch.tanh(x)
d2l.plot(x.detach(), y.detach(), 'x', 'tanh(x)', figsize=(5, 2.5))y = tf.nn.tanh(x)
d2l.plot(x.numpy(), y.numpy(), 'x', 'tanh(x)', figsize=(5, 2.5))y = jax.nn.tanh(x)
d2l.plot(x, y, 'x', 'tanh(x)', figsize=(5, 2.5))with autograd.record():
y = np.tanh(x)
d2l.plot(x, y, 'x', 'tanh(x)', figsize=(5, 2.5))The derivative of the tanh function is:
\[\frac{d}{dx} \operatorname{tanh}(x) = 1 - \operatorname{tanh}^2(x). \tag{4.1.7}\]
It is plotted below. As the input nears 0, the derivative of the tanh function approaches a maximum of 1. And as we saw with the sigmoid function, as input moves away from 0 in either direction, the derivative of the tanh function approaches 0.
# Clear out previous gradients
x.grad.zero_()
y.backward(torch.ones_like(x),retain_graph=True)
d2l.plot(x.detach(), x.grad, 'x', 'grad of tanh', figsize=(5, 2.5))with tf.GradientTape() as t:
y = tf.nn.tanh(x)
d2l.plot(x.numpy(), t.gradient(y, x).numpy(), 'x', 'grad of tanh',
figsize=(5, 2.5))grad_tanh = vmap(grad(jax.nn.tanh))
d2l.plot(x, grad_tanh(x), 'x', 'grad of tanh', figsize=(5, 2.5))y.backward()
d2l.plot(x, x.grad, 'x', 'grad of tanh', figsize=(5, 2.5))4.1.3 Summary and Discussion
We now know how to incorporate nonlinearities to build expressive multilayer neural network architectures. Your knowledge already puts you in command of a toolkit much like that of a practitioner circa 1990, except that you can lean on powerful open-source frameworks to build models in a few lines of code, rather than coding up layers and their derivatives by hand in C or Fortran.
A key reason ReLU displaced sigmoid and tanh in hidden layers is that it is so much more amenable to optimization. One could argue that this was one of the innovations that helped the resurgence of deep learning in the early 2010s. Research on activation functions has not stopped, though, and you will meet newer ones once we reach the Transformer architectures later in the book. The most common are GELU (Gaussian error linear unit), \(x \Phi(x)\), where \(\Phi\) is the standard Gaussian cumulative distribution function (Hendrycks and Gimpel 2016), used in BERT and GPT-2-style models; Swish, \(x \operatorname{sigmoid}(\beta x)\) (Ramachandran et al. 2017); and SwiGLU (Shazeer 2020), a gated variant that is the default feedforward nonlinearity in recent large language models such as PaLM, LLaMA, and Mistral. For now, ReLU remains the sensible default for the models we build next.
4.1.4 Exercises
- Show that adding layers to a linear deep network, i.e., a network without nonlinearity \(\sigma\) can never increase the expressive power of the network. Give an example where it actively reduces it.
- Find weights for a two-hidden-unit ReLU network that computes XOR, and verify them on the four inputs. (You may reuse the construction in Figure 4.1.2, but try to derive your own first.) Can a single ReLU unit compute XOR? Why or why not?
- Compute the derivative of the pReLU activation function.
- Compute the derivative of the Swish activation function \(x \operatorname{sigmoid}(\beta x)\).
- Show that an MLP using only ReLU (or pReLU) constructs a continuous piecewise linear function.
- Explain intuitively why composing ReLU layers can roughly double the number of linear pieces the network represents with each added layer, so that depth buys exponentially many pieces while width buys only linearly many. (This is the depth-versus-width gap behind the universal-approximation caveat above.)
- Sigmoid and tanh are very similar.
- Show that \(\operatorname{tanh}(x) + 1 = 2 \operatorname{sigmoid}(2x)\).
- Prove that the function classes parametrized by both nonlinearities are identical. Hint: affine layers have bias terms, too.
- Assume that we have a nonlinearity that applies to one minibatch at a time, such as the batch normalization (Ioffe and Szegedy 2015) (covered in Section 7.3). What kinds of problems do you expect this to cause?
- Provide an example where the gradients vanish for the sigmoid activation function.