GNGiseldo Neo and Alana NeoBooks
Mathematical Foundations for Machine Learning7 / 8

Neural Networks

In the previous chapters, we studied linear models and transformations of Neural networks combine these two ideas in an adaptive way: instead of manually choosing all features, the training adjusts successive transformations from the data.

In supervised learning, we received a sample

D={(xi,yi)}i=1N,xi∈X,yi∈Y, D=\{(x_i,y_i)\}_{i=1}^N, \qquad x_i\in X,\quad y_i\in Y,

and we chose a parameterized hypothesis hθ:X→Y^h_\theta:X\to\widehat Y. vector θ\theta gathers all the weights and biases of the network.

ℓ:Y^×Y⟶[0,∞) \ell:\widehat Y\times Y\longrightarrow[0,\infty)

measures the quality of an individual prediction.

ED(θ)=1N∑i=1Nℓ(hθ(xi),yi). E_D(\theta) =\frac1N\sum_{i=1}^N\ell(h_\theta(x_i),y_i).

The training algorithm seeks parameters that reduce this error, usually with regularization and a gradient-based method. real objective continues to be generalised for examples not observed; Memorizing the sample is not enough.

6.1 From artificial unit to network

An artificial neuron receives a vector x∈Rdx\in\mathbb R^d, calculates a match and apply a gg activation function:

z=wTx+b,a=g(z).(6.1) z=w^{\mathsf T}x+b, \qquad a=g(z). \tag{6.1}

Here, w∈Rdw\in\mathbb R^d contains the weights, b∈Rb\in\mathbb R is bias, zz is the preactivation and aa is the produced activation. shifting the threshold; without it, many borders would be forced to pass by origin.

A layer with mm neurons calculates all these operations in parallel:

z=Wx+b,a=g(z), z=Wx+b, \qquad a=g(z),

where W∈Rm×dW\in\mathbb R^{m\times d}, b∈Rmb\in\mathbb R^m and gg is applied component to component. Each line of WW corresponds to the weights of one neuron.

A feedforward network, or without feedback, chain layers without cycles. For two parametrizated layers,

a(1)=g1(W(1)x+b(1)), a^{(1)}=g_1(W^{(1)}x+b^{(1)}), hθ(x)=g2(W(2)a(1)+b(2)). h_\theta(x)=g_2(W^{(2)}a^{(1)}+b^{(2)}).

Flow of a feedforward network: the input is transformed by a hidden layer and reaches the output layer.

Figure 6.1. Flow of a feedforward network: the input is transformed by a hidden layer and reaches the output layer.

We call hidden layers the transformations between input and the output. The input itself has no parameters and therefore is not usually counted as a training layer. The expression “network of a layer” can be ambiguous: some authors have only hidden layers, while others In this chapter, we will say explicitly “a hidden layer” whenever this distinction imports.

6.2 Why does activation need to be nonlinear?

If all activations are identity, two similar layers are reduced to a single transformation in order:

W(2)(W(1)x+b(1))+b(2)=W(2)W(1)⏟W′x+W(2)b(1)+b(2)⏟b′. W^{(2)}(W^{(1)}x+b^{(1)})+b^{(2)} =\underbrace{W^{(2)}W^{(1)}}_{W'}x +\underbrace{W^{(2)}b^{(1)}+b^{(2)}}_{b'}.

Stack linear transformations, therefore, does not increase the class of Representable functions. Nonlinear activations between layers prevent this reduction and allow to build complex boundaries and approximations. The output layer, however, shall be chosen according to the task: identity for unrestricted regression, sigmoid for a probability binary and * softmax* for probabilities between various classes are choices Common.

6.3 Architecture and learning

The architecture defines the operation graph: number of layers, width of each layer, activations and connections. Weights and biases are parameters learned. Now width, depth, learning rate and regularization force are hyperparameters chosen by validation.

The training of a feedforward network can be summarized in four repeated steps:

  1. forward propagation: calculate activations and prediction;
  2. loss: compare prediction to target;
  3. retropropagation: calculate derived by the chain rule;
  4. update: modify the parameters with an optimizer.
# Pseudocode of a dense layer
z = W @ x + b
a = ativacao(z)

Although the expression is short, it is essential to follow the formats. x has dd components and the layer has mm neurons, W is shaped (m, d), while b, z and a have mm components. Dimension errors are among the most common problems in the first implementations.

Exercises

  1. Determine WW and bb formats for a layer that receives 8 features and produces 32 activations.
  2. How many training parameters does this layer have?
  3. Demonstrate that the composition of three related transformations is still I’m in the mood.
  4. Differentiate parameter, hyperparameter, preactivation and activation.
  5. Explain why a low loss in training does not guarantee good generalization.

6.4 Activation Functions

An activation function transforms the preactivation zz produced by a neuron. In the hidden layers, its main function is to introduce no linearity. At the exit, it also determines the domain of prediction and must be compatible with task and loss.

During backpropagation, the derivative of the activation participates in the rule of chain. Thus, saturation, discontinuity of the derivative and scale of gradients directly affect optimization.

Qualitative comparison between ReLU, Leaky ReLU, sigmoid and hyperbolic tangent.

Figure 6.2. Qualitative comparison between ReLU, Leaky ReLU, sigmoid and hyperbolic tangent.

6.4.1 ReLU Activation Function (Rectified Linear Unit)

The corrected linear unit is defined by

ReLU⁡(z)=max⁡(0,z). \operatorname{ReLU}(z)=\max(0,z).

Its derivative, except in z=0z=0, is

