Supervised Machine Learning: how to build your own Neural Network from scratch
Tags: go, tutorial, ai, machinelearning
Published: 2023-12-03 21:15:14

## Foreword

This article aims to provide a simple, minimalist and baby-steps introduction to how **Supervised Machine Learning** works. It will explain the underlying idea, the mechanics, and the reasons behind its functionality. Additionally, a concrete and minimalist example with code will be available at the end as a reference. Last, but not least, it does not mean to be a replacement of academic articles on this topic, but an introductory material for the ones who love math and coding.


## What is Machine Learning?

In brief, as you can see [in this nice article from MIT](https://mitsloan.mit.edu/ideas-made-to-matter/machine-learning-explained), “Machine learning is a subfield of artificial intelligence, which is broadly defined as the capability of a machine to imitate intelligent human behavior. Artificial intelligence systems are used to perform complex tasks in a way that is similar to how humans solve problems”. We can divide this AI field in three categories: **Supervised Learning (and this article will address it), Unsupervised Learning and Reinforcement Learning.**


## Supervised Learning: an overview

Supervised learning is a branch of machine learning where computers are trained by being presented with examples of desired behavior. It mimics the process of a teacher guiding a student in learning a subject, with continuous checks on the student’s progress.

For such type of Machine Learning, the algorithm is trained on a dataset that includes both input data and corresponding correct output or “answers.”

A funny example if this is the App [“Hot dog and Not hot dog”](https://www.youtube.com/watch?v=tWwCK95X6go) from the Silicon Valley TV Serie in which the character Jian Yang creates an app able to tell whether or not a picture is from a hot dog or not. For sure that’s not the best use case for supervised machine learning, in our day to day life we have much more useful uses like spam filters, product recommendations, fraud detection and so on.

Some methods used in supervised learning include **neural networks, naïve bayes, linear regression, logistic regression, random forest, and support vector machine (SVM)**.

As you can see, even being a subfield of Artificial Intelligence, supervised learning also has its own subtopics. In next section we’ll address how supervised learning works using neural networks.


## The fundamental pieces of Neural Networks: Neurons and the Universal Approximation Theorem

Dear reader, I must warn you that math is a passion of mine, and I’m thrilled as I write this section. So, proceed at your own risk :)

As previously discussed, supervised learning works by inputting some data into an algorithm and checking if the outcome matches the expected result. When implementing supervised learning using Neural Networks the output computation will be performed as the input passes through the [“neurons”](https://en.wikipedia.org/wiki/Artificial_neuron) of the net. A neuron in this case is essentially a function that receives one or more inputs, such as a vector containing values, does some calculation and provides a result. Each input of such neuron will have a weight attached to it to simulate the [synapse process](https://en.wikipedia.org/wiki/Synapse). After summing all (inputs * weights) plus a bias value the neuron applies the result into a activation function which is in charge of introducing non-linearity into the network, enabling it to learn and approximate complex relationships in the data. To help you visualize it check bellow image:


![Image took from https://www.researchgate.net/profile/Douw-Boshoff/publication/328733599/figure/fig2/AS:734165188218886@1552050029499/The-structure-of-the-artificial-neuron.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqqtgsmf1vzn5hb5orue.png)

In above image each “x” represents an input value fed into the neuron and each “w” is a weight applied to an input. The neuron sums all (x*w) with the bias ( theta letter) and the output of it is applied into the f(x). Mathematicaly we can describe it as the following:

![Neuron equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c1j0r8wbwyahwbm0te0y.png)

Where yk is the output of the kith neuron and f is an activation function, for instance it could be a [sigmoid function](https://en.wikipedia.org/wiki/Sigmoid_function). Above equation is enough to explain how a neuron works, but it is **doesn’t explain why it works.**

To grasp **why** it operates, let’s revisit the fundamental concept of supervised learning: we possess a labeled dataset that serves as the training data for a Neural Network, allowing it to comprehend the underlying patterns. Consider the following example: we aim to create a function, denoted as f(x), which, based on the hours of study by a computer science student, predicts their linear algebra test score. We assume that the student has already taken three tests, and we have their corresponding scores:


![Table where left column shows the hours of study and right column the test score.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzqt8082t1fu31m518jd.png)


Generalizing the idea we get:


![Table generalizing the idea of the presented problem.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbqczrltbvvhiljv2fi7.png)


Thus, our job here is to find a function f(x) so that: f(xi) is very close to yi, where i = 0,1,2…n. To do so we define a family of functions F that could be a good fit for this problem, like **linear regression**:


![Family of functions we need.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6abpy8jcrxduyqdceuw.png)


If, and only if, there really exists a function that could represent the relation between xi and yi we can take this as an [approximation problem](https://umanitoba.ca/science/research/mathematics/approximation-theory#:~:text=Learn%20more-,Approximation%20theory,-Approximation%20theory%20studies): how can we find an element from F as close as possible from our desired function?

We don’t all have corresponding yi for all xi, only a few samples where for sure f(xi) = yi. Thus, the best we can do is find a function that properly fits the relation between xi and yi, generalize unknown examples and is computationally possible to find. In other words, we want an element from F that minimizes the [supremum norm](https://en.wikipedia.org/wiki/Uniform_norm):

![The best approximation.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ik699tvcwvcs072oemw.png)
The best approximation.


![The supremum norm.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3qi6urpa9snrow8u52yg.png)
The supremum norm.


As we want the best fit between input data and output as possible we need to find the minimal || f — u||. The supremum norm is a mathematical tool that helps us measure the maximum vertical distance between the true function and our approximation across all possible x values. **By minimizing this supremum norm, we seek a function within F that provides the closest possible approximation to our desired function**.

A proof that the mathematical Neuron definition I’ve shown above is capable of finding the minimal || f — u|| is given by the [Universal Approximation Theory (UAT)](https://www.deep-mind.org/2023/03/26/the-universal-approximation-theorem/#:~:text=provide%20an%20answer.-,Universal%20Approximation%20Theorem), and this [quick video](https://www.youtube.com/watch?v=O45AaRPQhuI) shows why Neural Networks are able to learn pretty much any function due to the UAT.

The overall process is defining a small ε value that will control how closely the elements of F will fit our model. **The smaller ε is more accurate our Neural Network will be**. Once ε is defined we start searching a Neural Network in which the outputs are close to our desired f, bellow image (tries) to show it:


![Neural Network trying to fit the model.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ancv0azpi4h833w5fh5.png)

Neural Network trying to fit the model.

Although the UAT proves that such function u(x) (an element of F) exists **it doesn’t tell us how to find it** and the **required amount of neurons needed to fit _f(x)_ might be really big**, due to that finding an optimal Neural Netwok in practice is a challenge. Besides of it there are other points to take care while chasing for a Neural Network, such as avoiding **overfitting** and **underfitting**, the **quantity** and **quality** of data required, computational resources available and so on.

Such challenges will be addressed in next section, by assessing a simple problem as example and showing one possible way to find an optimal approximation (a Neural Network that fits the behavior of an f).


## Defining a concrete problem as example to solve and planning data architecture

We want to create a model that based on the amount of hours of study and the amount of hours of meditation of a computer science student we find its linear algebra test score. We can also assume that the student has already attempted to perform three tests and we have their respective score:



![Table showing a simple dataset of the problem we are trying to solve in this article. First two columns are, respectively, the hours of sleep and hours of meditation. The third one represents the test score.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gar4zbgu0msulda35jbg.png)

Table showing a simple dataset of the problem we are trying to solve in this article. First two columns are, respectively, the hours of sleep and hours of meditation. The third one represents the test score.

If we assume that the model we are trying to create is a function, then the _hours of sleep_ and _hours of meditation_ are inputs of such function, while _score_ is the output. Let’s define the vector X as the input of our model and Y as the output of it. Just to clarify it, if _f(x)_ represents our Neural Net and one possible input is _X=[6,5]_ (where 6 is the hours sleept and 5 hours of medidation) then _f(X)=[8]_ (where 8 is the test score). The same way would be if _X=[7,4]_ and _f(X)=[7]_ and also if _X=[7,5]_ and _f(X) = [8]_. A clever way to approach how we group inputs and outputs would be using matrices of them, then we would have the input matrix:


![Matrix with the Neural Network inputs.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ss6eho9o57x7mwnx4qhu.png)

Matrix with the Neural Network inputs.

Each line on above matrix X is a valid input where the left column represents the hours of sleep and the right column the hours of meditation. And then _f(X)_ will be:


![Matrix with the Neural Network outputs.
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvlfworo42wggntxmv1g.png)

Matrix with the Neural Network outputs.

Each line on above matrix Y is a valid output of the Neural Network.

One thing that must be pointed is that **both matrices data must be scaled to ensure that the Neural Network handles standardized units**. One way to achieve it is using [Min-max normalization](https://www.oreilly.com/library/view/hands-on-machine-learning/9781788393485/fd5b8a44-e9d3-4c19-bebb-c2fa5a5ebfee.xhtml#:~:text=Min%E2%80%93max%20normalization).

With the problem stated and input features known we can plan how the Neural Network structure will be. As our **input data has two dimensions** we need an input layer with two inputs, and as **our result is a single number** our network has one output only. Thus, the basic structure required for our Neural Network is the following:


![The basic structure of our Neural Network.]
(https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6n39ekil9yh2xdzui28k.png)

The basic structure of our Neural Network.

To complete the structure we need to plan the **hidden layers** of it. The amount of inner layers may vary depending on the problem the Neural Network needs to solve. In fact, real world examples could have millions of hidden layers. For the sake of simplicity we’ll stick if one hidden layers with 3 neurons only, and bellow image image shows it:


![The completed structure of our Neural Network.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wacv2fkhw04xfhc3iqti.png)


Some important things missing on image above are the **neuron weights**. We will assume that the weights of first layer are always 1 and ignore them, so applying them on the second and third layer we get:


![The completed structure of our Neural Network with Neuron weights.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b2xyj25wusrjn0rv4e5v.png)

The completed structure of our Neural Network with Neuron weights.

In case you didn’t get the weight notation take a look at bellow image:


![The completed structure of our Neural Network with Neuron weights.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zvmcduzyzws8geeiboam.png)

In next section we will properly address how the Neural Network model is built based on this proposed structure.

## The Neural Network model in action: forward process

The process of acctually using the Neural Network is called forward process. Here the Neural Network receive the inputs, pass all of them through the weights, apply the sum into the activation function and proceed to next layer.

Let’s start checking how the process works on the second layer. Each neuron inside of second layer will receive the input from all neurons from first layer and apply a weight on it. Once all inputs are weighted we will get the following:


![Neural Network with all second layer’s input weighted.
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vl83bj340u7yhiib8u6l.png)

Neural Network with all second layer’s input weighted.


Considering that we placed all input values into the matrix X and it is a 3x2 matrix, if we place all weights also on a matrix 2x3 we will end up having a matrix containing the results of all (inputs * weights). Let the weight matrix of second layer be:


![Matrix with second layer weights.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/87pd11fxaphu94x1w6yq.png)

Then, the product:


![Matrix product.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zuy1hxeg53js099huy9.png)

Will be:


![Matrix product.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it75muye53r8ubjqbvrj.png)

We’ll call the above product as:


![Matrix product.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tv8vt4y2jfrd898cy9zf.png)

Even before you ask: we’ll address the bias in next sections.

Once we calculated the weighted sum for each neuron we can now apply the activation function element wise on above matrix to calculate the output of second layer. For this problem, the activation function used will be the sigmoid:


![Sigmoid activation function.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/peuhjs94cuvu021e5evz.png)

Sigmoid activation function.


Thus, the second layer output can be defined as:


![Matrix containing second layer output.
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txsqnfvvm8l0cgtsxbue.png)

Matrix containing second layer output.

Once second layer is finished we proceed to the third layer with exact same process and with the second layer output being the third layer input. Let’s start by seeing the third layer weights:


![Matrix carrying the weights of third layer.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7z1vh2r2i1t1l71002w.png)

Matrix carrying the weights of third layer.

Multiplying the second layer output with third layer weights will gives us:


![Matrix values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7gy89pib1dzks0grbcb.png)



And to get the output of third layer we apply the sigmoid on this product:


![Matrix containing third layer output.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bnqehd2zll2v0z5wr1qs.png)

Above matrix has shape 3x1 and each line represents the predicted test score.

With the equations discussed in this section we are able to predict the test score based on the amount of study and medidation hours. But such predictions will probably be absolutely wrong :). **This is due to the fact that the weights from our layers once we create the Neural Network are defined randomly**. Thus, the Neural Network won’t be useful on helping us predicting the test score. To adjust the Neural Network we need a way to find proper values for our weights while we measure the accuracy of outputs. This will be addressed in next section.

## Assessing the Neural Network error: error cost

In order to improve the Neural Network accuracy we need to know how wrong the outputs are. To do so we’ll use a **cost function** (or loss function). **The cost function will measure the performance of our machine learning model quantifying the error between the prediction and expected value**. A good way to address the cost function is using the [Mean Squared Error (MSE)](https://www.statisticshowto.com/probability-and-statistics/statistics-definitions/mean-squared-error/) (soon it will be explained why such approach is effective and smart). In mathematical terms we can define MSE by the following:


![The error of our Neural Net](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kix4v4v1inaof4onhqal.png)


The error of our Neural Net

On above equation, E is the global error of our Neural Network,_y'_ is the expected output for one input and y is the received output for one input. In the case you are wondering why we placed the term 1/2: it was done for convenience during derivatives operations as it simplifies the computation of gradients and it doesn’t alter the fundamental meaning of Mean Squared Error (MSE), which remains a measure of the average squared difference between predicted and actual values.

Being brief, **training a Neural Network means minimize its cost function**. Our cost function is a function of the Neural Network input and its weights, and in case this is not clear we can expand E:


![Expanding the Neural Network error cost.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yrmzjv2wc1xvn8l3219o.png)

We just don’t have control over the X param, only the “client” of the Neural Network does. **Thus, if there is something we can change in order to adjust the cost function is the Neural Network weights**. But how can we adjust the weights? Brute force?


If we consider for a while a hypothetical Neural Network containing one weight only in which the “proper” value for it can be found on a set of 10k numbers, a brute force approach would take in the worst case 10k “checks” to find the proper values. If we also assume that each “check” takes 2 milliseconds (ms), then, the overall process would take 20 seconds. Anoying but still feasible.


![How the error cost would look like for one neuron.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqgg1nh5apjugmateie4.png)

It would takes us 10k times executing the forward process, calculating the error cost to, in the end, find the minimal error value. If we expand it to two neurons and we assume that this new neuron also has the proper value on a search space of 10k numbers, in such scenario, our search would require 100000000 iterations (10k * 10k), and if we also keep the check time of 2ms it would take 200,000 seconds or approximately 56 hours :)


![How the error cost would look like for two neurons.
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k35myruryhf04dkvl0xn.png)


The conclusion here is obvious: **the more neurons the Neural Network has, more expensive its training will be**. This phenomenon is called [Curse of dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality), which is a serie of challenges and issues that arise when dealing with data in high-dimensional spaces.

As we could see, **bruce force solutions are not feasible here**. We need a way to find a shortcut between all the available numbers in the search space to the ones that gives us the minumum of error cost function. **We could achieve it by kwnowing the direction that E decreases from one inspected point**. Let’s consider the scenarion with one single neuron again to visualize it. Consider bellow image where point P(wi, E(wi)) is a known point in the availble search space and we know that moving to the right decreases E while moving to the left increases E. Then, as we want to minimize E we can move to the right.


![Error and weight](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xf6wo06n8ka7v2rpk94v.png)

We can extend this ideia by asking: how E behaves when the weights changes? And fortunely there is an awesome tool to helps us finding it out called calculus, specifically the the derivatives. As mentioned above, E is a function of both Neural Network inputs and the weights, but we control only the weights. **Thus, to know how E behaves by modifying weights we need to calculate the derivative of E with respect of the weights**. If derivative of E with respect to the weights is positive we can say that E is increasing, otherwise it is decreasing. For the case of our Neural Network, which has more than one layer, we need to perform a parcial derivative of E with respect to each layer weight.

**By knowing the direction that E decreases we can iteratively look for lower values of E, ignoring points where it increases optmizing the search time.** Check bellow image to visualize it:


![A clever way to find lower values of E.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/belqdol93pysi3kbz11o.png)



The method described above is called [Gradient Descent](https://towardsdatascience.com/gradient-descent-algorithm-a-deep-dive-cf04e8115f21#:~:text=Gradient%20descent%20(GD)%20is%20an,e.g.%20in%20a%20linear%20regression).), which is a way to minimize the cost function by adjusting the model params in such a way that the cost decreases faster. **It works by calculating the gradient (slope) of the cost function with respect to the parameters and updating them in the opposite direction of the gradient, moving towards the minimum of the cost function**. We basically repeat this process until the cost function reaches the minimal value.

An important thing to point is that **we can use Gradient Descent for our Neural Network because our error cost function has a convex shape**, which ensures that E always moves on “the same direction”. The convex shape is a consequence of using the MSE, which is a quadratic function :)


If our cost function didn’t have such convex shape it could mess our Gradient Descent execution, and our search could end up being stuck on a **local minimum** rather than the **global minimum**. Check bellow image:


![Showing the problem of local and global minimum.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gq8291b60fub0rwr01ix.png)

It also worth poiting that for some scenarios the shape of cost function doesn’t matter, for instance in the case of using [Stochastic Gradient Descent](https://www.analyticsvidhya.com/blog/2020/10/how-does-the-gradient-descent-algorithm-work-in-machine-learning/#:~:text=for%20large%20datasets.-,Stochastic%20Gradient%20Descent,-Stochastic%20gradient%20descent), where you use one input example at time. In our case we’ll be using [Batch Gradient Descent](https://www.analyticsvidhya.com/blog/2020/10/how-does-the-gradient-descent-algorithm-work-in-machine-learning/#:~:text=used%20in%20practice.-,Batch%20Gradient%20Descent,-Batch%20gradient%20descent), where rather than one training example at time we’ll use a set of it.

## Backpropagation: adjusting weights using Gradient Descent

To perform the Batch Gradient Descent process to update the Neural Network weights we need to calculate the partial derivative of E with respect to our weights from second and third layer. Let’s start with third layer.


![dEdW3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fc2z3ywaynowusff5b53.png)

As the [derivative of a sum is the sum of derivatives](https://www.youtube.com/watch?v=fIOMrpVLtBs) we can move the inner sum to the outside:


![Applying derivative rule](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0m7lv6lj6mulbehcub3d.png)

For simplicity, let’s remove the outter sum and focus on the derivative part of an isolated case. That said, if we apply the [chain rule](https://www.youtube.com/watch?v=H-ybCx8gt-8) we would get:


![Chain rule](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/279lo8vj2wxklvb5pjsf.png)

As the term _y’_ is the expected output then it is a constant. Resolving the equation we get:


![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9hw9mfhcorngn3yowdv0.png)

If we remember that y (the output of Neural Network) is the result of the activation function applied on _v(3)_ and apply the chain rule again we get:


![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/982x8mzeqqhrq4w0yhbz.png)

The derivative of second term is the derivative of our activation function S, which is a sigmoid. The derivative of S is:


![Sigmoid prime](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inlimfxwapswk967pm4a.png)

Applying it we get:


![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u5888myp4sdr2ypzcc8r.png)

This part is a little bit tricky due to matrix dimensions, but don’t give up :)

A few iterations ago we have removed the Σ from our calculations to look to the problem isolatedly and now we can go back to it. Both matrices y’ and y have same dimentionality and the subctration between them can occur without any problem. The interesting part is what to do with S’, as it has the same dimension of the matrix subtraction. If we look closely on how this product would happen if we were applying the Σ summation we could see that this multiplication would be done element-wise. Thus, to represent it in the form of matrices mutiplication we can use the [Hadamard Product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)). Adding the proper notation to it we get:


![Applying notation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7nae9x98hdlgqv8vp99.png)


The last derivative to solve is the third term, which result is the Y(2). As in this step we are **propagating the error backwards to the weight that generated it** we need to mutiply the elements of Y(2) to its proper **back propagating error**. We can do so by multiplying the transpose of Y(2) by the first two terms:


![Solved equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yop8wwa0a7qkcd405qca.png)


And we are done with third layer! Proceeding to the second layer, the overall process is the same, the difference is that now we’ll perform the derivative of E with respect to W(2). We can start with:


![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6t2t5q7f20hhk7y3en7n.png)


Solving it we’ll have:


![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifcmco4r2dhnecf4t4vp.png)


Applying the chain rule we get:



![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4n12os8uba8gsv1wmit.png)

The first two terms are already known:


![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eq6nla50cvy9w37mzqtp.png)


And if we keep applying the chain rule:


![Solving equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pupmxit9koj3rtob6tit.png)

If we reorganize some terms on above equation and also on the one for the third layer we’ll see they have a product in common:


![Solved equations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o97gmmjhtayj617vpffx.png)


This product is the back propagating error of third layer. We can add the following notation to it:


![Solved equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/psizied2jf8dlqrhh2iw.png)

We can rewrite the equation for second layer to be the following:


![Solved equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sz8e1buzc0tcheurorn.png)

If we extend the idea, we can also define the back propagating error to the second layer and we’ll have the following:


![Solved equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agtj066ir99ttikyia3n.png)

Once we finished the equations for both second and third layer we are able to adjust the Neural Network weights by subtracting them with each respective gradient component. **We need to subtract because the gradient points in the direction of the steepest increase of the error, to reduce the error we need to move in the opposite direction of the gradient**. Thus, by subtracting we are adjusting the weights in the direction that decreases the error.

We can also mutiply our gradient component for a small scalar to control the size of the steps taken during each iteration of the optimization process. **This scalar is useful because it controls the size of the weight adjustments, ensuring that the optimization process is stable and converges to a meaningful solution**. This scalar is often called **learning rate**. Finding a proper learning rate is important because **a too-large learning rate can cause the optimization process to oscillate or diverge, potentially missing the minimum**. On the other hand, **a too-small learning rate can make the convergence very slow, requiring many iterations to reach the minimum**. By doing some researches we can find some suggestions on how to configure out the learning rate, one common suggestion is [something between 0.01 and 1.0](https://www.andreaperlato.com/theorypost/the-learning-rate/#:~:text=The%20range%20of%20values%20to%20consider%20for%20the%20learning%20rate%20is%20less%20than%201.0%20and%20greater%20than%2010%5E%2D6.%20A%20traditional%20default%20value%20for%20the%20learning%20rate%20is%200.1%20or%200.01%2C%20and%20this%20may%20represent%20a%20good%20starting%20point%20on%20your%20problem).


Thus, to update weights matrices we do the following:


![Solved equations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gp8u079hxgqv25zguhf0.png)

Where α is the learning rate. One thing worth point specifically during the implementation of such step is to **test the implementation to ensure it was well done**. Any implementation glitch on this step would lead to wrong Neural Network results and problems very hard to debug :)


## Training the Neural Network

Once we have designed the Neural Network structure, planned its forward process and the backpropagation process we are able to effectively train it. The idea is pretty simple: we define a param to controll how many “iterations” the training will have, usually this param is called [epoch](https://www.simplilearn.com/tutorials/machine-learning-tutorial/what-is-epoch-in-machine-learning#:~:text=EXPLORE%20PROGRAM-,What%20Is%20Epoch%3F%C2%A0,-An%20epoch%20is), and also the already mentioned **learning rate**. The learning rate, the amount of epochs and the number of layers are examples of what we call [hyperparameters](https://towardsdatascience.com/what-are-hyperparameters-and-how-to-tune-the-hyperparameters-in-a-deep-neural-network-d0604917584a). Once we define such numbers the process goes like: **for each epoch, execute the forward process, compute the error between the expected values and received values, calculate the gradient descent and update the weights**. A very high level algorithm would be:

![A simple way to train](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htol84qpew6ah12p4p8l.png)

With a reasonable amount of data with proper quality, time and computer power, above process will do the job, but there are some pitfalls during such process, specially for Neural Networks with a much bigger number of layers. For instance, finding a proper learning rate is a non trivial task and a bad weights initialization can result slow convergence or even convergence to suboptimal solutions. There are alternatives that can be explored such as [BFGS technique](https://medium.com/codechef-vit/why-bfgs-over-gradient-descent-3ecc3e7ffd), as it can perform a faster convergence and does not requires a manual definition of the learning rate.

Now we are missing to address two points to complete our basic knowledge about Neural Networks: bias and regularization. We’ll discuss them in next sections.

## Bias: enhancing flexibility

One component that so far we skipped is the bias on Neural Networks. An important job it does is giving to the Neural Network the hability to learn different constants for each neuron, **which is crucial for fitting diverse patterns in the data**. It also helps Neural Networks to model nonlinear relationships. Moreover, it allows neurons to be “activated” even when the weighted sum of inputs is below zero, and this is important for modeling situations where certain features may not contribute much to the output individually but still play a role when combined with other features.

In order to introduce the use of bias in our model we might need to adjust the found equations a little bit. The first adjustment is on how we calculate the weighted input, now we need to add a matrix B containing the biases:


![Adding Bias](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sf3gz8cnszyiqzozdpn6.png)


And we also need to update _B(2)_ and _B(3)_ during the backpropagation. The ideia is the same applied to weights, so if we start with _B(3)_:


![Solving equations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qi85jx0heb950u7szft0.png)


And to update B(3) we do:


![Solved bias](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k9sn5m2i2i1gdh3n4pnc.png)

For B(2) we also do the same process, and due to that we can ommit some parts:


![Solved bias](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3fir86l9s9bh998ewkvn.png)

And to update it:


![Solved bias b2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ih0rf6syb32c31dbz7l.png)

Now we can finally move to last step :)


## Overfitting: we can’t ignore the noise!

Let’s assume that in a few days the same student will have another linear algebra test, and it is hopping to pass it now :). So the student uses our Neural Network to find a proper combination of hours of study and meditation to succeed on the test. It concludes that a score 7 is enough and testing based on the vector X=[7,4], which also is record from its previous test, it decides to study for 7 hours and medidate for 4. Once the test score is informed it sees it scored 5 :(

There can be several reasons for the model predict such wrong score, like the student missing to review a topic in which the test focused more, the student having headache during the test, or even back luck.

The important point here is the **data we use to design our model is just a perception of a fact, but between the fact _per se_ and our observation there is noise. In other words, there are other factors that influence the test score, and some of them we might not even be aware that they exist**. If a model doesn’t take it into account the Neural Network can endup having overfitting issues, which is when the Neural Network performs good with training data but badly with unseen data.

Overfitting verification is a must have during the Neural Network training and one interesting way to do so is split the training data in two parts: a bigger one to train the Neural Network while iterating through some epochs, and a smaller one to evaluate if the training caused an overfitting.

To avoid having such problems we can introduce a form of regularization that will discourage overly complex models with excessively large parameter values. Common regularization techniques are [Ridge and Lasso regularization](https://www.analyticsvidhya.com/blog/2022/08/regularization-in-machine-learning/#:~:text=overfitting%20or%20underfitting.-,Regularization%20Techniques,-Ridge%20Regularization), in our approach we’ll use the Ridge method. To do so we need to adjust how we calculate the error cost E and the gradient components. For the error cost we can do:


![Regularization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y637ytlk43uwzsapfqie.png)

On above equation, the right added term can be interpreted as a **penalty for complex models**. The β is a regularization hyperparameter that helps us to control the relative cost. Higher β implies in bigger penalties for higher model complexity, resulting in less overfitting. We also are multiplying the left term by 1/n where n is the amout of input samples, thus the number of rows of X. This term is important as it ensures that the regularization penalty is not overly influenced by the size of the dataset. The regularization term involves summing up the squared weights across all parameters. Without normalization, this sum would grow with the number of examples in your dataset. By dividing by the number of examples we ensure that the regularization term is on a consistent scale, regardless of the size of your dataset. If we don’t normalize it, the regularization term might dominate the loss term in the objective function, especially for large datasets. This could lead to the optimization process being overly sensitive to the regularization term, potentially overshadowing the impact of the actual loss term.

About the gradient components we can do:


![Solved equation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/guh652ttj1qcjrzypicc.png)

And that’s it :)

## Summary

We went through a lot of points in deep details, so let’s wrap it up like a check list of “what to take care while creating a neural network to solve a supervised machine learning problem”.

### 1. Understand the problem

- What is the problem we are trying to solve?
- What are the inputs of the model we need to create?
- What are the outputs of the model we need to create?

### 2. Neural Network topology

- How many dimensions our input layer requires?
- How many dimensions our output layer requires?
- Which hyperparameters needs initialization?
- How do we initialize weights? Random values?
- How do we initialize biases? Random values?
### 3. Training data
- Which amount of data do we need to train the model?
- Does the training dataset requires cleaning?
- How much of the dataset will be used for training and how much to check the training?
- How can we check if we have overfitting problems?

## Reference Code

I put a minimalist implementation of a Neural Network to solve the problem of the student trying to pass the linear algebra test, you can see the code on [my Github repository](https://github.com/buarki/supervised-machine-learning).


## Key References

- [Approximation by Superpositions of a Sigmoidal Function](https://web.njit.edu/~usman/courses/cs675_fall18/10.1.1.441.7873.pdf); G. Cybenkot.

- [The Universal Approximation Theorem](https://www.deep-mind.org/2023/03/26/the-universal-approximation-theorem/); Alexander.

- [Machine learning, explained](https://mitsloan.mit.edu/ideas-made-to-matter/machine-learning-explained); Sara Brown.


This article was originally posted on my personal site: https://www.buarki.com/blog/ml-supervised-learning