ANN
Neural Networks are a big topic. Today I'm going to discuss the fundamentals of Neural Networks.
I'll give references from authoritative sources. So don't hesitate to ask me.
An artificial neural network (ANN) is a series of algorithms that aims to recognize underlying relationships in a set of data through a process that mimics the way the human brain works. Such a system “learns” to perform tasks by analyzing examples, generally without being programmed with task-specific rules.
Global Architecture
Neural networks are organized in several layers:
- Input layer : the input layer neurons receive the information needed to describe the problem to be analyzed;
- Hidden layer : the hidden layer is an intermediate layer that allows neural networks to model nonlinear phenomena. It is said to be "hidden" because it has no direct contact with the outside world. The outputs of each hidden layer are the inputs of the units of the following layer;
- Output layer : the output layer is the last layer of the network; it produces the result, the prediction.

The Perceptron
The perceptron is the first and simplest neural network model: a supervised learning algorithm invented in 1957 by Frank Rosenblatt, a notable psychologist in the field of artificial intelligence.
This network is said to be simple because it has only two layers: an input layer and an output layer. This structure contains only one weight matrix, and all the units of the input layer are connected to the output layer.
The perceptron is a linear classifier for binary predictions; in other words, it can classify or separate data into two categories.


3D representation of linearly separable data
How the perceptron works
First of all, the simple perceptron takes n input values (x1, x2,…, xn) and is also defined by n + 1 constants:
- n synaptic coefficients (or weights: w1, w2,…, wn);
- A bias: a neuron whose activation function is equal to 1. Like other neurons, a bias connects to the neurons of the previous layer through a weight, usually called the threshold.
Then each input value must be multiplied by its corresponding weight (wixi), and the results of these products must be added up in order to obtain a weighted sum. The neuron then produces one of two possible values, determined by whether the result of the sum is lower or higher than the threshold.


The weighted sum can be transformed into the dot product of two vectors, w (weights) and X (inputs), where w⋅ X = Σ Wixi; the inequality can then be solved by moving θ to the other side (the threshold).


Also, remember that the bias is like a neuron whose activation function is equal to 1, so multiplying it by its weight (the threshold) simply means multiplying the threshold by 1. As a result, the common notation replaces the threshold with a variable b (for bias), where b = -θ.


Completing all these steps produces the following architecture:


Schematic representation of the simple perceptron
Once the weighted sum is obtained, an activation function needs to be applied. The simple perceptron uses the Heaviside step function to convert the resulting value into a binary output, classifying the results as 0 or 1.


Graphical representation of the Heaviside step function
The Heaviside step function is especially useful in classification tasks where the input data is linearly separable.
Multi-Layer Perceptron
A Multi-Layer Perceptron (MLP) consists of an input layer, an output layer and one or more hidden layers. So it is no longer a single neural network like the simple perceptron, but neural networks, in the plural. If an MLP has n layers, it has n-1 weight matrices.
In theory, adding enough neurons to the hidden layer can be sufficient to approximate any nonlinear function.
Multi-Layer Perceptron architecture:


Graphical representation of a Multi-Layer Perceptron
A neural network produces a prediction after passing all the inputs through all the layers, up to the output layer. This process is called forward propagation.
Neural networks work the same way as a perceptron. So to understand neural networks, you need to understand the perceptron!
Activation Functions
The activation function, also known as the transfer function, is an essential component of a neural network. In addition to introducing the concept of nonlinearity into the network, it aims to convert the signal entering a unit (neuron) into an output signal (response).
The function gets its name from its biological equivalent, the “action potential”: the excitation threshold that, once reached, results in a neuron response.
It is worth noting that, thanks to the bias, it is possible to shift the activation function curve up or down, which means greater learning opportunities for the network.
There are two types of activation functions: linear and nonlinear.


Linear Activation Function
This is a simple function of the form f (x) = x. The input passes to the output with little or no modification. It is nothing more and nothing less than a case of proportionality.


Graphical representation of a linear function
Nonlinear Activation Functions
Nonlinear functions are the most widely used, and they make it possible to separate data that is not linearly separable. A nonlinear equation governs the correspondence between inputs and outputs.
The main nonlinear functions:
- Sigmoid:
The sigmoid function (or logistic function) is an “S” curve that produces an output between 0 and 1, expressed as a probability.


Definition of the sigmoid function


Graphical representation of the sigmoid function
Being a “smoother” version, it is preferred over the Heaviside step function, but it is not without flaws. Indeed, the sigmoid function is not zero-centered, so negative inputs can produce positive outputs. Moreover, its effect on the neurons is relatively low; the result is often very close to 0 or 1, which leads some of them to saturate. Finally, the exponential function makes the operation computationally expensive.
- Hyperbolic Tangent (TanH):
The hyperbolic tangent is a sigmoidal function similar to the previous one; however, because of its symmetry, it usually gives better results than the logistic function. In fact, the difference is that the result of the TanH function is mapped between -1 and 1. It is generally preferred over the Sigmoid function because it is zero-centered. This function is ideal for multi-layer perceptrons, especially for the hidden layers.


Definition of the hyperbolic tangent


Graphical representation of the TanH function
Apart from this aspect, the TanH function shares the same drawbacks as the Sigmoid function.
- Rectified Linear Unit (ReLU):
The ReLU function helps solve the saturation problem of the functions above. It is the most commonly used.


Definition of the ReLU function