ReLU⁡′(z)={0,z<0,1,z>0. \operatorname{ReLU}'(z)= \begin{cases} 0, & z<0,\\ 1, & z>0. \end{cases}

At zero point the function is not differentiable; libraries adopt a conventional subderivative, usually zero. ReLU is cheap and not saturated in the positive semi-axis, so it is a frequent choice in layers. Hidden.

In the negative semiaxis, however, the gradient is zero. negative preactivations for all examples may stop updating Your weights: is the problem of the dead ReLU. Initialization, rate of learning and variants with negative inclination help reduce it.

6.4.2 Leaky ReLU Activation Function

Leaky ReLU maintains a small slope on the negative side:

LeakyReLU⁡α(z)={z,z>0,αz,z≤0,0<α<1. \operatorname{LeakyReLU}_\alpha(z)= \begin{cases} z, & z>0,\\ \alpha z, & z\leq0, \end{cases} \qquad 0<\alpha<1.

Its derivative is 11 on the positive side and α\alpha on the negative side, except for the convention chosen at zero. Thus, a neuron receives some gradient even when its preactivation is negative. α=0,01\alpha=0{,}01 are common, but α\alpha is a hyperparameter and not a universal constant.

6.4.3 Sigmoid Activation Function

The logistic sigmoid is

σ(z)=11+e−z,0<σ(z)<1. \sigma(z)=\frac1{1+e^{-z}}, \qquad 0<\sigma(z)<1.

Its derivative can be calculated from the output itself:

σ′(z)=σ(z)(1−σ(z)). \sigma'(z)=\sigma(z)(1-\sigma(z)).

The maximum value of the derivative is 1/41/4, reached in z=0z=0. For ∣z∣|z| large, the output approaches zero or one and the derivative approaches zero. In deep nets, multiply successively small derivatives contributes to the disappearance of the gradient .

The sigmoid is especially suitable for the exit layer of a binary classification, where it can represent P(Y=1∣x)P(Y=1\mid x). In modern hidden layers, ReLU and variants usually to be preferred.

A direct implementation of e−ze^{-z} can overflow to zz a lot Negative. Numerically stable functions treat cases separately z≥0z\geq0 e z<0z<0.

6.4.4 Hyperbolic Tangent Activation Function (tanh)

The hyperbolic tangent is

tanh⁡(z)=ez−e−zez+e−z,−1<tanh⁡(z)<1, \tanh(z)=\frac{e^z-e^{-z}}{e^z+e^{-z}}, \qquad -1<\tanh(z)<1,

and its derivative is

ddztanh⁡(z)=1−tanh⁡2(z). \frac{d}{dz}\tanh(z)=1-\tanh^2(z).

Unlike sigmoid, tanh is centered on zero. This can facilitate optimization when positive and negative activations are useful. also satura for large-magnitude inputs and therefore does not eliminate the disappearance of the gradient. recurrent networks.

6.4.5 Softmax

For classification between KK mutually exclusive classes, the layer of output produces * logs* z∈RKz\in\mathbb R^K. Softmax converts them into Probabilities:

softmax⁡(z)i=ezi∑j=1Kezj,i=1,…,K. \operatorname{softmax}(z)_i =\frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}, \qquad i=1,\ldots,K.

Each component is positive and the sum is one. Add the same constant to all logits do not change the result. We use this property for avoid overflowing:

softmax⁡(z)i=ezi−m∑jezj−m,m=max⁡jzj. \operatorname{softmax}(z)_i =\frac{e^{z_i-m}}{\sum_j e^{z_j-m}}, \qquad m=\max_jz_j.

Softmax docks outputs: increasing the probability of a class reduces the mass available to others. Therefore, it applies to classes exclusive. In multi-label classification, in which several classes can be true simultaneously, we use an independent sigmoid by label.

6.4.6 Output and task activation

TaskTypical outputActivationCommon Loss
Royal Regression1 or more valuesidentitysquared error
Binary classification1 logitsigmoidbinary cross-entropy
Exclusive multiclassKK logssoftmaxcategorical cross-entropy
Multi-labelKK logsKK sigmoidsbinary cross-entropy

In practice, libraries often combine logits and entropy cross in a single stable operation. In this case, the loss function waits raw logits and applies internally sigmoid or softmax; apply the activation before can duplicate the operation and impair stability.

import numpy as np


def softmax_estavel(z):
    z = np.asarray(z, dtype=float)
    deslocado = z - np.max(z, axis=-1, keepdims=True)
    exp_z = np.exp(deslocado)
    return exp_z / np.sum(exp_z, axis=-1, keepdims=True)

Exercises

  1. Calculate ReLU, sigmoid and tanh to z∈{−2,0,2}z\in\{-2,0,2\}.
  2. Show that σ′(z)=σ(z)(1−σ(z))\sigma'(z)=\sigma(z)(1-\sigma(z)).
  3. Prove that softmax is invariant to the sum of a constant in all logits.
  4. Explain why softmax is not suitable for an image that can contain both “car” and “pedestrian”.
  5. What happens to the gradients of a sigmoid cell when the pre-activations have great magnitude?

6.5 Single layer neural network

Before studying wide networks, it is useful to separate two architectures from the sometimes they get similar names.

  • A single neuron calculates g(wTx+b)g(w^{\mathsf T}x+b).
  • A network with a hidden layer uses several intermediate neurons And then you combine your activations into an exit.

In this chapter, “single layer network” will mean a network with a hidden layer, because this is the convention used in approximation theorems of the following section.

6.5.1 A single neuron

A neuron with x∈Rdx\in\mathbb R^d input produces

h(x)=g(wTx+b). h(x)=g(w^{\mathsf T}x+b).

Different activation and loss choices recover already known models:

TemplateOutput activationPredictionTypical loss
Linear regressionidentityreal valuesquared error
Perceptronsignalclass {−1,+1}\{-1,+1\}classification error
Logistic regressionsigmoidbinary probabilitycross-entropy
Softmax Returnsoftmax over KK logsProbabilities of KK classescategorical cross-entropy

All these models produce linear decision boundaries in the space of Input. Activation changes output and appropriate loss, but level wTx+b=0w^{\mathsf T}x+b=0 remains a hyperplane. solves, for example, the XOR without a prior transformation of features.

6.5.2 A hidden layer

Consider mm hidden neurons, an input with dd features and an scalar output. Hidden layer calculates

aj(x)=g(wjTx+bj),j=1,…,m. a_j(x)=g(w_j^{\mathsf T}x+b_j), \qquad j=1,\ldots,m.

The output combines these new features:

hθ(x)=gout ⁣(c+∑j=1mvjaj(x)).(6.2) h_\theta(x) =g_{\mathrm{out}}\!\left( c+\sum_{j=1}^m v_j a_j(x) \right). \tag{6.2}

In matrix notation,

hθ(x)=gout ⁣(vTg(Wx+b)+c), h_\theta(x) =g_{\mathrm{out}}\!\left( v^{\mathsf T}g(Wx+b)+c \right),

with

W∈Rm×d,b∈Rm,v∈Rm,c∈R. W\in\mathbb R^{m\times d},\quad b\in\mathbb R^m,\quad v\in\mathbb R^m,\quad c\in\mathbb R.

Each hidden neuron learns a aj(x)a_j(x) feature. output learns how to combine them. Unlike a transformation fixed polynomial, both directions wjw_j and displacements bjb_j they are adjusted by the data.

6.5.3 Parameter count

The matrix WW contains mdmd weights, the vector bb contains mm biases, the output contains mm weights and a bias. (6.2) has

md+m+m+1=m(d+2)+1 md+m+m+1=m(d+2)+1

Training parameters. For kk outputs, we use V∈Rk×mV\in\mathbb R^{k\times m} and c∈Rkc\in\mathbb R^k, totaling

md+m+km+k md+m+km+k

parameters. This count helps estimate memory, compare architectures and identify implementation errors.

6.5.4 Batch forward propagation

Adopt the convention that each line of matrix X∈RN×dX\in\mathbb R^{N\times d} It’s an example.

Z(1)=XWT+1bT∈RN×m, Z^{(1)}=XW^{\mathsf T}+\mathbf1b^{\mathsf T} \in\mathbb R^{N\times m}, A(1)=g(Z(1)), A^{(1)}=g(Z^{(1)}), Z(2)=A(1)VT+1cT∈RN×k. Z^{(2)}=A^{(1)}V^{\mathsf T}+\mathbf1c^{\mathsf T} \in\mathbb R^{N\times k}.

The vector of one represents the transmission of the same bias to all examples; libraries perform this operation by * broadcasting*.

import numpy as np


def forward_uma_camada(X, W, b, V, c):
    Z1 = X @ W.T + b
    A1 = np.maximum(Z1, 0.0)
    Z2 = A1 @ V.T + c
    return Z1, A1, Z2

Returning intermediate values is useful in learning: a backpropagation reuses Z(1)Z^{(1)} and A(1)A^{(1)} to calculate the derivatives.

6.5.5 Training

The parameters are not adjusted neuron by neuron in shape independent. Output loss generates gradients that cross the layer of exit and reach all hidden neurons. neuronal permutations may represent the same function and function as the neurons. loss is generally not convex in the parameters of all layers, solution does not have the simplicity of linear regression by minimum square.

Even so, efficient derivatives allow you to train large networks by gradient descent and its variants. Initialization, data scale, learning rate, lot size and regularization influence the result.

Exercises

  1. Count the parameters of a network with d=10d=10, m=20m=20 and k=3k=3.
  2. Check the formats of all matrices in the batch calculation.
  3. Explain why to change the order of two hidden neurons and exchange the corresponding VV columns does not change the network function.
  4. Why applying the signal function inside the hidden layer makes it difficult to Gradient training?
  5. Compare fixed polynomial features with learned activations from a hidden layer.

6.6 Universal approximation theorem for single layer networks

Consider the functions produced by networks with a hidden layer and output linear:

g(x)=c+∑j=1mvj sigma(wjTx+bj).(6.3) g(x)=c+\sum_{j=1}^{m}v_j\,sigma(w_j^{\mathsf T}x+b_j). \tag{6.3}

Each value of mm defines a class with finite width. The theorem studies the union of these classes when we allow mm to be as large as It’s necessary.

6.6.1 Statement

Be K⊂RdK\subset\mathbb R^d compact and be σ:R→R\sigma:\mathbb R\to\mathbb R a continuous function. (6.3) shape are dense in C(K)C(K), with the standard of the supreme, if and only if σ\sigma is not a polynomial.

In concrete terms, for every continuous function f:K→Rf:K\to\mathbb R and all ε>0\varepsilon>0, there is a finite width mm and there are parameters wj,bj,vj,cw_j,b_j,v_j,c such that

∥f−g∥∞=sup⁡x∈K∣f(x)−g(x)∣<ε.(6.4) \lVert f-g\rVert_\infty =\sup_{x\in K}|f(x)-g(x)|<\varepsilon. \tag{6.4}

For a vector output f:K→Rkf:K\to\mathbb R^k, we can approach each component and gather them into an output layer with kk units. Choosing the error of each component small enough, we obtain a approach in the desired vector standard.

6.6.2 How to interpret the theorem

The word dense means we can get arbitrarily close of any element of C(K)C(K), not that a single fixed network represents all functions. The width and parameters depend on ff, of KK and ε\varepsilon tolerance .

The hypothesis of compactness also matters. In Rd\mathbb R^d, a set compact is closed and limited. The supreme standard in (6.4) requires that the approach be good simultaneously at all points of this domain, a stronger guarantee than correcting just a finite sample.

Usual activations such as ReLU, sigmoid and tanh are non-polynomial and meet the expressiveness condition. If σ\sigma is a qqgrade polynomial, each term σ(wTx+b)\sigma(w^{\mathsf T}x+b) has a maximum degree qq; sums Finitas continue to grade at most qq. This finite dimension class cannot evenly approximate all continuous functions.

6.6.3 Intuition with ReLU in a dimension

A combination of ReLUs in a variable,

g(x)=a+sx+∑j=1mvjReLU⁡(x−tj), g(x)=a+sx+\sum_{j=1}^{m}v_j\operatorname{ReLU}(x-t_j),

is linear by parts. Before tjt_j, the corresponding term is zero; After tjt_j, it changes the slope in vjv_j. Therefore, placing tjt_j breakpoints and by choosing the tilt changes, we can to build a linear interpolation by parts.

Every continuous function in a compact range is uniformly continuous. When refining the mesh sufficiently, its linear interpolation by parts it is evenly close to the function. This provides a concrete intuition for the universality of the ReLU in a dimension. general proof requires additional arguments.

6.6.4 What the theorem does not guarantee

The result is existence. It does not state:

  • what width mm is required for a specific function;
  • that the network will be small or computationally efficient;
  • which gradient descent will find the existing parameters;
  • that a finite sample will identify the function;
  • that the network will generalise well outside KK;
  • that a hidden layer is always the best architecture.

A wide network can represent the solution and still be difficult to train. Furthermore, approximating any continuous function does not imply approaching with few data. Expressivity, optimization and generalization are issues distinct.

6.6.5 Width versus depth

The theorem allows you to concentrate all complexity into a hidden layer, But it doesn’t say that it’s efficient. compact as simple operations composition. Deep networks reflect this compositional structure and may represent certain functions with much less units than a shallow net.

Thus, “one layer is universal” does not make depth useless. universality answers if an approximation exists; studies of efficiency investigate how many units and layers are required.

6.6.6 Computing example: piecewise linear function

import numpy as np


def relu(x):
    return np.maximum(x, 0.0)


def rede_relu_1d(x, intercepto, inclinacao, pontos, saltos):
    """Representa uma função linear por partes usando ReLUs."""
    x = np.asarray(x, dtype=float)
    y = intercepto + inclinacao * x
    for t, delta in zip(pontos, saltos):
        y = y + delta * relu(x - t)
    return y

The vector saltos does not store the slopes of each stretch, but the change of inclination at each breakpoint. This parameterization is a explicit representation of a ReLU network with an input and a layer Hiding.

Exercises

  1. Explain the difference between uniform error in KK and error only in Training points.
  2. Show a finite combination of polynomial activations of grade qq remains a polynomial of grade at most qq.
  3. Represent f(x)=∣x∣f(x)=|x| exactly with two ReLU units.
  4. Build a 11 tilt function before zero and 33 after zero using the previous code.
  5. Give an example of statement about training that does not stem from universal approximation theorem.

6.7 Multi-layer neural network

A deep network chain several learned transformations. receives one representation, produces another and delivers to the next layer. As the connections only point forward, the computer graph does not It has cycles.

6.7.1 Layer notation

Consider a network with LL layers parameterized. a(0)=x∈Rn0a^{(0)}=x\in\mathbb R^{n_0} and for ℓ=1,…,L\ell=1,\ldots,L,

z(ℓ)=W(ℓ)a(ℓ−1)+b(ℓ),a(ℓ)=gℓ ⁣(z(ℓ)).(6.5) z^{(\ell)} =W^{(\ell)}a^{(\ell-1)}+b^{(\ell)}, \qquad a^{(\ell)}=g_\ell\!\left(z^{(\ell)}\right). \tag{6.5}

If the ℓ\ell layer has nℓn_\ell units, then

W(ℓ)∈Rnℓ×nℓ−1,b(ℓ),z(ℓ),a(ℓ)∈Rnℓ. W^{(\ell)}\in\mathbb R^{n_\ell\times n_{\ell-1}}, \qquad b^{(\ell)},z^{(\ell)},a^{(\ell)}\in\mathbb R^{n_\ell}.

The complete hypothesis is

hθ=h(L)∘h(L−1)∘⋯∘h(1), h_\theta =h^{(L)}\circ h^{(L-1)}\circ\cdots\circ h^{(1)},

where h(ℓ)(a)=gℓ(W(ℓ)a+b(ℓ))h^{(\ell)}(a)=g_\ell(W^{(\ell)}a+b^{(\ell)}). The layer h(1)h^{(1)} appears to the right because it is applied first. Invert this order is a frequent mistake when writing compositions.

The widths determine the formats of the matrices between consecutive layers.

Figure 6.3. The widths determine the formats of the matrices between consecutive layers.

6.7.2 Dense layers

In a layer dense, or fully connected, each unit receives All activations of the previous layer. That explains why W(ℓ)W^{(\ell)} has one entry for each pair formed by a unit of current layer and one unit of the anterior layer.

Not every network uses dense connections. Convolutional layers share weights and explore spatial structure; attention mechanisms combine representations according to similarities learned; recurring networks share parameters over time. It’s useful, but operators don’t have to be arbitrary dense matrices.

6.7.3 Hidden activations and output activation

Hidden activations g1,…,gL−1g_1,\ldots,g_{L-1} introduce nonlinearity. They don’t need to be equal in all layers, though architectures homogeneous are common. The final activation gLg_L is chosen according to meaning desired for output:

  • identity for regression without band restriction;
  • sigmoid for binary probability or independent labels;
  • softmax for mutually exclusive classes;
  • another specific transformation when the output must comply with a restriction of the problem.

During training, we usually keep the values before activation final, called logs, because losses combined with logits offer greater numerical stability.

6.7.4 Parameter count

A dense layer of width nℓ−1n_{\ell-1} for nℓn_\ell has

nℓnℓ−1+nℓ=nℓ(nℓ−1+1) n_\ell n_{\ell-1}+n_\ell =n_\ell(n_{\ell-1}+1)

parameters: a matrix of weights and a bias per unit. whole has

P=∑ℓ=1Lnℓ(nℓ−1+1)(6.6) P=\sum_{\ell=1}^{L} n_\ell(n_{\ell-1}+1) \tag{6.6}

Training parameters. For example, architecture 4→8→6→34\to8\to6\to3 contains

8(4+1)+6(8+1)+3(6+1)=115 8(4+1)+6(8+1)+3(6+1)=115

parameters. The count includes biases and does not count the input layer as parametrizada.

6.7.5 Batch calculation

When each line represents an example, A(0)=X∈RN×n0A^{(0)}=X\in\mathbb R^{N\times n_0}. Propagation uses

Z(ℓ)=A(ℓ−1)(W(ℓ))T+b(ℓ), Z^{(\ell)} =A^{(\ell-1)}(W^{(\ell)})^{\mathsf T}+b^{(\ell)},

where the bias is transmitted to the NN lines by * broadcasting*. Z(ℓ)Z^{(\ell)} and A(ℓ)A^{(\ell)} have N×nℓN\times n_\ell format.

import numpy as np


def relu(z):
    return np.maximum(z, 0.0)


def forward_denso(X, pesos, vieses):
    A = np.asarray(X, dtype=float)
    cache = []

    for W, b in zip(pesos[:-1], vieses[:-1]):
        Z = A @ W.T + b
        A_novo = relu(Z)
        cache.append((A, Z))
        A = A_novo

    Z_saida = A @ pesos[-1].T + vieses[-1]
    cache.append((A, Z_saida))
    return Z_saida, cache

The example uses ReLU in hidden layers and leaves the last layer in logits. cache saves values required for backpropagation. automatic differentiation library, the computational graph fulfills this role.

6.7.6 Hierarchical representations

Each layer can reuse features built by the previous one. In a visual task, initial layers can respond to contrasts local, while later layers combine these responses into patterns This interpretation is useful, but it doesn’t mean that each neuron always has a simple human meaning.

The depth also changes the geometry of the optimization. The function can be simple in the output space and yet have many parameterizations equivalents. Gradients that cross several layers may disappear or explode; initialization, normalization, residual connections and choice of activation helps to control these effects.

Check formats before values

Many neural network errors are silent incompatibilities of axes. Document if examples occupy rows or columns and test each Matrix product. * Broadcasting* can produce a valid matrix with one meaning different than intended.

Exercises

  1. List the formats of all tensors in a network 5→10→4→25\to10\to4\to2 for a lot with 32 examples.
  2. Calculate the number of parameters of this network using (6.6).
  3. Show algebraically that two layers without nonlinear activation can be replaced by a single layer in order.
  4. Explain why the input layer does not add parameters.
  5. Modify pseudocode to apply stable softmax on output only during inference.

6.8 Universal approximation theorem for ReLU networks limited by width

The previous theorem allows you to use a single hidden layer, as long as yours width can grow. There is a complementary possibility: keep the small width and allow depth to grow. For ReLU networks, this exchange still preserves the ability of universal approximation in the certain spaces of function.

6.8.1 Statement in the L1L^1 norm

Be f:Rn→Rf:\mathbb R^n\to\mathbb R an integrable function in the sense of Lebesgue, that is,

∥f∥1=∫Rn∣f(x)∣ dx<∞. \lVert f\rVert_1 =\int_{\mathbb R^n}|f(x)|\,dx<\infty.

For all ε>0\varepsilon>0, there is a feedforward network fully connected with ReLU activation, maximum width not exceeding n+4n+4 and finite depth such that the FθF_\theta function represented by the network satisfies

∥f−Fθ∥1=∫Rn∣f(x)−Fθ(x)∣ dx<ε.(6.7) \lVert f-F_\theta\rVert_1 =\int_{\mathbb R^n}|f(x)-F_\theta(x)|\,dx <\varepsilon. \tag{6.7}

Depth is not previously fixed: it can increase when the target function becomes more complex or when ε\varepsilon decreases. Therefore, the result does not state that a unique architecture of width n+4n+4 and fixed depth approximates all functions.

6.8.2 The meaning of width

The width of a network is the largest number of units in one of its hidden layers. If the widths are n1,…,nL−1n_1,\ldots,n_{L-1}, then

largura⁡(N)=max⁡ℓ=1,…,L−1nℓ. \operatorname{largura}(\mathcal N) =\max_{\ell=1,\ldots,L-1}n_\ell.

The n+4n+4 limit depends on the input dimension nn, and not on the number of sample examples. It is a sufficient limit for the above result, not a statement that every function requires exactly that width or that this is the best limit for every variant of the problem.

6.8.3 Comparison with approximation by a hidden layer

The two results distribute capacity in different ways:

AspectFlat netLimited-width network
Deptha hidden layercan grow
Widthcan grownot more than n+4n+4
Functions in the statementcontinuous in compactIntegrable in Rn\mathbb R^n
StandardL∞L^\infty uniformintegral L1L^1
Type of guaranteeexistenceexistence

Standards express different requirements. major deviation:

∥f−g∥∞=sup⁡x∈K∣f(x)−g(x)∣. \lVert f-g\rVert_\infty =\sup_{x\in K}|f(x)-g(x)|.

The L1L^1 error accumulates the area — or volume — of the difference. approach may have very large error in a small measurement region and still show reduced L1L^1 error. Therefore, the two theorems do not should be compared only by the number of neurons.

6.8.4 Construction intuition

A constructive demonstration can be understood in four movements.

  1. Truncate the tails. As f∈L1(Rn)f\in L^1(\mathbb R^n), we chose a large cube outside of which the ∣f∣|f| integral is small.
  2. Approach by simple blocks. Inside the cube, simple functions, constants in small regions, approach ff in L1L^1.
  3. Build one block at a time. Deep ReLU Layers form approximations of regions and their values, reusing few Auxiliary coordinates.
  4. Accumulate results. The network carries input and a sum Partial while adding the contribution of the next block.

The width remains limited because the same units function as a small workspace reused along the depth. network exchange processing “in parallel”, characteristic of a layer very wide, by “sequential” processing in many layers.

A wide network calculates many blocks in parallel; a narrow and deep network reuses width along the layers.

Figure 6.4. A wide network calculates many blocks in parallel; a narrow and deep network reuses width along the layers.

6.8.5 Why can indicator functions be approximated?

ReLU is continuous, so a finite ReLU network does not represent exactly the discontinuity of an indicator function at all points. In standard L1L^1, this is not necessary. We can replace the border abrupt by a narrow and linear transition by parts. thickness of the transition region, its contribution to the integral error It also decreases.

This observation highlights the importance of the norm. converges evenly to an indicator function in a domain that It contains its border, because the jump remains discontinuous.

6.8.6 Extension to multiple outputs

For f:Rn→Rkf:\mathbb R^n\to\mathbb R^k, a simple strategy is to approach each component. However, the width limit needs to account for the exits and architecture used to transport them. We should not apply automatically the value scale n+4n+4 to any vector theorem without check your specific statement.

6.8.7 What the Guarantee Doesn’t Solve

Just like the theorem of a hidden layer, (6.7) is a representation result. It does not provide:

  • a small depth;
  • a small amount of parameters;
  • an algorithm to find the weights;
  • numerical stability during training;
  • guarantee of generalization from a finite sample;
  • good point-to-point approach, as the standard is L1L^1.

An existing construction can be too deep for practice. It can also use weights of great magnitude, which makes it difficult to optimization. Choice of architecture remains a decision statistical and computational.

6.8.8 Numerical verification of the norm

In a dimension, if we know a mesh sufficiently thin, we can approximate the integral of the error by trapezium rule:

import number as np


def error_l1_approached(f, g, beginning, end, points=20_001):
    x = np.linspace(start, end, points)
    error = np.abs(f(x) -g(x))
    return np.trapezoid(error, x)

This calculation evaluates only the range chosen and produces a Numerical approach. To relate it to the integral across the line, We also need to limit or estimate tail error.

Exercises

  1. Differentiate maximum width, depth and total number of parameters.
  2. Explain why a function with high error in a very long interval narrow may have small L1L^1 error.
  3. Show that the indicator function of a range cannot be approximate evenly by continuous functions with error smaller than 1/21/2 in a domain that contains its ends.
  4. For n=20n=20, what width is enough provided by the utterance? Does the result determine the depth?
  5. Compare the idea of parallel computing of a wide network with the sequential reuse of units in a deep network.

6.9 Width versus depth of neural networks

Previous theorems show that both width and depth They don’t say, though, that two architectures with the same number of parameters are also efficient to represent a particular function.

Width offers many units operating in parallel on the same representation. Depth allows composing transformations and reuse intermediate results.This difference is similar to the comparison between an expanded expression and a program that creates auxiliary values and Re-use it.

6.9.1 Composition and linear regions

ReLU networks represent linear functions per part. a layer with multiple ReLUs can introduce several breakpoints. composing layers, the breakpoints of a transformation can be replicated in the regions previously created, making the number of Snippets grow rapidly.

Consider the triangular function in [0,1][0,1]:

T(x)=2ReLU⁡(x)−4ReLU⁡ ⁣(x−12)+2ReLU⁡(x−1). T(x)=2\operatorname{ReLU}(x) -4\operatorname{ReLU}\!\left(x-\frac12\right) +2\operatorname{ReLU}(x-1).

It rises from 00 to 11 and then descends to 00. T∘TT\circ T produces more oscillations; repeating the composition increases your number without needing to rewrite each snippet independently.

The composition of a triangular function progressively creates more linear regions.

Figure 6.5. The composition of a triangular function progressively creates more linear regions.

Depth separation results formalize this intuition: there are families of functions that deep nets represent with quantity Moderate of units, but whose depth network approach limited requires much greater width in some utterances of mode any statement of this kind depends on the hypotheses — activation, Standard, error allowed, domain and limits imposed on weights — and should not be converted into a universal rule over any data set.

6.9.2 When the width helps

Larger layers may:

  • learn various characteristics at the same level of abstraction;
  • reduce bottlenecks that would rule out information too soon;
  • increase the parallelism available on accelerators;
  • offer short paths between entrance and exit.

Excessive width also increases memory, matrix products and risk of redundancy. More parameters do not replace data, regularization or a appropriate objective function.

6.9.3 When depth helps

Depth is especially natural when the task has structure compositional: pixels form local patterns, patterns form parts and parts form objects; in language, symbols form expressions and expressions participate in larger contexts.

However, deep nets have long derivation paths. can cause gradients that disappear or explode, elevate latency sequential and make optimization more sensitive. Residual connections, adequate normalization and initialization were developed, in part, to make deep nets trainable.

6.9.4 Bottlenecks and residual connections

A very narrow layer can work as a bottleneck. This is useful if We want compression, but harmful when it eliminates necessary information to the following layers. A residual connection calculates

a(ℓ+1)=a(ℓ)+Fℓ(a(ℓ)), a^{(\ell+1)}=a^{(\ell)}+F_\ell(a^{(\ell)}),

as long as the formats are compatible. direct path to information and gradients, allowing the block Learn a correction instead of rebuilding the entire representation.

6.9.5 Validation-oriented choice

There is no universal proportion between width and depth. fair comparison shall control, where possible:

  1. total number of parameters or computational cost;
  2. training procedure and budget of seasons;
  3. regularisation and transformation of data;
  4. metric in validation, latency and memory usage;
  5. variability between random initializations.

A smaller architecture that reaches the required metric with training stable is usually preferable. understanding possibilities and limitations, but the final choice combines theory with experimental evidence.

def contar_parametros_densos(larguras):
    return sum(
        saida * (entrada + 1)
        for entrada, saida in zip(larguras[:-1], larguras[1:])
    )


print(contar_parametros_densos([20, 64, 10]))
print(contar_parametros_densos([20, 24, 24, 10]))

Comparing only the amount of layers would be misleading: the code allows also check the parameter budget of the candidate architectures.

Exercises

  1. Sketch T(x)T(x) and T(T(x))T(T(x)) in the [0,1][0,1] range.
  2. Explain why composition may be more economical than enumerating directly all parts of a function.
  3. Calculate the parameters of the two architectures of the Python example.
  4. Give an example of task with naturally compositional structure.
  5. Why a result of theoretical separation does not guarantee that a network will deeper have better accuracy on any real basis?

6.10 Gradient descent

Training a network means choosing your parameters θ={W(ℓ),b(ℓ)}ℓ=1L\theta=\{W^{(\ell)},b^{(\ell)}\}_{\ell=1}^L to reduce a function As deep networks make up many nonlinear operations, this function rarely has a closed solution. Iteratives based on derivatives.

6.10.1 Objective function

For a sample D={(xi,yi)}i=1ND=\{(x_i,y_i)\}_{i=1}^N, we defined

ED(θ)=1N∑i=1Nℓ(hθ(xi),yi)+λR(θ),(6.8) E_D(\theta) =\frac1N\sum_{i=1}^N \ell(h_\theta(x_i),y_i)+\lambda R(\theta), \tag{6.8}

where ℓ\ell is the loss for example, RR is an optional term of regularization and λ≥0\lambda\geq0 control your strength. Some examples are:

  • squared error in regression;
  • binary cross-entropy for two results;
  • categorical cross-entropy for exclusive classes.

The choice must combine the meaning of the output, the probabilistic model and numerical stability. Accuracy, although useful for evaluation, is discontinuous and does not usually serve directly as a gradient objective.

6.10.2 Direction of steepest descent

For a small disturbance Δθ\Delta\theta, the first approach order is

ED(θ+Δθ)≈ED(θ)+∇ED(θ)TΔθ. E_D(\theta+\Delta\theta) \approx E_D(\theta) +\nabla E_D(\theta)^{\mathsf T}\Delta\theta.

Between unitary directions, the gradient points to the greatest growth local and its opposite points to the greatest decrease. ** decrease ** gradient update

θt+1=θt−ηt∇ED(θt),(6.9) \theta_{t+1} =\theta_t-\eta_t\nabla E_D(\theta_t), \tag{6.9}

with learning rate ηt>0\eta_t>0. The name “maximum slope” describes the negative direction of gradient, but “descent gradient” is terminology more common.

The negative direction of the gradient locally reduces the objective function; different rates produce steps of different sizes.

Figure 6.6. The negative direction of the gradient locally reduces the objective function; different rates produce steps of different sizes.

We did not normalize the gradient in the default update. Local slope information. Standard gradient methods they exist, but they constitute another algorithm and change the interpretation of the ηt\eta_t.

6.10.3 Full batch, stochastic and mini-batch

Calculating (6.8) on all examples provides the gradient of complete batch. For large databases, we divide the data into mini-batches BtB_t and use

gt=1∣Bt∣∑i∈Bt∇θℓ(hθ(xi),yi)+λ∇θR(θ). g_t =\frac1{|B_t|}\sum_{i\in B_t} \nabla_\theta\ell(h_\theta(x_i),y_i) +\lambda\nabla_\theta R(\theta).

The update becomes θt+1=θt−ηtgt\theta_{t+1}=\theta_t-\eta_tg_t. A batch with an example characterizes stochastic descent; intermediate batches they take advantage of vectorization and introduce noise that can help the exploration.

A season is a passage through the training examples. A iteration is an update. With NN examples and lots of size BB, a time contains approximately ⌈N/B⌉\lceil N/B\rceil iterations.

6.10.4 Learning rate

If η\eta is too small, the training progresses slowly. very large, the loss can oscillate, diverge or produce non- finite. There is no value like 0,10{,}1 that is suitable for all nets.

We can use constant rate, programmed decay or based adaptation in the gradient history. * Momentum* accumulates an average of the directions; Adam adapts scales by parameter. These methods facilitate training, but they still require monitoring and do not guarantee the global minimum.

6.10.5 Initialization and symmetry breaking

Initializing all hidden weights in zero makes neurons of the same layer They remain identical and waste the Available width. We use random values with related variance the number of entries, as initializations of Xavier or He, depending on the activation.

Vieces can often start at zero because random weights already The random seed should be recorded to make it reproducible experiments.

6.10.6 Stopping criteria

Gradient exactly zero is not a realistic criterion and can indicate minimum, maximum, seal point or saturation. In practice, we combine:

  • maximum time or time limit;
  • loss and metrics in training and validation;
  • no improvement in validation by a number of times;
  • gradient standard or variation of parameters;
  • NaN or infinite values check.

early stop saves parameters with better validation, no The test set remains. reserved until the end.

6.10.7 Optimization minimum loop

def train(model, batch, optimizer, epochs):
    for epoch in range:
        template.mode_training()

        for X, y in batches:
            optimizer.zero_gradients()
            logits = model(X)
            loss = function_loss(logits, y)
            loss.retropropagate()
            optimizer.update()

        _Evalidation(model)

Zero gradients is explicit because many libraries accumulate them by default. Backpropagation calculates derivatives; optimizer decides how Turn them into updates.

Minimization does not always mean gradient smaller

In mini-batches, the loss of the next lot may increase even when the global trend improves. In addition, the gradient norm can grow temporarily. Smoothed curves and validation metrics are more information that a single iteration.

Exercises

  1. Derive (6.9) from the first approach order and choice Δθ=−η∇ED\Delta\theta=-\eta\nabla E_D.
  2. How many updates are there per season for N=10 000N=10\,000 and B=128B=128?
  3. Explain why all equal hidden weights preserve symmetry.
  4. Describe observable signs of an excessive learning rate.
  5. Differentiate training loss, validation loss and test metric.

6.11 Vectorization

Vectorization consists in expressing several scalar operations as a operation on vectors or matrices. In addition to making notation compact, it allows libraries to use highly optimized routines and run many parallel multiplications in CPU, GPU or other accelerators.

6.11.1 Axis conventions

We will adopt a single rule:

  • each line contains an example;
  • each column contains an attribute or a unit;
  • the weight matrix stores one neuron per line.

So for a layer that receives dd values and produces mm activations,

W∈Rm×d,b∈Rm. W\in\mathbb R^{m\times d}, \qquad b\in\mathbb R^m.

For a single vector-column x∈Rdx\in\mathbb R^d, we use

z=Wx+b∈Rm. z=Wx+b\in\mathbb R^m.

In the batch code, the examples occupy lines, and the transposition of WW Come on, come on.

6.11.2 A layer applied to a batch

If X∈RB×dX\in\mathbb R^{B\times d} represents a mini-batch with BB examples, then

Z=XWT+1BbT∈RB×m,(6.10) Z=XW^{\mathsf T}+\mathbf1_Bb^{\mathsf T} \in\mathbb R^{B\times m}, \tag{6.10}

e

A=g(Z)∈RB×m. A=g(Z)\in\mathbb R^{B\times m}.

The ZijZ_{ij} input is the preactivation of the jj unit for the example ii. Activation is applied element to element, except vector functions such as softmax, which operate along the axis of the classes.

Formats of a dense layer vectorized with examples organized in the lines.

Figure 6.7. Formats of a dense layer vectorized with examples organized in the lines.

6.11.3 Broadcasting of bias

We don’t need to materially build the matrix. 1BbT\mathbf1_Bb^{\mathsf T}. By adding a (m,) format vector to a matrix (B, m), NumPy and similar libraries logically repeat the vector in each line. This mechanism is called * broadcasting*.

Broadcasting saves memory, but can hide errors. A bias with (B, 1) format can also be added to Z, but would add a value for example, not a value per unit. Formats would be compatible and the meaning would be wrong.

6.11.4 Multiple Layers

For a n0→n1→⋯→nLn_0\to n_1\to\cdots\to n_L architecture and a batch with BB examples,

A(0)=X∈RB×n0, A^{(0)}=X\in\mathbb R^{B\times n_0}, Z(ℓ)=A(ℓ−1)(W(ℓ))T+b(ℓ),A(ℓ)=gℓ(Z(ℓ)). Z^{(\ell)} =A^{(\ell-1)}(W^{(\ell)})^{\mathsf T}+b^{(\ell)}, \qquad A^{(\ell)}=g_\ell(Z^{(\ell)}).

In each layer, only the second dimension changes: from nℓ−1n_{\ell-1} to nℓn_\ell. The BB dimension of the batch is preserved.

import numpy as np


def camada_densa(A, W, b, ativacao):
    A = np.asarray(A)
    W = np.asarray(W)
    b = np.asarray(b)

    if A.ndim != 2 or W.ndim != 2 or b.ndim != 1:
        raise ValueError("A e W devem ser matrizes; b deve ser vetor")
    if A.shape[1] != W.shape[1] or W.shape[0] != b.shape[0]:
        raise ValueError("dimensões incompatíveis na camada densa")

    Z = A @ W.T + b
    return ativacao(Z), Z

Checks make the convention explicit. unit tests with small batches help to confirm values, no format only.

6.11.5 Why is it faster?

A Python loop that calculates each neuron and each example separately The matrix multiplication delegates the work to compiled implementations, uses vector instructions, memory in blocks and parallelism. The mathematical amount of multiplications does not It disappears, but execution uses hardware better.

Vectoring also has limits. A very large batch may exceed the memory, and storing all activations is expensive during training. Mini-batches balance parallelism, memory and update frequency the parameters.

6.11.6 Vectorization of loss

For regression with kk outputs, if Y^,Y∈RB×k\widehat Y,Y\in\mathbb R^{B\times k}, the average squared error can be written as

EB=1Bk∥Y^−Y∥F2, E_B=\frac1{Bk}\lVert\widehat Y-Y\rVert_F^2,

where ∥⋅∥F\lVert\cdot\rVert_F is Frobenius’ norm. the reduction uses sum or average and on which axes; this changes the scale of the gradient and, consequently, the appropriate learning rate.

Exercises

  1. Determine ZZ format for B=64B=64, d=100d=100 and m=32m=32.
  2. Write (6.10) using examples like columns and compare where the transposition appears.
  3. Explain the semantic error of adding a (B, 1) vector to Z.
  4. Why larger lots do not reduce the mathematical amount of multiplications, although they may reduce execution time?
  5. Compare the gradient of an added loss with that of the same average loss.

6.12 Reverse automatic differentiation by chain rule

To update millions of parameters, we need to calculate many derived from a single output scale: loss. ** reverse mode of ** automatic differentiation is suitable for this structure. It executes the graph for front, stores intermediate values and runs operations in order reverse, applying the chain rule.

Self-differentiation is neither symbolic differentiation nor approximation by finite differences. It applies exact derivation rules to operations elementals carried out by the program, subject only to rounding Numeric.

6.12.1 A simple computational graph

Consider

z=wx+b,a=g(z),E=ℓ(a,y). z=wx+b,\qquad a=g(z),\qquad E=\ell(a,y).

The forward pass calculates zz, aa and EE. In reverse,

∂E∂z=∂E∂a∂a∂z, \frac{\partial E}{\partial z} =\frac{\partial E}{\partial a} \frac{\partial a}{\partial z},

And then

∂E∂w=∂E∂z∂z∂w,∂E∂b=∂E∂z∂z∂b. \frac{\partial E}{\partial w} =\frac{\partial E}{\partial z} \frac{\partial z}{\partial w}, \qquad \frac{\partial E}{\partial b} =\frac{\partial E}{\partial z} \frac{\partial z}{\partial b}.

Like ∂z/∂w=x\partial z/\partial w=x and ∂z/∂b=1\partial z/\partial b=1, we get

∂E∂w=δx,∂E∂b=δ,δ:=∂E∂z. \frac{\partial E}{\partial w}=\delta x, \qquad \frac{\partial E}{\partial b}=\delta, \qquad \delta:=\frac{\partial E}{\partial z}.

In reverse passage, the derivative of loss flows through operations in the opposite order and each node uses values saved in direct passage.

Figure 6.8. In reverse passage, the derivative of loss flows through operations in the opposite order and each node uses values saved in direct passage.

6.12.2 Vector-Jacobian products

A layer can produce a vector. If u=f(v)u=f(v) and the scalar loss is E(u)E(u), the string rule can be written as

∇vE=Jf(v)T∇uE, \nabla_v E =J_f(v)^{\mathsf T}\nabla_u E,

where JfJ_f is the Jacobian of ff. Reverse mode does not need to store All this Jacobian: directly calculates the product Jf(v)T∇uEJ_f(v)^{\mathsf T}\nabla_u E, called vector product–Jacobian.

This is crucial in networks. To explicitly form each Jacobian would be expensive, while propagating a derivative vector has cost of the same order of Pass forward.

6.12.3 Derivation to a dense layer

For an example, the ℓ\ell layer calculates

z(ℓ)=W(ℓ)a(ℓ−1)+b(ℓ),a(ℓ)=gℓ(z(ℓ)). z^{(\ell)} =W^{(\ell)}a^{(\ell-1)}+b^{(\ell)}, \qquad a^{(\ell)}=g_\ell(z^{(\ell)}).

Set the retrograde signal

δ(ℓ):=∂E∂z(ℓ).(6.11) \delta^{(\ell)} :=\frac{\partial E}{\partial z^{(\ell)}}. \tag{6.11}

Using external products, the gradients of the parameters are

∂E∂W(ℓ)=δ(ℓ)(a(ℓ−1))T,(6.12) \frac{\partial E}{\partial W^{(\ell)}} =\delta^{(\ell)}(a^{(\ell-1)})^{\mathsf T}, \tag{6.12} ∂E∂b(ℓ)=δ(ℓ).(6.13) \frac{\partial E}{\partial b^{(\ell)}} =\delta^{(\ell)}. \tag{6.13}

The formats confirm the expression:

(nℓ×1)(1×nℓ−1)=nℓ×nℓ−1. (n_\ell\times1)(1\times n_{\ell-1}) =n_\ell\times n_{\ell-1}.

6.12.4 Last layer

The shape of δ(L)\delta^{(L)} depends on activation and loss.

δ(L)=∇a(L)E⊙gL′(z(L)), \delta^{(L)} =\nabla_{a^{(L)}}E \odot g_L'(z^{(L)}),

where ⊙\odot denotes product element by element.

For squared error E=12∥a(L)−y∥2E=\frac12\lVert a^{(L)}-y\rVert^2,

δ(L)=(a(L)−y)⊙gL′(z(L)). \delta^{(L)} =(a^{(L)}-y)\odot g_L'(z^{(L)}).

For softmax combined with categorical cross-entropy, derivation simplifies for

δ(L)=p−y, \delta^{(L)}=p-y,

where p=softmax⁡(z(L))p=\operatorname{softmax}(z^{(L)}) and yy are the target vector. This formula presupposes the specific combination of activation and loss; no It must be reused indiscriminately.

6.12.5 Hidden layers

The preactivation of the next layer depends on a(ℓ)a^{(\ell)}:

z(ℓ+1)=W(ℓ+1)a(ℓ)+b(ℓ+1). z^{(\ell+1)} =W^{(\ell+1)}a^{(\ell)}+b^{(\ell+1)}.

By applying the chain rule,

δ(ℓ)=((W(ℓ+1))Tδ(ℓ+1))⊙gℓ′(z(ℓ)).(6.14) \delta^{(\ell)} =\left((W^{(\ell+1)})^{\mathsf T} \delta^{(\ell+1)}\right) \odot g_\ell'(z^{(\ell)}). \tag{6.14}

The transposed matrix redistributes for each unit of the current layer the contributions from all the units of the next layer. product by gℓ′g_\ell' crosses local activation.

Recurrence begins in δ(L)\delta^{(L)} and continues to the first layer. After getting each δ(ℓ)\delta^{(\ell)}, we use (6.12) e (6.13).

6.12.6 Vectorized form for mini-batches

With examples on the lines, be A(ℓ−1)∈RB×nℓ−1A^{(\ell-1)}\in\mathbb R^{B\times n_{\ell-1}} e Δ(ℓ)∈RB×nℓ\Delta^{(\ell)}\in\mathbb R^{B\times n_\ell}. If loss is average the lot,

∂E∂W(ℓ)=1B(Δ(ℓ))TA(ℓ−1), \frac{\partial E}{\partial W^{(\ell)}} =\frac1B(\Delta^{(\ell)})^{\mathsf T}A^{(\ell-1)}, ∂E∂b(ℓ)=1B∑i=1BΔi,:(ℓ), \frac{\partial E}{\partial b^{(\ell)}} =\frac1B\sum_{i=1}^B\Delta^{(\ell)}_{i,:},

and the spread to the anterior layer is

Δ(ℓ−1)=(Δ(ℓ)W(ℓ))⊙gℓ−1′(Z(ℓ−1)). \Delta^{(\ell-1)} =\left(\Delta^{(\ell)}W^{(\ell)}\right) \odot g_{\ell-1}'(Z^{(\ell-1)}).

The axis of the sum of bias is the examples. Add to the units It would produce a vector with wrong shape and meaning.

6.12.7 Branches in the graph

When a value feeds two paths, loss depends on it for both. The total derivative is the sum of contributions. uu influences EE through r1(u)r_1(u) and r2(u)r_2(u), then

∂E∂u=∂E∂u∣r1+∂E∂u∣r2. \frac{\partial E}{\partial u} =\left.\frac{\partial E}{\partial u}\right|_{r_1} +\left.\frac{\partial E}{\partial u}\right|_{r_2}.

This explains why libraries accumulate gradients and why connections residuals add up paths in reverse passage.

6.12.8 Check for finite differences

Central differences offer an implementation check:

∂E∂θj≈E(θj+h)−E(θj−h)2h. \frac{\partial E}{\partial\theta_j} \approx \frac{E(\theta_j+h)-E(\theta_j-h)}{2h}.
def derivative_numerica(loss, theta, index, h=1e-5):
    Original = theta[index]

    theta[index] = original + h
    plus = loss()

    theta[index] = original - h
    minus = loss()

    theta[index] = original
    return (more - less) / (2 *h)

This method requires two evaluations per parameter, suffers with choice of hh and rounding, and it is not suitable for training. It serves as test on small nets, using double precision and avoiding no points Distinguished from the ReLU.

Accumulated gradient is not update

The retropropagation calculates derivatives. It does not alter parameters by itself. The optimizer uses these derivatives later. Mix the two roles difficult to test and reuse the implementation.

Exercises

  1. Derive z=wx+bz=wx+b gradients without omitting the steps of the rule of the Jail.
  2. Check (6.14) formats for a layer nℓ−1→nℓ→nℓ+1n_{\ell-1}\to n_\ell\to n_{\ell+1}.
  3. Explain why two-way gradients should be added.
  4. Derive δ(L)\delta^{(L)} for identity output and squared error.
  5. Compare cost and purpose of reverse and reverse automatic differentiation finite differences.

6.13 Algorithm Backpropagation

Retropropagation, or backpropagation, is the specialized application of reverse mode of automatic differentiation to a neural network. loss gradients relative to all parameters. gradient, Adam or other optimizer uses these gradients in one step later.

6.13.1 Overview

For a mini-batch, a training iteration has four phases:

  1. Direct spread: calculate Z(ℓ)Z^{(\ell)} and A(ℓ)A^{(\ell)} from first to the last layer and store the required values.
  2. Loss: calculate EE from output and targets.
  3. Reverse spread: start Δ(L)\Delta^{(L)} on output and go through LL layers up to 11, calculating gradients.
  4. Update: apply the optimizer to the parameters.

For simple gradient descent, the correct update is

Wt+1(ℓ)=Wt(ℓ)−ηt∂E∂Wt(ℓ), W^{(\ell)}_{t+1} =W^{(\ell)}_t -\eta_t\frac{\partial E}{\partial W^{(\ell)}_t}, bt+1(ℓ)=bt(ℓ)−ηt∂E∂bt(ℓ). b^{(\ell)}_{t+1} =b^{(\ell)}_t -\eta_t\frac{\partial E}{\partial b^{(\ell)}_t}.

The old parameter, at tt, appears on the right side. Use t+1t+1 index on both sides would make the rule circular.

6.13.2 Vectored algorithm

With examples on the lines and an average loss, reverse propagation performs, for ℓ=L,L−1,…,1\ell=L,L-1,\ldots,1,

dW(ℓ)=1B(Δ(ℓ))TA(ℓ−1), dW^{(\ell)} =\frac1B(\Delta^{(\ell)})^{\mathsf T}A^{(\ell-1)}, db(ℓ)=1B∑i=1BΔi,:(ℓ), db^{(\ell)} =\frac1B\sum_{i=1}^{B}\Delta^{(\ell)}_{i,:},

and, if ℓ>1\ell>1,

Δ(ℓ−1)=(Δ(ℓ)W(ℓ))⊙gℓ−1′(Z(ℓ−1)). \Delta^{(\ell-1)} =\left(\Delta^{(\ell)}W^{(\ell)}\right) \odot g'_{\ell-1}(Z^{(\ell-1)}).

The 1/B1/B factor should appear only once. We can incorporate it into the initial delta or the gradients of the parameters, but doubling it reduces the gradient by B2B^2 and omit it makes your scale grow with the batch.

6.13.3 Full example with two layers

Consider ReLU in hidden layer, identity output and

E=12B∑i=1B∥y^i−yi∥2. E=\frac1{2B}\sum_{i=1}^{B} \lVert\widehat y_i-y_i\rVert^2.
import numpy as np


def forward(X, W1, b1, W2, b2):
    Z1 = X @ W1.T + b1
    A1 = np.maximum(Z1, 0.0)
    Y_hat = A1 @ W2.T + b2
    cache = (X, Z1, A1)
    return Y_hat, cache


def backward(Y_hat, Y, cache, W2):
    X, Z1, A1 = cache
    B = X.shape[0]

    # Output Delta; 1 / B average enters here.
    D2 = (Y_hat - Y) / B
    dW2 = D2.T @ A1
    db2 = D2.sum(axis=0)

    D1 = (D2 @ W2) * (Z1 > 0)
    dW1 = D1.T @ X
    db1 = D1.sum(axis=0)
    return dW1, db1, dW2, db2


def atualizar(parametros, gradientes, taxa):
    for nome, gradiente in zip(parametros, gradientes):
        nome -= taxa * gradiente

If Y_hat and Y have (B, k) format, then D2 will also have (B, k). The function assumes that all matrices are point floating and that the update in place is desired.

6.13.4 Cache and memory

To calculate gℓ′(Z(ℓ))g'_{\ell}(Z^{(\ell)}) and products with A(ℓ−1)A^{(\ell-1)}, we store direct pass activations. On very networks deep, this storage dominates the training memory.

An alternative is checkpointing: save only a few activations and recalculate others during reverse passage. This changes time of In the inference, we don’t need the reverse graph and We can release middlemen earlier.

6.13.5 Secure Update Order

All gradients should be calculated with the same values as the Direct pass parameters. Update W(L)W^{(L)} before calculating Δ(L−1)\Delta^{(L-1)} would make recurrence use a new weight, inconsistent with the graph that produced the loss. First we calculate all gradients; only after the optimizer changes the parameters.

A proper implementation shall be progressively verified:

  1. test each direct layer with known small values;
  2. check activation and gradient formats;
  3. compare gradients to finite differences in a tiny network;
  4. to confirm that a sufficiently small step reduces the loss of it lot;
  5. try to deliberately overset a set with few examples;
  6. check non-finite values and gradient standards during training.

Overfit a small batch does not prove generalization, but it is a test useful chaining between model, loss, retropropagation and update.

Retropropagation reuses calculations

Calculating each partial derivative of zero would repeat a large part of the graph. The efficiency of the algorithm comes from storing intermediate derivatives and reuse them for all previous parameters.

Exercises

  1. Check the formats of D1, dW1, db1, D2, dW2 and db2.
  2. Derive the output delta used in the example from the squared error.
  3. Explain why weights should only be updated after all gradients have been calculated.
  4. What changes in formulas if loss adds the examples instead of using the medium?
  5. Describe how checkpointing swaps memory for computing.

6.13.7 Summary of the chapter

Neural networks make up related transformations and nonlinear activations for Learn representations. Width and depth offer shapes additional expressiveness, but do not guarantee optimization or Training combines vectorized operations, a loss. Distinguished, reverse automatic differentiation and an optimiser. formats, scales and separation between these steps makes the implementation more correct and easier to debug.

6.14 Multiple choice exercises

In each question, check the only correct alternative. Use the formats of matrices to check the responses involving vectorization.

  1. If all activations of a dense network are linear functions, the composition of several layers shall be equivalent to:

    1. a single transformation in order.
    2. a decision tree.
    3. an RBF core.
    4. a function necessarily periodic.
  2. The ReLU function is defined by:

    1. max⁡(0,z)\max(0,z).
    2. 1/(1+e−z)1/(1+e^{-z}).
    3. exp⁡(z)/∑jexp⁡(zj)\exp(z)/\sum_j\exp(z_j).
    4. z2z^2.
  3. For multiclass classification with mutually exclusive classes, a usual output activation is:

    1. ReLU applied to a single number.
    2. softmax.
    3. absolute value.
    4. identity followed by compulsory rounding.
  4. A dense layer with 5 inputs and 3 neurons has as many parameters, including a neuron bias?

  5. The universal approximation theorem states, under its conditions, that a network:

    1. can approximate functions of a target class with arbitrary accuracy.
    2. always finds the best weights automatically.
    3. perfectly generalizes with an example.
    4. requires exactly two hidden units.
  6. In a ReLU network, increasing depth can be especially useful for:

    1. represent hierarchical compositions.
    2. eliminate all hyperparameters.
    3. dispense nonlinear activations.
    4. ensure convexity of weight loss.
  7. At gradient descent, the default update is:

    1. θ←θ+η∇J(θ)\theta\leftarrow\theta+\eta\nabla J(\theta).
    2. θ←θ−η∇J(θ)\theta\leftarrow\theta-\eta\nabla J(\theta).
    3. θ←∇J(θ)/0\theta\leftarrow\nabla J(\theta)/0.
    4. θ←θ2\theta\leftarrow\theta^2.
  8. For a lot X∈RN×dX\in\mathbb{R}^{N\times d} and weights W∈Rd×mW\in\mathbb{R}^{d\times m}, the Z=XW+bZ=XW+b pre-activation output has format:

    1. d×dd\times d.
    2. m×Nm\times N mandatory.
    3. N×mN\times m.
    4. N×dN\times d in all cases.
  9. In reverse automatic differentiation, vector–Jacobian products allow:

    1. propagate output derivatives to the previous nodes of the graph.
    2. delete the graph before calculating the loss.
    3. replace all data with scalars.
    4. avoid the rule of jail.
  10. During backpropagation, the weights shall be updated:

    1. as soon as each intermediate derivative appears, even if old weights still They’re necessary.
    2. only after calculating the gradients necessary for iteration.
    3. before forward propagation.
    4. only when the loss is exactly zero.

Answer key with explanations

  1. a. The composition of related transformations remains in tune; without not linearity, depth does not expand this functional class.
  2. a. ReLU preserves positive inputs and zeros negative inputs.
  3. b. Softmax produces non-negative probabilities whose sum is one.
  4. c. There are 5×3=155\times3=15 weights and 3 biases, totaling 18 parameters.
  5. a. The result deals with existence and approximation, does not guarantee training, efficiency or generalization.
  6. a. Successive layers can reuse and compose level characteristics previous ones.
  7. b. The negative signal points locally in the direction of function reduction objective.
  8. c. The product (N×d)(d×m)(N\times d)(d\times m) results in N×mN\times m, and bias is spread by line.
  9. a. The reverse mode accumulates sensitivities by means of the string rule without To form completely unnecessary Jacobian.
  10. b. Update before the end can mix new and old values and produce inconsistent gradients.