Lesson 13 · Introduction to Deep Learning I
⏱ 55 min read
This is the final lecture of the first machine learning course. We will bring together much of what we have already studied: linear models, loss functions, gradient descent, logistic regression and the fight against overfitting. And then we will see how a neural network emerges from these familiar ideas.
The main goal is to understand not just what a neural network is made of, but how it works as a single system:
- Input features — what is known about the object.
- The forward pass — weights, biases, weighted sums and activation functions.
- The prediction and the loss function — how far the prediction is from the correct answer.
- Backpropagation — computing the gradients: how the parameters affect the error.
- The optimizer — updating the weights and the biases.
The cycle repeats while the model is learning. Let us remember this sequence. Every other concept in the lecture exists in order to make sense of one of its stages.
Part I. From familiar models to neural networks
1. Why deep learning was needed
1.1. What deep learning is
Let us start with three concepts that are often used almost as synonyms, although they mean different things.
Machine learning (ML) is a field of artificial intelligence in which algorithms learn to find patterns in data and use them for prediction or decision-making.
For example, we can give a model information about apartments: the area, the number of rooms, the district and the price. From the examples the model will learn to predict the price of an apartment it has never seen.
An artificial neural network (ANN) is a family of models made up of connected computational elements called artificial neurons. These elements transform input numbers into output numbers using trainable parameters.
Deep learning (DL) is a branch of machine learning based on training multilayer neural networks. The word "deep" is primarily about having several successive layers of computation.
The three concepts relate to each other like this:
- Artificial intelligence (AI) — the broad field of building systems that perform tasks associated with intellectual activity.
- Machine learning (ML) — models that learn from data. Neural networks are one type of such models.
- Deep learning (DL) — an approach to machine learning with multilayer neural networks.
This is a simplified scheme of the relationships between the fields. In particular, not all artificial intelligence is based on machine learning, and not all machine learning uses neural networks.
1.2. Why not stop at the models we have already studied?
In the previous lectures we met several ways of building models.
- Linear regression finds a relationship between features and a numerical answer.
- Logistic regression uses a linear combination of features for classification.
- KNN looks for similar objects among the training examples.
- Decision trees split objects by conditions in sequence.
- Random forest combines many trees.
- Gradient boosting adds models one after another that correct the mistakes of the previous ones.
All these approaches are useful. But let us consider a task in which we have to determine whether a photograph shows a cat.
A human easily uses many visual details: contours, the shape of the ears, the eyes, the texture of the fur, the relative position of the parts of the body. And how do we turn an image into numbers that a model will understand?
We could invent features by hand: the number of contours, the average colour, the shape of individual regions. This approach is called feature engineering — creating useful features from the raw data.
The problem is that for complex data it is hard to think of all the necessary features in advance.
Neural networks offer a different approach: we specify the structure of the model, and during training it selects the parameters that help to extract useful combinations of the input data.
In sufficiently complex multilayer networks the intermediate representations can gradually become better suited to the task. For example, an early layer may react to simple changes in brightness, while the following layers combine the information into more complex features.
This does not mean that every layer will necessarily learn exactly that sequence. The specific representations depend on the architecture, the data, the task and the training.
1.3. What neural networks can do
Neural networks are applied to very different types of data.
- Images — object recognition, image classification, analysis of medical scans.
- Sound — speech recognition, sound classification, audio signal processing.
- Text — message classification, machine translation, text processing and generation.
- Numerical data and forecasting — time-series forecasts, estimating indicators and modelling complex dependencies.
Different types of data often use different neural network architectures. In this lecture we will study a basic architecture — the multilayer perceptron (MLP).
1.4. Why neural networks often need a lot of data
A neural network can have very many trainable parameters. To select them, the model has to get enough information from the examples.
Imagine that we are trying to train a model to determine the price of an apartment from two features: the area and the number of rooms.
If the relationship is approximately linear, a simple model may be enough.
Now imagine that we need to recognise complex images. The variety of possible objects, lighting, angles and backgrounds is much greater. Training a model capable of handling such differences robustly usually requires more diverse data and significant computation.
But the rule "neural networks always require huge amounts of data" is wrong. Small networks can be trained on small datasets, and pre-trained models can adapt to new tasks with a relatively small number of examples.
The main idea: neural networks do not replace all other models. They provide a flexible way to build complex functions, but that flexibility comes at the price of computation, tuning and the risk of overfitting.
2. From linear regression to an artificial neuron
2.1. Recalling the linear model
In Lecture 2 we studied the formula of linear regression:
Let us go through the notation once more.
| Notation | Meaning |
|---|---|
| \(x\) | The input feature — a known value |
| \(w\) | The weight — a parameter that determines the influence of the feature |
| \(b\) | The bias — a parameter that allows the result to be shifted |
| \(\hat y\) | The prediction of the model |
Suppose we predict the price of an apartment in conventional units from its area:
If \(x=20\), then:
The model multiplied the area by the weight \(3\) and added the bias \(10\).
The weight and the bias do not have to be known in advance. During training the model selects them from the data in order to reduce the loss function.
2.2. What changes if there are several inputs?
Imagine that the price depends not only on the area but also on the number of rooms. Let us denote:
- \(x_1\) — the area;
- \(x_2\) — the number of rooms;
- \(w_1\) and \(w_2\) — the weights of these features;
- \(b\) — the bias.
Then the model can compute:
Why do we use the letter \(z\) rather than \(\hat y\) straight away? Because now we need to single out a separate stage of the computation — the weighted sum of the inputs. Later we will be able to transform it with an additional function.
For example, let:
We substitute the numbers:
First the multiplications:
We obtained the number \(59\).
For now this is only the result of the weighted sum. Depending on the model, it may be the final prediction or an intermediate value for the next computation.
2.3. What an artificial neuron is
An artificial neuron is a computational element that receives input numbers, multiplies them by the corresponding weights, adds the results together with the bias and transforms the sum with an activation function.
Its computation consists of two stages. The first stage is the weighted sum:
Here:
- \(n\) — the number of inputs;
- \(i\) — the index of the input;
- \(x_i\) — the value of input number \(i\);
- \(w_i\) — the weight of that input;
- \(b\) — the bias;
- \(z\) — the result before activation.
The symbol \(\sum\) means "add up all the listed terms". For example, if there are three inputs, then:
The second stage is the activation function:
Here \(f\) is the chosen activation function and \(a\) is the output of the neuron after it is applied. As a result the neuron does not merely add numbers up: it transforms them according to a certain rule.
2.4. A complete numerical example of a neuron
Let the neuron receive two inputs:
Its parameters:
To begin with we compute the weighted sum:
We substitute the values:
We perform the multiplications:
Now suppose the activation function is ReLU. We will examine its exact definition in the next section; for now it is enough to know the rule: it replaces a negative number with zero and leaves a positive one unchanged.
We get:
So the input numbers \(2\) and \(3\) turned into the output \(0\). What happened?
| Stage | Value |
|---|---|
| Inputs | \(2\) and \(3\) |
| Weighted sum \(z\) | \(-1\) |
| Output after ReLU \(a\) | \(0\) |
Note that an output of \(0\) does not mean that the original inputs were zero. It came about after applying the weights, the bias and the activation.
2.5. What the weights and the bias mean
The weight shows how an input affects the weighted sum.
- A positive weight increases the sum when the input is positive.
- A negative weight decreases it when the input is positive.
- The larger the absolute value of the weight, the stronger the influence of the input on the sum, all else being equal.
The bias \(b\) is added independently of the input values. It allows the model to shift the result and thereby widens the set of available transformations.
However, a single weight cannot always be interpreted as the standalone importance of a feature: the meaning of a weight depends on the scale of the input data, the other parameters and the whole architecture.
2.6. How an artificial neuron differs from a biological one
The name comes from a historical analogy with nerve cells. A biological neuron receives signals, processes them and passes them on to other cells. An artificial neuron also takes inputs and produces a result that can be fed to the following elements of the network.
But the similarity is limited.
A biological cell has complex electrochemical dynamics. An artificial neuron in an MLP is a mathematical operation on numbers. It does not reproduce a full biological cell and does not become a thinking being thanks to the mere use of that name.
In machine learning what matters to us is not the resemblance to a brain but what computational function the model can implement.
3. Activation functions
We have already seen that a neuron first computes a number \(z\) and then transforms it:
Why is the second stage needed?
Imagine that we built a network of several layers, but every layer only multiplies the inputs by weights and adds the results up. Despite the large number of parameters, such a network would in the end still perform a linear transformation.
For a network to be able to model more complex relationships, non-linear activation functions are usually added between the linear transformations.
Non-linearity means that the function cannot be fully represented by an ordinary linear transformation. It is exactly what allows a multilayer network to create more complex relationships.
3.1. ReLU
ReLU stands for Rectified Linear Unit. Intuitively, this function cuts off negative values, leaving zero, and passes positive values on unchanged.
The formula:
The word \(\max\) means "choose the greater of the two values". Examples:
Checking ReLU on an example. The result is \(0\). A negative value turns into \(0\); a non-negative one stays as it is.
The range of the outputs of ReLU is from \(0\) to \(+\infty\). Advantages:
- simple and fast to compute;
- for positive values the derivative equals \(1\), so in that region the gradient signal is not reduced by ReLU itself;
- widely used in the hidden layers of MLPs and many other networks.
Limitation: if a neuron constantly receives negative values, its ReLU output stays zero. On the negative part the derivative equals zero, so the gradient does not pass through that neuron. This is one of the reasons the Leaky ReLU variant appeared.
3.2. Sigmoid
The sigmoid transforms any real number into a number between \(0\) and \(1\). The formula:
Here \(e\approx2.71828\) is a mathematical constant, the base of the natural logarithm.
We do not need to study the exponential function in detail right now. It is important to understand that the sigmoid squeezes the input into the interval from \(0\) to \(1\).
Examples:
The larger the positive value of \(z\), the closer the output is to \(1\). The more strongly negative the value, the closer the output is to \(0\).
The sigmoid is often used at the output of a binary classification model when an estimate of the probability of the positive class is required.
Limitation: for values that are very large in absolute terms the output almost stops changing. In such regions the derivative of the sigmoid is close to zero, which can make the training of deep networks harder.
3.3. Hyperbolic tangent (tanh)
The hyperbolic tangent, or tanh, is similar to the sigmoid, but its outputs lie between \(-1\) and \(1\).
Examples:
Tanh is convenient when both positive and negative values are useful. Like the sigmoid, it saturates for inputs that are large in absolute value, and its derivative becomes small.
3.4. Leaky ReLU
Leaky ReLU keeps a small negative slope instead of zeroing the negative region completely.
Here \(\alpha\) is a small positive number, for example \(0.01\). If \(z=-3\), then with \(\alpha=0.01\):
Unlike ReLU, the result is not zero. A small gradient is preserved on the negative part.
3.5. Comparing the activation functions
| Function | Range | Typical use | Main limitation |
|---|---|---|---|
| ReLU | \([0,+\infty)\) | Hidden layers | Zero gradient on the negative part |
| Sigmoid | \((0,1)\) | The output of binary classification | Saturation and small gradients |
| Tanh | \((-1,1)\) | Some hidden layers and special models | Saturation and small gradients |
| Leaky ReLU | \((-\infty,+\infty)\) | Hidden layers | The slope \(\alpha\) has to be chosen |
3.6. Why the derivatives of activations matter
The derivative shows how much the output of a function changes when its input changes slightly. For example, on the positive part of ReLU:
On the negative part:
These values matter during training: the gradient passes through the computations of the network, and the derivative of each function takes part in determining how strongly the early parameters affect the final error.
There is no need to memorise all the derivatives right now. For the moment it is important to grasp the connection: an activation function determines the output of a neuron, and its derivative influences how the gradient passes during training.
3.7. Hidden activation and the output of the model are not the same thing
Inside the network activations help to build complex transformations. At the output the function is chosen with the task in mind.
- For regression a linear output is often used.
- For binary classification the sigmoid may be used.
- For multiclass classification softmax is often applied.
Softmax transforms a set of numbers into a probability distribution over the classes: every value lies between \(0\) and \(1\), and the sum of all the values equals \(1\).
For three classes, for example, the output may look like this:
This means that the model assigned the score \(0.7\) to the first class, \(0.2\) to the second and \(0.1\) to the third. These numbers cannot always be interpreted as well-calibrated probabilities: it depends on the quality of the model and on the calibration.
4. How neurons form a network: the MLP
4.1. The layers of a neural network
A multilayer perceptron (MLP) is a basic neural network architecture in which the outputs of one layer are passed to the next layer, usually through fully connected links.
In a fully connected layer every neuron receives inputs from all the neurons of the previous layer. Let us go through the three kinds of layer.
- The input layer represents the features of the object.
- A hidden layer transforms the information between the input and the output.
- The output layer forms the final result of the model.
The word "hidden" does not mean that the values are inaccessible or secret. It means that this is an intermediate layer, not the original input or the final output of the model.
The MLP scheme: 2 → 2 → 1
Two inputs, two neurons in the hidden layer, one output neuron.
The lines denote trainable connections. Every connection has a weight; every neuron of the hidden and output layers usually has a bias.
The input features are not trainable neurons themselves. In the example \(x_1\) and \(x_2\) are simply two numbers describing the object.
4.2. What architecture and parameters are
The architecture describes the structure of the network: how many layers it has, how many neurons are in each layer and how they are connected.
The parameters of a model are the numerical values that are selected during training. In an ordinary MLP these are primarily the weights of the connections and the biases of the neurons.
For example, the architecture "two inputs, two hidden neurons, one output" may have different weight values after different training runs. The architecture stays the same, but the resulting function differs.
It is important not to confuse parameters and hyperparameters.
- The weights and the biases are parameters that the model trains.
- The number of layers, the number of neurons and the learning rate are hyperparameters that are chosen to configure the training.
4.3. Vectors and matrices: why this notation is needed
Until now we have written down the computations of a single neuron. But when there are many neurons, long formulas become inconvenient.
A vector is an ordered set of numbers. For example:
This is a vector of two elements. A matrix is a rectangular table of numbers. For example:
It has two rows and two columns. In a neural network a weight matrix makes it possible to write many weighted sums in a single formula:
Then:
Here \(f\) is applied to every element of the vector \(\mathbf{z}\) separately. Let us consider a layer with two inputs and three neurons. Then:
- \(\mathbf{x}\) contains 2 numbers;
- \(W\) contains 3 rows and 2 columns;
- \(\mathbf{b}\) contains 3 biases;
- \(\mathbf{z}\) contains 3 weighted sums;
- \(\mathbf{a}\) contains 3 outputs after activation.
The general rule for a fully connected layer:
where \(n\) is the number of input numbers and \(m\) is the number of neurons in the layer. The notation \(\mathbb{R}^{m\times n}\) means that the matrix has \(m\) rows and \(n\) columns, and its elements are real numbers.
The input vector has \(n\) elements, while the vectors of biases, weighted sums and activations have \(m\) elements.
4.4. How many parameters does a layer need?
For each of the \(m\) neurons there are \(n\) weights and one bias. Therefore:
For a layer with two inputs and two neurons:
That is four weights and two biases. For the next layer with two inputs and one output neuron:
The whole network from the scheme above contains:
Nine trainable parameters in total.
5. The forward pass
The forward pass is the computation of the prediction of the model from the input data with the current values of the parameters. At this stage the network does not yet have to learn or change its weights. It simply performs the specified computations.
Let us consider a network with two inputs, two hidden neurons and one output neuron. For simplicity we use ReLU in the hidden layer and a linear output.
5.1. Setting the inputs and the parameters
The input features:
The first hidden neuron:
The second hidden neuron:
The output neuron:
All the numbers here are conventional: we made them up in order to learn to perform the calculations by hand.
5.2. Computing the first hidden neuron
We substitute the inputs:
We apply ReLU:
The first hidden neuron produces \(4\).
5.3. Computing the second hidden neuron
We substitute the values:
We apply ReLU:
The second hidden neuron produces \(0\).
5.4. Computing the output of the network
Now the output neuron receives \(a_1=4\) and \(a_2=0\):
We substitute the values:
So the network produced the prediction \(8.5\). The result of the forward pass:
| Quantity | Value |
|---|---|
| The first neuron \(a_1\) | \(4\) |
| The second neuron \(a_2\) | \(0\) |
| The prediction \(\hat y\) | \(8.5\) |
5.5. What happens if one weight is changed?
Suppose we change the weight of \(x_1\) in the first hidden neuron from \(1\) to \(2\). Then:
ReLU leaves \(6\), so \(a_1=6\). The second neuron has not changed and still produces \(a_2=0\).
The new prediction:
The prediction grew from \(8.5\) to \(12.5\). This shows that the weight of a single early neuron can influence the final prediction through a sequence of computations.
But we do not yet know whether this is a good result. If the correct answer is \(10\), increasing the prediction helped. If the correct answer is \(20\), it may have made the result worse. To assess it we need a loss function.
5.6. Why the network is not computed by hand for every object
In a real task the network receives many objects, and every layer may contain thousands or millions of parameters.
Instead of individual computations, modern libraries use operations on arrays of numbers. They make it possible to perform a large number of multiplications and additions in parallel.
A GPU — a graphics processing unit — is especially efficient for many such operations. However, it does not make the model smarter by itself: it helps to perform the computations faster.
6. The prediction, the target and the loss function
6.1. Three quantities that must not be confused
Suppose a model predicts the price of an apartment.
- The target (\(y\)) is the correct answer known for a training example.
- The prediction (\(\hat y\)) is the answer produced by the model.
- The error is a measure of how much the prediction differs from the correct answer.
Let:
The difference between the prediction and the target:
The sign shows the direction of the deviation. But for training we often need a quantity that assesses the quality of the prediction taking the direction and the scale of the error into account.
This task is solved by the loss function.
6.2. Regression and MSE
In a regression task the model predicts a number. One common loss function is the mean squared error, MSE (Mean Squared Error).
For one object we square the difference:
The square makes the error non-negative and penalises large deviations more strongly. If we have \(N\) objects, the mean squared error is written like this:
Here \(N\) is the number of objects, \(y_i\) is the correct answer for object \(i\), and \(\hat y_i\) is the prediction for it.
6.3. Binary classification
In binary classification we have to choose between two classes, for example "spam" and "not spam". The sigmoid makes it possible to transform the output logit \(z\) into a number from \(0\) to \(1\):
If \(p=0.8\), the model has assigned the score \(0.8\) to the positive class. With the standard threshold \(0.5\) it will assign the object to the positive class.
For training, binary cross-entropy is often used. Its meaning is to penalise the model for probabilistic predictions that agree poorly with the correct labels.
6.4. Multiclass classification
If there are more than two classes, for example "cat", "dog" and "bird", the model can produce one number per class. Softmax transforms these numbers into a probability distribution:
Here \(z_k\) is the output for class \(k\), and the sum in the denominator is taken over all the classes. For example, the result may be:
| Class | The score of the model |
|---|---|
| Cat | 0.70 |
| Dog | 0.20 |
| Bird | 0.10 |
The sum equals \(1\). The model chooses the cat as the most probable class.
6.5. Why a correct architecture does not guarantee a good prediction
The architecture determines which functions the model can in principle represent. But the specific weights and biases still have to be selected.
A randomly initialised network may produce poor predictions. That is why training has to measure the error, determine how the parameters affect it, and update the parameters in a suitable direction.
This is exactly where neural networks meet the optimization from Lectures 3–4.
Part II. How a neural network learns
7. The training loop of a neural network
7.1. Training is the selection of parameters
A network has trainable parameters \(\theta\). This letter often denotes the whole set of weights and biases of the model.
At the start of training the parameters are usually initialised in a certain way. Then the network receives training examples and gradually changes the parameters in order to reduce the loss function.
The full cycle looks like this:
- The input data — we obtain the features of the object and, during training, its correct answer.
- The forward pass — we compute the prediction with the current weights and biases.
- The loss function — we measure how far the prediction is from the target value.
- Backpropagation — we compute the gradients of the loss function with respect to the trainable parameters.
- The optimizer step — we update the parameters using the gradients.
- Repetition — we continue training on the next batches.
7.2. A reminder of gradient descent
In Lecture 3 we studied gradient descent. Its idea is to change the parameters of the model so as to reduce the loss function.
The basic formula:
Let us go through every symbol.
- \(\theta_{\text{old}}\) — the current parameters of the model.
- \(\theta_{\text{new}}\) — the parameters after the update.
- \(L\) — the loss function.
- \(\nabla_\theta L\) — the gradient of the loss function with respect to the parameters.
- \(\eta\) — the learning rate.
A gradient is a set of derivatives of the loss function with respect to the different parameters. It shows how the loss changes when each parameter changes slightly while the other parameters are held fixed.
The minus sign means that in standard gradient descent we move in the direction opposite to the gradient.
7.3. A small numerical example of a weight update
Let the parameter be \(w=2\), the learning rate \(0.1\), and the gradient with respect to this parameter \(4\). Then:
The weight decreased from \(2\) to \(1.6\).
This does not yet prove that the loss necessarily decreased in practice for any step. If the step is too large or the function is complex, the update may make the result worse. The learning rate and the choice of the optimizer matter.
7.4. What an epoch, a batch and an optimization step are
| Term | Explanation |
|---|---|
| Epoch | One complete pass over the training dataset |
| Batch | A small group of objects processed together |
| Optimization step | One update of the parameters by the optimizer |
Suppose the training set contains 1,000 objects and the batch size is 100.
Then, under an ordinary training scheme, one epoch contains 10 batches. If the optimizer updates the parameters after every batch, one epoch includes 10 optimization steps.
If the network is trained for 20 epochs, that will be 200 optimization steps under the same conditions.
In reality the number of steps depends on the size of the data, the batch size, the way the last incomplete batch is handled and the chosen training scheme.
7.5. Why the weights are not selected one by one by hand
In a large network the parameters influence each other through chains of computations. Changing one weight can change the output of a hidden neuron, then the next layer, and then the final prediction.
Selecting every parameter by hand would be practically impossible. Instead the algorithm computes gradients for many parameters, and the optimizer uses them for systematic updating.
The key distinction: the gradient says how the loss depends on the parameters, while the optimizer decides how to change the parameters given the gradient and the chosen algorithm.
8. Backpropagation: how the error reaches the early layers
This is the central idea of the lecture. Let us look at it not as a magic command but as a sequence of computations.
8.1. The main question
Suppose the network produced the prediction \(8.5\), although the correct answer is \(10\).
We know that the prediction needs to be improved. But the network has many weights and biases. How can we tell which parameters to change and by how much?
We need to find out how each parameter affects the final loss function. This process is called backpropagation.
Strictly speaking, backpropagation computes the gradients using the structure of the model's computations. It does not update the weights itself.
8.2. Intuition: a chain of dependencies
Let us imagine a simple model:
Each quantity depends on the previous one.
- \(x\) — the input;
- \(z_1\) — the weighted sum of the first neuron;
- \(a_1\) — the result of the activation;
- \(\hat y\) — the prediction;
- \(L\) — the loss.
If we change an early weight, \(z_1\) changes. A change in \(z_1\) can change \(a_1\), then the prediction, and finally the loss function.
To compute the influence of an early weight, we need to take all the intermediate dependencies into account.
8.3. The chain rule
The chain rule is a rule for differentiating a composite function. It allows us to find how a change in one quantity affects the final result through intermediate computations.
Let:
Then \(L\) depends on \(w\) through \(z\) and \(\hat y\). The chain rule gives:
This is not an accidental multiplication of three derivatives. Each of them is responsible for one transition in the chain of computations.
8.4. A numerical example of backpropagation
Let us take the simplest possible model:
Let the current weight be:
Then the prediction is:
The loss function:
Now let us compute the gradient with respect to the weight. Step 1. The derivative of the loss with respect to the prediction.
The derivative of the square:
We substitute the values:
Step 2. The derivative of the prediction with respect to the intermediate quantity. Here \(\hat y=z\), therefore:
Step 3. The derivative of the intermediate quantity with respect to the weight. Since \(z=wx\) and \(x=2\):
Step 4. We multiply the derivatives.
We have obtained the gradient \(-8\). What does it mean? At the current point a small increase in the weight will decrease the loss, because the gradient is negative.
8.5. Now the optimizer works
Let the learning rate be \(0.1\).
Let us check the new prediction:
The new loss:
The loss decreased from \(4\) to \(0.16\).
What have we just done?
| Quantity | Before the step | After the step |
|---|---|---|
| Weight \(w\) | 2 | 2.8 |
| Prediction \(\hat y\) | 4 | 5.6 |
| Loss \(L\) | 4 | 0.16 |
In this particular example one step reduced the loss. This does not mean that any step on any task will be equally successful.
8.6. Backpropagation and Gradient Descent are different things
| Backpropagation | Gradient Descent |
|---|---|
| Computes the gradients with respect to the parameters | Uses the gradients to update the parameters |
| Relies on the chain rule | Uses the update rule |
| Answers the question "how does the loss depend on the weights?" | Answers the question "how should the weights be changed?" |
Modern optimizers, for example Adam, use more complex update rules than plain gradient descent. But the principle of separation remains the same: first the gradients have to be obtained, and then the optimizer uses them to update the parameters.
9. Overfitting in neural networks
9.1. What is overfitting?
Overfitting occurs when a model adapts too well to the training data but performs worse on new examples.
This is not a problem specific to neural networks. We have already encountered it while studying decision trees, random forests and boosting.
A large network may have enough parameters to memorize many characteristics of the training objects, including random noise.
9.2. Train, validation and test
Data is often split into three parts.
- Train (the training set) is used to fit the parameters of the model.
- Validation (the validation set) is used to tune hyperparameters and choose the model.
- Test (the test set) is used for the final evaluation on data that did not participate in the tuning.
Suppose the training error keeps decreasing, but the validation error starts growing after a certain point. This may indicate overfitting.
9.3. Early stopping
Early stopping is the early termination of training.
The idea is simple: we monitor the quality on the validation set and stop training when further epochs stop improving the chosen metric.
For example:
| Epoch | Train loss | Validation loss |
|---|---|---|
| 1 | 0.80 | 0.85 |
| 2 | 0.60 | 0.68 |
| 3 | 0.45 | 0.54 |
| 4 | 0.32 | 0.56 |
| 5 | 0.23 | 0.63 |
The train loss decreases constantly. The validation loss reaches its minimum at the third epoch and then grows.
In such a situation a stop around the third epoch can be considered. In practice, tolerance for short-term fluctuations is often used rather than reacting to every increase in the error.
9.4. Regularization and weight decay
Regularization is a general approach that helps limit unwanted complexity of a model.
Weight decay is one of the methods that adds a tendency to reduce the magnitudes of the weights to the training process.
In simplified terms, a penalty for large weights can be added to the original loss function:
Here \(L_{\text{data}}\) is the loss on the data, \(\lambda\) is the regularization coefficient, and the sum of squared weights defines the penalty.
This formula illustrates L2 regularization. The particular implementation of weight decay depends on the optimizer and its settings.
Regularization does not guarantee the absence of overfitting, but it helps control the complexity of the model.
10. Why deep networks can be hard to train
10.1. Vanishing gradients
During backpropagation the gradient is passed from the later layers to the earlier ones. At each step it is multiplied by the derivatives of the corresponding computations.
If many of the factors are less than one in absolute value, the product can become very small. For example:
If there are far more such factors, the final value can turn out to be almost zero.
This phenomenon is called the vanishing gradient. The early layers receive very small gradients, so their parameters may be updated too weakly.
10.2. Exploding gradients
The opposite situation is also possible. If the products of the factors are greater than one in absolute value, the value of the gradient can grow rapidly.
For example:
With a large number of such factors the gradients can become excessively large. This is called the exploding gradient. Gradients that are too large can lead to unstable updates and a sharp growth of the loss function.
10.3. Other causes of difficulty
- Unsuccessful initialization. If the initial weights are chosen poorly, the signals and gradients may have unsuitable scales.
- The scale of the inputs. If some features have values around \(0.01\) and others around \(100000\), training can become harder.
- Activation functions. Some functions saturate at large absolute values and give very small derivatives.
- Too large a learning rate. The updates may jump over regions of lower loss.
To solve these problems, special initialization methods, data normalization and other techniques for stabilizing training are used. We will look at them in more detail in the following courses.
11. The number of parameters and the computational cost
11.1. Counting the parameters
Consider a fully connected layer with 100 inputs and 64 neurons. Each neuron receives 100 inputs, so it has 100 weights and one bias.
One neuron accounts for:
For 64 neurons:
That is 6 464 trainable parameters in total.
If the number of neurons is increased, the number of parameters grows. If new fully connected layers are added, both the computational cost and the memory requirements usually grow.
11.2. Why is more not always better?
A large network has greater potential expressiveness, but this does not guarantee better quality.
The result depends on the data, the architecture, the training, the regularization and the complexity of the task. A large model may train longer, require more memory and overfit more strongly when data is scarce.
11.3. Why is a GPU needed?
Fully connected layers contain many multiplication and addition operations. They can be combined efficiently into matrix computations.
A GPU is capable of performing a large number of such operations in parallel, which speeds up the training and the application of many neural networks.
But the batch size also affects the computations. A large batch often makes better use of the GPU, yet requires more memory. A batch that is too large does not always give better generalization and may require additional tuning of the training.
Part III. Comparison with classical machine learning
12. Neural networks and familiar models
| Model | How it works | When it may be more convenient |
|---|---|---|
| Linear regression | Combines the features in a linear way | Simple dependencies, interpretability |
| Logistic regression | Transforms a linear combination into a probability estimate | Basic classification, a clear reference point |
| KNN | Looks for the nearest training objects | Small tasks with a suitable distance metric |
| Decision tree | Splits the feature space with conditions | Simple rules, interpretability |
| Random forest | Combines many trees | Many tabular tasks, a stable baseline approach |
| Gradient boosting | Builds an ensemble of models successively | Often a very strong option for tabular data |
| MLP | Successively transforms the input through trainable layers | Complex non-linear dependencies, numerical data and other suitable tasks |
12.1. How is an MLP similar to a linear model?
Each neuron performs a weighted sum with an added bias. This is the linear operation we already know.
But non-linear activations appear between the layers. They allow the network to build functions that are considerably more complex than a single linear combination of the inputs.
If all the non-linear activations are removed, several consecutive linear transformations can be combined into one transformation. That is why depth by itself does not make a model non-linear.
12.2. Why is a neural network not always better than boosting?
On small tabular datasets, gradient boosting is often a strong choice: it works well with many types of numerical and categorical features, does not require the same architectural tuning as a neural network, and not infrequently gives good quality without a huge amount of data.
Neural networks are especially useful where complex representations have to be learned, for example when working with images, text and audio, and also in tasks where large datasets or pre-trained models are available.
But this is not a rigid division. An MLP can also be effective on tabular data, and boosting can solve complex practical problems excellently.
The right approach is to choose a model based on the results of validation, the constraints of the task, the available data and the cost of development.
Part IV. An end-to-end classification example
13. How a small network learns to distinguish two classes
Now let us bring together the familiar stages: the inputs, the forward pass, the loss, the gradients and the parameter update.
Suppose we need to classify conventional objects by two numerical features \(x_1\) and \(x_2\). Each object belongs to one of two classes: \(0\) or \(1\).
For the teaching example let us take a network with:
- two input features;
- one hidden neuron with ReLU;
- one output neuron with sigmoid.
We deliberately chose a very small network so that all the computations can be checked by hand.
13.1. The object and the prediction
Let:
The correct class is \(1\). Let us define the hidden neuron:
We substitute the inputs:
We apply ReLU:
The output logit:
We apply the sigmoid:
The model estimates the probability of the positive class at approximately \(62.2\%\).
13.2. Calculating the loss
For a single binary example binary cross-entropy has the form:
Here \(\ln\) is the natural logarithm. Since the correct label is \(y=1\), the expression simplifies:
We substitute \(p\approx0.622\):
This is the estimate of the loss for this object and the current parameters.
13.3. How does the network learn from this example?
Next, backpropagation computes the gradients of the loss with respect to the output weight, the hidden weights and the biases. The optimizer uses these gradients to update the parameters.
After the update the model performs a new forward pass. If the loss decreased, this is a sign of improvement by the chosen loss function on the example under consideration, but it is not yet proof of better quality on new data.
13.4. Why is one object not enough?
A model that predicts one object well can make mistakes on thousands of others.
That is why training takes place on many examples, and quality is checked on data that did not participate in fitting the parameters. Only in this way can we estimate how well the model generalizes patterns beyond the training set.
Part V. Practice with Python and PyTorch
14. A practical exercise: training a small neural network
Now let us move from calculations on paper to code.
We will use PyTorch — a Python library for building and training neural networks. It can perform mathematical operations on tensors and compute gradients automatically.
A tensor is a generalization of the numbers, vectors and matrices we know. A number can be regarded as a zeroth-order tensor, a vector as a first-order tensor and a matrix as a second-order tensor. In neural networks tensors make it possible to store input data, weights, predictions and gradients.
14.1. Preparing the environment
If PyTorch is not installed yet, first activate the project's virtual environment and then install the library:
python -m pip install torch
You can check the installation with the command:
python -c "import torch; print(torch.__version__)"
For this teaching example an ordinary CPU is enough. Using a GPU is optional.
14.2. The full code
Let us create a small dataset with two features. The model has to learn to identify class \(1\) when the sum of the features is greater than \(1\), and class \(0\) otherwise.
This is an artificial teaching task, not a full-fledged model for real use.
import torch
from torch import nn
# 1. Create the training data.
# Each row is one object, the two columns are its features.
X = torch.tensor([
[0.0, 0.0],
[0.0, 1.0],
[1.0, 0.0],
[1.0, 1.0],
[0.2, 0.3],
[0.8, 0.7],
[0.2, 0.9],
[0.9, 0.2],
], dtype=torch.float32)
# The target classes: 0 or 1.
y = torch.tensor([
[0.0],
[0.0],
[0.0],
[1.0],
[0.0],
[1.0],
[1.0],
[1.0],
], dtype=torch.float32)
# 2. Define the MLP.
model = nn.Sequential(
nn.Linear(2, 4),
nn.ReLU(),
nn.Linear(4, 1),
)
14.3. Going through the program step by step
Step 1. Importing the libraries
import torch
from torch import nn
import connects a library so that we can use its functions and classes.
torch provides operations on tensors. nn contains the components for building neural networks and loss functions.
Step 2. Creating the data
X = torch.tensor([...], dtype=torch.float32)
X is the feature matrix. In our example it has eight rows and two columns.
dtype=torch.float32 means that the numbers are stored in the 32-bit floating-point format.
The variable y contains the correct classes. We write them as floating-point numbers so that they match the format expected by the chosen loss function.
Step 3. Defining the model
model = nn.Sequential(
nn.Linear(2, 4),
nn.ReLU(),
nn.Linear(4, 1),
)
nn.Sequential creates a sequence of layers: the output of each layer is passed to the next one.
nn.Linear(2, 4)— a fully connected layer with two inputs and four neurons.nn.ReLU()— applies ReLU to the outputs of the hidden layer.nn.Linear(4, 1)— transforms the four input values into a single output logit.
There is no sigmoid inside the model. This is deliberate: BCEWithLogitsLoss combines the computation of the binary cross-entropy with the handling of logits in a numerically stable way.
Step 4. The loss function
loss_fn = nn.BCEWithLogitsLoss()
It estimates the discrepancy between the output logits of the model and the correct binary labels.
In this implementation there is no need to apply the sigmoid separately before computing the loss. The sigmoid will be needed later, when we want to interpret the logits as probability estimates.
Step 5. The optimizer
optimizer = torch.optim.Adam(
model.parameters(),
lr=0.03)
model.parameters() returns the trainable parameters of the model — the weights and biases.
Adam is an optimizer that uses the gradients and accumulated information about their changes to adapt the parameter updates.
lr=0.03 sets the learning rate.
This is a hyperparameter that we chose in advance. It is not trained automatically like an ordinary neuron weight.
14.4. Three commands that are important to understand
Inside the loop there are three commands that often raise questions for beginners.
optimizer.zero_grad()
Removes the gradients accumulated from the previous step. In PyTorch gradients are accumulated by default, so before computing a new set of gradients they are usually reset to zero.
loss.backward()
Launches automatic differentiation: PyTorch computes the gradients of the loss with respect to the model's parameters. This is the practical implementation of computing derivatives through the chain of operations.
optimizer.step()
Uses the computed gradients to update the parameters according to the optimizer's algorithm. This is exactly where the weights and biases change.
It is worth paying attention to the order of the actions:
- Reset the old gradients.
- Compute the prediction.
- Calculate the loss.
- Call
backward(). - Call
step().
If the order is mixed up or one of the commands is skipped, training may work incorrectly.
14.5. What do the other commands do?
loss.item()
Converts a tensor containing a single number into an ordinary Python numeric value. This is convenient for printing to the console.
model.eval()
Switches the model into evaluation mode. In this small network there are no layers whose behaviour changes substantially between training and evaluation, but it is a useful habit for more complex models.
with torch.no_grad():
Disables gradient tracking inside the block. During ordinary prediction we do not need to perform backpropagation, so there is no need to store additional information for differentiation.
probabilities = torch.sigmoid(logits)
Transforms the logits into values between \(0\) and \(1\).
predictions = (probabilities >= 0.5).float()
Turns the probability estimates into classes: values of \(0.5\) and above become \(1\), and the rest become \(0\).
14.6. What should the result be?
During training the program prints the loss every 100 epochs. Usually, for such a small task, the loss will decrease and the predictions will gradually match the labels better.
But the specific results depend on the random initialization of the parameters. The code in this lecture was not run, so exact loss values are not given here and no particular accuracy is promised.
In addition, we evaluate the model on the same data we trained it on. For a genuine estimate of generalization ability, a separate test set has to be set aside.
Part VI. Common misconceptions
15. Ten common mistakes in understanding neural networks
1. "A neural network is just a lot of neurons."
The number of neurons does not describe the whole model. The connections, weights, biases, activation functions, loss function and training algorithm matter too.
2. "The more layers, the better."
Greater depth can increase the expressiveness of a model, but it also complicates training and raises the requirements for data and computation.
3. "Backpropagation and Gradient Descent are the same thing." Backpropagation computes the gradients. Gradient Descent uses the gradients to update the parameters.
4. "The gradient updates the weights itself." The gradient is information about the derivatives of the loss function. The parameters are changed by the optimizer.
5. "If the training loss decreased, the model has learned to solve the task." A decrease in the training loss does not guarantee good quality on new objects. An independent evaluation is needed.
6. "A neural network is necessarily needed for any task." A linear model, a tree or boosting may turn out to be simpler, faster and more accurate on a particular dataset.
7. "Weights are ready-made knowledge that the network receives in advance."
In ordinary training the weights are initialized with initial values and fitted from the data. In pre-trained models the weights were already trained earlier, but that is the result of a previous training process.
8. "One training step should noticeably improve quality."
A single step may give a very small improvement, may not change quality noticeably, or may even make it temporarily worse. Training is evaluated over many steps.
9. "A GPU is needed to make the model smarter." A GPU speeds up many computations. By itself it does not improve the architecture, the data or the quality of training.
10. "Deep learning has nothing to do with classical ML."
Deep learning is part of machine learning. Neural networks use the same fundamental ideas: data, parameters, a loss function, gradients and the evaluation of generalization ability.
11. "A hidden layer is a layer that cannot be seen." Its values can be computed and examined. "Hidden" means that it lies between the input and the output of the model.
12. "If the sigmoid produced 0.9, the probability is exactly 90%."
This is the model's estimate. It is not necessarily well calibrated: in reality, among objects with a prediction of 0.9 the positive class may occur in fewer than 90% of cases.
Part VII. Preparing for an ML interview
16. Questions and answers
Below, a brief answer comes first, which can be spoken at an interview, followed by an explanation for understanding.
Question 1. What is Deep Learning?
Brief answer: deep learning is a branch of machine learning that uses multilayer neural networks to model complex dependencies in data.
In more detail: a network successively transforms the inputs through trainable layers. During training the weights and biases are fitted, allowing the chosen loss function to be reduced. Deep networks are especially useful for complex data, but they are not always better than classical models.
Question 2. What is an artificial neuron?
Brief answer: it is a computational element that calculates a weighted sum of the inputs with a bias and applies an activation function.
In more detail: \(x_i\) are the inputs, \(w_i\) are the weights, \(b\) is the bias, \(z\) is the sum before activation and \(a\) is the output after it.
Question 3. How do weights differ from biases?
Brief answer: weights determine the contribution of the corresponding inputs to the weighted sum, while the bias adds a component independent of the inputs.
In more detail: changing a weight changes the influence of a particular input. Changing the bias shifts the result of the neuron regardless of the values of the input features.
Question 4. Why are activation functions needed?
Brief answer: they introduce non-linearity, which allows a multilayer network to model more complex dependencies than a single linear transformation.
In more detail: without non-linearities, several consecutive linear layers can be combined into one linear layer. Depth by itself does not create non-linearity.
Question 5. Why do several linear layers not give a full-fledged deep model?
Brief answer: a composition of linear transformations remains a linear transformation.
In more detail: if one layer computes \(W_1x+b_1\) and the next applies another linear transformation to the result, they can be combined into one transformation with a different weight matrix and bias.
Question 6. What is an MLP?
Brief answer: an MLP is a multilayer perceptron, usually consisting of fully connected layers with activation functions between them.
In more detail: the input features are passed to the hidden layers and then to the output layer. The weights and biases are trained on the data.
Question 7. What happens during the forward pass?
Brief answer: the model successively computes the outputs of its layers and obtains the final prediction.
In more detail: at each layer the weighted sums are calculated, the activation functions are applied, and the results are passed to the next layer. At this stage the parameters are usually not updated.
Question 8. What is a loss function?
Brief answer: a loss function quantitatively estimates how well the model's prediction matches the correct answer according to the chosen criterion.
In more detail: for regression MSE can be used, and for binary classification, binary cross-entropy. The loss serves as the target quantity that training strives to reduce.
Question 9. What is backpropagation?
Brief answer: an algorithm for computing the gradients of the loss function with respect to the network's parameters using the chain rule.
In more detail: the computations start from the loss and go back through the graph of operations in order to determine how the parameters influenced the final result.
Question 10. How does backpropagation differ from Gradient Descent?
Brief answer: backpropagation computes the gradients, and Gradient Descent uses them to update the parameters.
In more detail: these are two different stages of training. The gradients can be used by different optimizers, including SGD and Adam.
Question 11. What is the chain rule?
Brief answer: it is a rule for differentiating a composite function that makes it possible to compute the influence of an early quantity on the result through intermediate computations.
In more detail: if the loss depends on a parameter through several functions, the derivative with respect to the parameter equals the product of the corresponding derivatives along the chain of dependencies.
Question 12. What is an epoch and a batch?
Brief answer: an epoch is one complete pass over the training set, and a batch is a group of objects processed in one computation step.
In more detail: if the parameters are updated after each batch, the number of batches per epoch determines the number of optimization steps in that epoch.
Question 13. Why do neural networks overfit?
Brief answer: the network can adapt to the characteristics and noise of the training set that do not recur in new data.
In more detail: the risk depends on the complexity of the model, the amount and quality of the data, the regularization and the training process. Independent data and monitoring of the validation loss are used for evaluation.
Question 14. What are vanishing gradients?
Brief answer: it is a situation in which the gradients become very small during backpropagation, so the early layers receive weak signals for updating their parameters.
In more detail: when derivatives smaller than one in absolute value are multiplied repeatedly, the product can rapidly approach zero.
Question 15. How is the number of parameters of a layer counted?
Brief answer: for a fully connected layer with \(n\) inputs and \(m\) neurons, with a bias for each neuron, the number of parameters equals \(mn+m\).
In more detail: each neuron has \(n\) weights and one bias. There are \(m\) neurons in total, so the result is \(m(n+1)\).
Question 16. Is a neural network always better than gradient boosting?
Brief answer: no. The choice depends on the data, the task, the computational constraints and the quality requirements.
In more detail: boosting is often a strong choice for tabular data. Neural networks are especially useful for many complex tasks with images, text and audio, but the comparison has to be made experimentally.
Part VIII. Independent practice
17. Tasks for independent solution
First try to solve the tasks on your own. There is no need to get the right answer immediately: the goal is to learn to walk the path from the problem statement to the computation.
1. Analysing the neuron formula — beginner level
In the formula \(z=3x_1-2x_2+4\), identify the inputs, the weights, the bias and the result before activation. How many inputs does the neuron have?
2. Computing the output — beginner level
Given \(x_1=2\), \(x_2=4\), \(w_1=0.5\), \(w_2=-1\), \(b=2\). Find \(z\) and the ReLU output.
3. Performing a forward pass — intermediate level
Hidden neuron 1: \(z_1=x_1+x_2-1\). Hidden neuron 2: \(z_2=2x_1-x_2\). Both use ReLU. Output: \(\hat y=2a_1+a_2\). Find the prediction for \(x_1=2\), \(x_2=1\).
4. Counting the parameters — intermediate level
How many trainable parameters does a fully connected layer with 5 inputs and 3 neurons have, if each neuron has a bias?
5. Choosing the output — intermediate level
Which output activation should be chosen for regression without a range limit, for binary classification and for multiclass classification? Briefly explain the choice.
6. Separating the algorithms — intermediate level
A developer claims that they called backpropagation and it updated the weights. What is wrong with this claim?
7. Spotting overfitting — intermediate level
The train loss keeps decreasing while the validation loss grows for several epochs in a row. How can the situation be interpreted, and what could be tried?
8. Finding the mistake — advanced level
In a training program the call to optimizer.zero_grad() was forgotten, while loss.backward() is called on every iteration. Why can this lead to incorrect training?
9. Computing the gradient — advanced level
Model \(\hat y=wx\), \(x=3\), \(y=9\), current \(w=2\), loss \((\hat y-y)^2\). Find the prediction, the loss and the derivative \(dL/dw\).
10. Taking a step — advanced level
Use the gradient from task 9 and the learning rate \(\eta=0.1\). Compute the new weight and the new prediction. Did the loss decrease?
Show detailed solutions
1. Analysing the neuron formula
In the formula \(z=3x_1-2x_2+4\) there are two inputs: \(x_1\) and \(x_2\). The weights equal \(w_1=3\) and \(w_2=-2\), and the bias is \(b=4\). Before activation we get the weighted sum \(z=3x_1-2x_2+4\); its numerical value depends on the values of the inputs.
2. Computing the output
\(z=0.5\cdot2+(-1)\cdot4+2=1-4+2=-1\). The ReLU of a negative value is zero, so \(a=0\).
3. Performing a forward pass
\(z_1=2+1-1=2\), so \(a_1=2\). Next \(z_2=2\cdot2-1=3\), so \(a_2=3\). The prediction: \(\hat y=2\cdot2+3=7\).
4. Counting the parameters
Each of the three neurons has 5 weights and one bias, that is, 6 parameters. In total \(3\cdot(5+1)=18\) trainable parameters.
5. Choosing the output
For regression without a range limit a linear output without activation is suitable. For binary classification, the sigmoid: a single value from 0 to 1. For multiclass, softmax: a probability distribution over the classes.
6. Separating the algorithms
Backpropagation only computes the gradients. The parameters are updated by the optimizer, so the claim that backpropagation itself updated the weights is incorrect.
7. Spotting overfitting
The divergence of the curves indicates overfitting: the network is adapting to the training set. Early stopping, regularization, simplifying the model or additional data are worth considering.
8. Finding the mistake
Without optimizer.zero_grad() the gradients accumulate between iterations, so the updates become incorrect: the old gradients are added to the new ones.
9. Computing the gradient
The prediction \(\hat y=wx=2\cdot3=6\). The loss \(L=(\hat y-y)^2=(6-9)^2=9\). The derivative \(\frac{dL}{dw}=2(\hat y-y)x=2\cdot(-3)\cdot3=-18\).
10. Taking a step
The new weight: \(w_{\text{new}}=2-0.1\cdot(-18)=3.8\). The new prediction: \(\hat y_{\text{new}}=3.8\cdot3=11.4\). The new loss: \(L_{\text{new}}=(11.4-9)^2=5.76\). The loss decreased from 9 to 5.76.
Part IX. Lecture summary
18. A brief summary
A neural network is a computational model that transforms input data into a prediction through a sequence of operations with trainable parameters.
A single neuron computes a weighted sum and applies an activation function:
Layers are formed from neurons and the connections between them. In an MLP the outputs of one layer are passed to the next, and the architecture determines the number of layers, neurons and connections.
During training the network goes through a repeating cycle:
- Computes the prediction — forward pass.
- Measures the error — loss.
- Computes the gradients — backpropagation.
- Updates the parameters — optimizer step.
- Repeats the process on the following batches.
After training it is important to check how the network performs on new data. A low training loss does not yet guarantee good generalization.
Topic map
-
Data and features
The objects are described by numerical features; the goal is to predict a number or a class.
-
Neuron
A weighted sum of the inputs with a bias and an activation function: \(a=f\left(\sum_i w_ix_i+b\right)\).
-
Layers and MLP
The outputs of one layer are passed to the next; non-linear activations between the layers make it possible to model complex dependencies.
-
Forward pass
The network successively computes the outputs of the layers and obtains the prediction.
-
Loss function
The prediction is compared with the correct answer: MSE, binary cross-entropy, the loss for multiclass classification.
-
Backpropagation
The chain rule gives the gradients of the loss function with respect to all the parameters of the network.
-
Optimizer
The parameters are updated in the direction of decreasing loss: \(\theta_{\text{new}}=\theta_{\text{old}}-\eta\nabla_\theta L\).
-
The training cycle
Epochs and batches: steps 4–7 are repeated on different portions of the data.
-
Quality control
Validation, early stopping and regularization; the final check is on an independent test set.
18.1. Table of key concepts
| Concept | Simple explanation |
|---|---|
| Neuron | Computes a weighted sum and applies an activation |
| Weight (weight) | Determines the contribution of an input to the sum |
| Bias (bias) | Shifts the weighted sum |
| Activation (activation) | The output of a neuron after the activation function |
| MLP | A multilayer fully connected network |
| Forward pass | Computing the prediction |
| Loss | A numerical estimate of the error |
| Gradient | The derivatives of the loss function with respect to the parameters |
| Backpropagation | Computing the gradients through the network |
| Optimizer | An algorithm for updating the parameters |
| Epoch | A complete pass over the training data |
| Batch | A group of objects processed together |
| Overfitting | Fitting the training data while generalization gets worse |
| Early stopping | Stopping training by a quality criterion |
| Vanishing gradient | Gradients that are too small |
| Exploding gradient | Gradients that are too large |
18.2. Key terms
| Term |
|---|
| Deep Learning |
| Artificial Neural Network |
| Artificial Neuron |
| Weight |
| Bias |
| Activation Function |
| Hidden Layer |
| Input Layer |
| Output Layer |
| Multilayer Perceptron, MLP |
| Forward Pass |
| Loss Function |
| Backpropagation |
| Chain Rule |
| Gradient Descent |
| Optimizer |
| Learning Rate |
| Epoch |
| Batch |
| Overfitting |
| Regularization |
| Early Stopping |
| Vanishing Gradients |
| Exploding Gradients |
| Number of Parameters |
| Tensor |
| Logit |
| Prediction |
18.3. Main formulas
1. The weighted sum of a neuron
\(x_i\) are the inputs, \(w_i\) are the weights, \(b\) is the bias and \(z\) is the result before activation. 2. Activation
\(f\) is the activation function and \(a\) is the output of the neuron. 3. ReLU
A negative input becomes zero, a non-negative one is preserved. 4. Sigmoid
It transforms a logit into a value between \(0\) and \(1\). 5. Computing a layer
The matrix \(W\) stores the weights of all the neurons of the layer, and the vectors contain the inputs, biases and outputs. 6. MSE
The mean squared deviation of the predictions from the correct answers. 7. Updating the parameters
\(\theta\) are the parameters, \(\eta\) is the learning rate, \(L\) is the loss and \(\nabla_\theta L\) is the gradient. 8. The number of parameters of a fully connected layer
\(n\) is the number of inputs and \(m\) is the number of neurons, if each neuron has a bias.
18.4. The full training cycle
The cycle is repeated on every batch:
- Forward pass — the network computes the prediction.
- Loss — the prediction is compared with the correct answer.
- Backpropagation — the gradients with respect to the parameters are computed.
- Optimizer step — the parameters are updated.
- The next batch — the process repeats.
This scheme reflects the main idea of the course: the network does not receive ready-made correct weights. It successively computes predictions, evaluates them and uses the gradients to fit the parameters.
18.5. Final test
-
What is the main role of a neuron's weights?
- To set the correct answers for training
- To determine the contribution of the inputs to the weighted sum
- To measure the loss
-
What provides the non-linearity of a multilayer MLP?
- The number of layers itself
- Activation functions between linear transformations
- Only the GPU
-
What does backpropagation do?
- Computes the gradients
- Changes the weights by itself
- Splits the data into train and test
-
What happens if
zero_grad()is forgotten in an ordinary PyTorch loop?- The weights are reset to zero
- The gradients may accumulate between iterations
- The model automatically switches to the GPU
-
What is the best way to detect overfitting?
- Look only at the train loss
- Enlarge the network at every increase in the error
- Compare quality on the training and on independent validation data
Show answers
- To determine the contribution of the inputs to the weighted sum
- Activation functions between linear transformations
- Computes the gradients
- The gradients may accumulate between iterations
- Compare quality on the training and on independent validation data
18.6. What you should be able to do after the lecture
Before moving on to the next course, it is worth making sure you can do the following on your own:
- explain what an artificial neuron is;
- calculate its weighted sum and output;
- explain the purpose of weights, biases and activation functions;
- perform a forward pass of a small network;
- count the number of parameters of a fully connected layer;
- explain why a network needs a loss function;
- tell a forward pass, backpropagation and an optimizer step apart;
- perform a simple calculation of a gradient and a weight update;
- explain the purpose of epochs, batches and the learning rate;
- distinguish overfitting from normal training;
- explain why a neural network is not necessarily better than boosting;
- read a simple PyTorch training loop and explain the purpose of
zero_grad(),backward()andstep().
If some of the points do not work out yet, that does not mean the lecture has failed. It is especially important to master gradually the computations and the chain of dependencies in backpropagation: we will return to these ideas.
18.7. A bridge to the next course
We have completed the first sequential course in machine learning — from linear regression and optimization to ensembles, gradient boosting and basic neural networks.
Over these 13 lectures we gradually worked through several fundamental principles:
- models are mathematical functions with parameters;
- training is fitting parameters from data;
- a loss function makes it possible to measure the quality of a prediction;
- gradients help determine how to change the parameters;
- the quality of a model has to be checked on data it did not see during training.
In the next course we will be able to go deeper into neural network architectures and see how the general idea of trainable layers is applied to different types of data.
A preliminary sequence for further study:
- CNN (Convolutional Neural Networks) — convolutional neural networks and image processing.
- RNN, LSTM and GRU — sequences and temporal dependencies.
- Attention — the attention mechanism.
- Transformer — the architecture underlying many modern language models.
- Tokenization and the structure of LLMs — how text is represented by numbers and how a language model builds a continuation.
- Pre-training and fine-tuning — how models are created and adapted.
- Evaluation, inference and the practical use of models — how to verify quality and apply trained systems.
This is a preliminary plan, which can be refined according to the programme of the next course.
And the most important thing in conclusion: there is no need to remember every formula right now or to be able to write a whole neural network from scratch without mistakes. It is far more important to understand the general logic and to be able to reconstruct the details gradually by reasoning.
It is now clear that a neural network is not a magic black box. It is a sequence of computations, trainable parameters and mathematical rules. Real study of deep learning begins precisely with this understanding.
Practice in the interactive lab
Three actions for this lecture: see how the optimizer works, change the complexity of the model and work through the loss for classification.
-
See how the optimizer works — open "Descent along the loss function": the ball descends along the loss surface step by step. This is the same logic as in the network's training loop: the gradients set the direction and the learning rate sets the step size.
-
Change the complexity of the model — open "Polynomial degree: overfitting" and move the degree slider: a model that is too simple underfits, one that is too complex overfits. In a neural network the same role is played by the number of layers and neurons, regularization and early stopping.
-
Explain the loss for classification — open "Logistic loss" and compare the loss values for different probabilities: a confident wrong answer is penalized sharply. That is exactly the binary cross-entropy the network uses in the two-class example.
There is no separate demo about neural networks in the lab: these three pages show related ideas — descent along the loss, complexity control and the logistic loss.