Graphical representation of the ReLU function
If the input is negative, the output is 0; if it is positive, the output is z. This activation function significantly improves network convergence and does not saturate.
But the ReLU function isn't perfect either. If the input value is negative, the neuron can remain inactive, so the weights are not updated and the network stops learning.
Why is this activation function needed?
Without a nonlinear activation function, an artificial neural network, no matter how many layers it has, will behave like a simple perceptron, because summing its layers will only result in another linear function.
Which function should be used?
Is it a regression or a classification problem? If it's classification, is it a binary classification? In the end, there is no single best activation function; it depends on the task at hand.
The Cost Function
To learn, the perceptron must know that it has made a mistake and what answer it should have given. This is supervised learning. To do this, you need a cost function whose purpose is to calculate the error, in other words, to measure the gap between the prediction y_hat and the expected value y. The cost function must therefore be minimized until it reaches its optimum: this is neural network training.
To define the cost function J, the mean squared error can be used:


Mean squared error (MSE)
where:
- m is the number of training examples;
- y is the expected value;
- y_hat is the predicted value.
Once the prediction has been compared with the expected value, the information must be sent back through the neural network, so that it travels back along the synapses and updates the weights. This is nothing more and nothing less than the reverse path of the forward propagation mentioned earlier. It is called backpropagation.
As mentioned earlier, the goal of a Machine Learning algorithm is to find a combination of weights that minimizes the cost function.

Gradient Descent
When there are more weights, and therefore high-dimensional spaces, a problem arises: the Curse of Dimensionality. A naive approach such as brute force can no longer be used. To compute the cost function with a feasible method, it is therefore necessary to use gradient descent, one of the most popular algorithms for performing optimization.
Suppose the cost function J is convex:


Three-dimensional representation of a convex function
The horizontal axes represent the space of the parameters, the weights and the bias, while the cost function J is an error surface above the horizontal axes. The blue circle is the initial cost value. All that's left is to go down, but what's the best way to get there from here?
To answer this question, some parameters, namely the weights and the bias, need to be changed. This will then involve the gradient of the cost function, since the gradient vector naturally points in the direction of the steepest slope. It is important to know that the input values are fixed, so the weights (and the bias) are the only tunable variables that can be controlled.
Now imagine a ball dropped into a round bucket (the convex function); it only needs to reach the bottom. This is optimization. As it descends, it will need to move from left to right to optimize its position.


Starting from an initial position, look at the angle of the slope to draw the tangent at that point: this means computing a derivative. If the slope is negative, the ball moves to the right; if it is positive, it moves to the left.
But something is missing, namely at least one hyperparameter: the learning rate (α). The slope shows the direction to take, but it doesn't say how far the ball should go in that direction. That is the role of the learning rate, which determines the size of each step toward the minimum.
Putting it all together, gradient descent can be defined as follows:


The canonical formula for gradient descent
where:


- θ are the model's parameters (the weight vector);


- ∇ J (θ) is the gradient of the cost function J; in other words, it is the vector containing each of the partial derivatives. We get it by differentiating the function once;
- α is the learning rate (step size), set before the learning process.
Choosing the learning rate is still an open question; the optimal value for a given model on a given dataset cannot be computed analytically. Instead, a good enough learning rate has to be found by trial and error, but keep in mind that it should decrease over time.
Choosing the right value for the learning rate matters, because it affects the learning speed on the one hand and the chance of finding a local optimum (convergence) on the other. If chosen poorly, this value can feed the two main causes of poor performance in predictive models:
- Overfitting: the algorithm fits the training dataset really well, and that is a problem, because it will no longer be able to generalize from the data. With a high learning rate, more distance can be covered at each step, but at the risk of overshooting the lowest point, since the slope keeps changing. Simply put, the loss function oscillates around the minimum and may even diverge;
- Underfitting : setting a very low learning rate makes it possible to move confidently in the direction of the negative slope. A low α is more precise, but computing the gradient takes a long time and leads to painfully slow convergence.


Left: α too small; Middle: good α; Right: α too large.
With a good learning rate and after a few iterations, a suitable minimum should be found; at that point the ball can no longer go any lower.
Finally, the best weights for optimizing the network are determined.
That is what backpropagation is about: knowing the contribution of each weight to the network's total error, and thereby converging on the optimized weight configuration.


Stochastic Gradient Descent
There is a problem, though: gradient descent requires the cost function to be convex. In other words, the curve lies entirely above each of its tangents, and the derivative of such a function is increasing over its whole interval. As shown earlier, it takes this form: ∪. So what about a non-convex function?
This time, suppose the cost function J is not convex:


Three-dimensional representation of a non-convex function
In such a case, following the steepest slope is no longer enough. Understanding the error surface becomes visually more complex, and it has particular features such as local minima and possible saddle points.


The risk, then, is that some iterative algorithms get stuck, slowing backpropagation down considerably, and end up in a position that is not the smallest overall value (the global minimum).
To overcome this problem, it is possible to use stochastic gradient descent (SGD).


Mathematical formula for SGD
Despite appearances, it is faster. It produces more weight fluctuation, which increases the chance of detecting the global minimum instead of stopping at a local minimum.
Indeed, it isn't necessary to test and load the entire dataset into memory only to adjust the weights at the end. Stochastic gradient descent does this after each iteration, making the process computationally lighter. Moreover, standard (or batch) gradient descent is deterministic: if the starting conditions (weights) are always the same, the result will always be the same as well.
I've covered all the important topics related to Artificial Neural Networks. But if anyone wants to know more, or wants to learn about a specific topic, feel free to message me :)