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
and we chose a parameterized hypothesis . vector gathers all the weights and biases of the network.
measures the quality of an individual prediction.
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 , calculates a match and apply a activation function:
Here, contains the weights, is bias, is the preactivation and is the produced activation. shifting the threshold; without it, many borders would be forced to pass by origin.
A layer with neurons calculates all these operations in parallel:
where , and is applied component to component. Each line of corresponds to the weights of one neuron.
A feedforward network, or without feedback, chain layers without cycles. For two parametrizated layers,

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:
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:
- forward propagation: calculate activations and prediction;
- loss: compare prediction to target;
- retropropagation: calculate derived by the chain rule;
- 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 components and the layer has neurons, W is shaped (m, d), while b, z and a have components. Dimension errors are among the most common problems in the first implementations.
Exercises
- Determine and formats for a layer that receives 8 features and produces 32 activations.
- How many training parameters does this layer have?
- Demonstrate that the composition of three related transformations is still I’m in the mood.
- Differentiate parameter, hyperparameter, preactivation and activation.
- Explain why a low loss in training does not guarantee good generalization.
6.4 Activation Functions
An activation function transforms the preactivation 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.

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
Its derivative, except in , is
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:
Its derivative is on the positive side and on the negative side, except for the convention chosen at zero. Thus, a neuron receives some gradient even when its preactivation is negative. are common, but is a hyperparameter and not a universal constant.
6.4.3 Sigmoid Activation Function
The logistic sigmoid is
Its derivative can be calculated from the output itself:
The maximum value of the derivative is , reached in . For 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 . In modern hidden layers, ReLU and variants usually to be preferred.
A direct implementation of can overflow to a lot Negative. Numerically stable functions treat cases separately e .
6.4.4 Hyperbolic Tangent Activation Function (tanh)
The hyperbolic tangent is
and its derivative is
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 mutually exclusive classes, the layer of output produces * logs* . Softmax converts them into Probabilities:
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 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
| Task | Typical output | Activation | Common Loss |
|---|---|---|---|
| Royal Regression | 1 or more values | identity | squared error |
| Binary classification | 1 logit | sigmoid | binary cross-entropy |
| Exclusive multiclass | logs | softmax | categorical cross-entropy |
| Multi-label | logs | sigmoids | binary 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
- Calculate ReLU, sigmoid and tanh to .
- Show that .
- Prove that softmax is invariant to the sum of a constant in all logits.
- Explain why softmax is not suitable for an image that can contain both “car” and “pedestrian”.
- 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 .
- 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 input produces
Different activation and loss choices recover already known models:
| Template | Output activation | Prediction | Typical loss |
|---|---|---|---|
| Linear regression | identity | real value | squared error |
| Perceptron | signal | class | classification error |
| Logistic regression | sigmoid | binary probability | cross-entropy |
| Softmax Return | softmax over logs | Probabilities of classes | categorical cross-entropy |
All these models produce linear decision boundaries in the space of Input. Activation changes output and appropriate loss, but level remains a hyperplane. solves, for example, the XOR without a prior transformation of features.
6.5.2 A hidden layer
Consider hidden neurons, an input with features and an scalar output. Hidden layer calculates
The output combines these new features:
In matrix notation,
with
Each hidden neuron learns a feature. output learns how to combine them. Unlike a transformation fixed polynomial, both directions and displacements they are adjusted by the data.
6.5.3 Parameter count
The matrix contains weights, the vector contains biases, the output contains weights and a bias. (6.2) has
Training parameters. For outputs, we use and , totaling
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 It’s an example.
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 and 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
- Count the parameters of a network with , and .
- Check the formats of all matrices in the batch calculation.
- Explain why to change the order of two hidden neurons and exchange the corresponding columns does not change the network function.
- Why applying the signal function inside the hidden layer makes it difficult to Gradient training?
- 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:
Each value of defines a class with finite width. The theorem studies the union of these classes when we allow to be as large as It’s necessary.
6.6.1 Statement
Be compact and be a continuous function. (6.3) shape are dense in , with the standard of the supreme, if and only if is not a polynomial.
In concrete terms, for every continuous function and all , there is a finite width and there are parameters such that
For a vector output , we can approach each component and gather them into an output layer with 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 , not that a single fixed network represents all functions. The width and parameters depend on , of and tolerance .
The hypothesis of compactness also matters. In , 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 is a grade polynomial, each term has a maximum degree ; sums Finitas continue to grade at most . 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,
is linear by parts. Before , the corresponding term is zero; After , it changes the slope in . Therefore, placing 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 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 ;
- 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
- Explain the difference between uniform error in and error only in Training points.
- Show a finite combination of polynomial activations of grade remains a polynomial of grade at most .
- Represent exactly with two ReLU units.
- Build a tilt function before zero and after zero using the previous code.
- 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 layers parameterized. and for ,
If the layer has units, then
The complete hypothesis is
where . The layer appears to the right because it is applied first. Invert this order is a frequent mistake when writing compositions.

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 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 introduce nonlinearity. They don’t need to be equal in all layers, though architectures homogeneous are common. The final activation 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 for has
parameters: a matrix of weights and a bias per unit. whole has
Training parameters. For example, architecture contains
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, . Propagation uses
where the bias is transmitted to the lines by * broadcasting*. and have 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
- List the formats of all tensors in a network for a lot with 32 examples.
- Calculate the number of parameters of this network using (6.6).
- Show algebraically that two layers without nonlinear activation can be replaced by a single layer in order.
- Explain why the input layer does not add parameters.
- 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 norm
Be an integrable function in the sense of Lebesgue, that is,
For all , there is a feedforward network fully connected with ReLU activation, maximum width not exceeding and finite depth such that the function represented by the network satisfies
Depth is not previously fixed: it can increase when the target function becomes more complex or when decreases. Therefore, the result does not state that a unique architecture of width 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 , then
The limit depends on the input dimension , 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:
| Aspect | Flat net | Limited-width network |
|---|---|---|
| Depth | a hidden layer | can grow |
| Width | can grow | not more than |
| Functions in the statement | continuous in compact | Integrable in |
| Standard | uniform | integral |
| Type of guarantee | existence | existence |
Standards express different requirements. major deviation:
The error accumulates the area — or volume — of the difference. approach may have very large error in a small measurement region and still show reduced 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.
- Truncate the tails. As , we chose a large cube outside of which the integral is small.
- Approach by simple blocks. Inside the cube, simple functions, constants in small regions, approach in .
- Build one block at a time. Deep ReLU Layers form approximations of regions and their values, reusing few Auxiliary coordinates.
- 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.

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 , 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 , 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 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 .
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
- Differentiate maximum width, depth and total number of parameters.
- Explain why a function with high error in a very long interval narrow may have small error.
- Show that the indicator function of a range cannot be approximate evenly by continuous functions with error smaller than in a domain that contains its ends.
- For , what width is enough provided by the utterance? Does the result determine the depth?
- 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 :
It rises from to and then descends to . produces more oscillations; repeating the composition increases your number without needing to rewrite each snippet independently.

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
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:
- total number of parameters or computational cost;
- training procedure and budget of seasons;
- regularisation and transformation of data;
- metric in validation, latency and memory usage;
- 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
- Sketch and in the range.
- Explain why composition may be more economical than enumerating directly all parts of a function.
- Calculate the parameters of the two architectures of the Python example.
- Give an example of task with naturally compositional structure.
- 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 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 , we defined
where is the loss for example, is an optional term of regularization and 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 , the first approach order is
Between unitary directions, the gradient points to the greatest growth local and its opposite points to the greatest decrease. ** decrease ** gradient update
with learning rate . The name “maximum slope” describes the negative direction of gradient, but “descent gradient” is terminology more common.

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 .
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 and use
The update becomes . 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 examples and lots of size , a time contains approximately iterations.
6.10.4 Learning rate
If is too small, the training progresses slowly. very large, the loss can oscillate, diverge or produce non- finite. There is no value like 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
- Derive (6.9) from the first approach order and choice .
- How many updates are there per season for and ?
- Explain why all equal hidden weights preserve symmetry.
- Describe observable signs of an excessive learning rate.
- 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 values and produces activations,
For a single vector-column , we use
In the batch code, the examples occupy lines, and the transposition of Come on, come on.
6.11.2 A layer applied to a batch
If represents a mini-batch with examples, then
e
The input is the preactivation of the unit for the example . Activation is applied element to element, except vector functions such as softmax, which operate along the axis of the classes.

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. . 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 architecture and a batch with examples,
In each layer, only the second dimension changes: from to . The 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 outputs, if , the average squared error can be written as
where 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
- Determine format for , and .
- Write (6.10) using examples like columns and compare where the transposition appears.
- Explain the semantic error of adding a
(B, 1)vector toZ. - Why larger lots do not reduce the mathematical amount of multiplications, although they may reduce execution time?
- 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
The forward pass calculates , and . In reverse,
And then
Like and , we get

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 and the scalar loss is , the string rule can be written as
where is the Jacobian of . Reverse mode does not need to store All this Jacobian: directly calculates the product , 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 layer calculates
Set the retrograde signal
Using external products, the gradients of the parameters are
The formats confirm the expression:
6.12.4 Last layer
The shape of depends on activation and loss.
where denotes product element by element.
For squared error ,
For softmax combined with categorical cross-entropy, derivation simplifies for
where and 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 :
By applying the chain rule,
The transposed matrix redistributes for each unit of the current layer the contributions from all the units of the next layer. product by crosses local activation.
Recurrence begins in and continues to the first layer. After getting each , we use (6.12) e (6.13).
6.12.6 Vectorized form for mini-batches
With examples on the lines, be e . If loss is average the lot,
and the spread to the anterior layer is
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. influences through and , then
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:
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 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
- Derive gradients without omitting the steps of the rule of the Jail.
- Check (6.14) formats for a layer .
- Explain why two-way gradients should be added.
- Derive for identity output and squared error.
- 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:
- Direct spread: calculate and from first to the last layer and store the required values.
- Loss: calculate from output and targets.
- Reverse spread: start on output and go through layers up to , calculating gradients.
- Update: apply the optimizer to the parameters.
For simple gradient descent, the correct update is
The old parameter, at , appears on the right side. Use 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 ,
and, if ,
The 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 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
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 and products with , 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 before calculating 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.
6.13.6 Recommended tests
A proper implementation shall be progressively verified:
- test each direct layer with known small values;
- check activation and gradient formats;
- compare gradients to finite differences in a tiny network;
- to confirm that a sufficiently small step reduces the loss of it lot;
- try to deliberately overset a set with few examples;
- 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
- Check the formats of
D1,dW1,db1,D2,dW2anddb2. - Derive the output delta used in the example from the squared error.
- Explain why weights should only be updated after all gradients have been calculated.
- What changes in formulas if loss adds the examples instead of using the medium?
- 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.
-
If all activations of a dense network are linear functions, the composition of several layers shall be equivalent to:
- a single transformation in order.
- a decision tree.
- an RBF core.
- a function necessarily periodic.
-
The ReLU function is defined by:
- .
- .
- .
- .
-
For multiclass classification with mutually exclusive classes, a usual output activation is:
- ReLU applied to a single number.
- softmax.
- absolute value.
- identity followed by compulsory rounding.
-
A dense layer with 5 inputs and 3 neurons has as many parameters, including a neuron bias?
-
-
The universal approximation theorem states, under its conditions, that a network:
- can approximate functions of a target class with arbitrary accuracy.
- always finds the best weights automatically.
- perfectly generalizes with an example.
- requires exactly two hidden units.
-
In a ReLU network, increasing depth can be especially useful for:
- represent hierarchical compositions.
- eliminate all hyperparameters.
- dispense nonlinear activations.
- ensure convexity of weight loss.
-
At gradient descent, the default update is:
- .
- .
- .
- .
-
For a lot and weights , the pre-activation output has format:
- .
- mandatory.
- .
- in all cases.
-
In reverse automatic differentiation, vector–Jacobian products allow:
- propagate output derivatives to the previous nodes of the graph.
- delete the graph before calculating the loss.
- replace all data with scalars.
- avoid the rule of jail.
-
During backpropagation, the weights shall be updated:
- as soon as each intermediate derivative appears, even if old weights still They’re necessary.
- only after calculating the gradients necessary for iteration.
- before forward propagation.
- only when the loss is exactly zero.
Answer key with explanations
- a. The composition of related transformations remains in tune; without not linearity, depth does not expand this functional class.
- a. ReLU preserves positive inputs and zeros negative inputs.
- b. Softmax produces non-negative probabilities whose sum is one.
- c. There are weights and 3 biases, totaling 18 parameters.
- a. The result deals with existence and approximation, does not guarantee training, efficiency or generalization.
- a. Successive layers can reuse and compose level characteristics previous ones.
- b. The negative signal points locally in the direction of function reduction objective.
- c. The product results in , and bias is spread by line.
- a. The reverse mode accumulates sensitivities by means of the string rule without To form completely unnecessary Jacobian.
- b. Update before the end can mix new and old values and produce inconsistent gradients.