Artificial Intelligence. Implementing Ellipse Classification with Dense Neural Networks in C and Octave
.
1. Abbreviation
AI – Artificial Intelligence
Batch (or deterministic) Gradient Method – Classical Gradient Descent using the full training set
SGD Optimizer / Method – Stochastic Gradient Descent
Mini-Batch SGD Optimizer / Method – Stochastic Gradient Descent using a mini-batch (the gradients are averaged over the examples in the mini-batch)
Momentum Optimizer / Method – Stochastic Gradient Descent with Momentum
Adam Optimizer / Method – Adaptive Moment Estimation
\( lr = \eta = 0.001…0.1 \) – learning rate (1)
\( gradient(P) = G_{P} = \nabla_{P} \mathcal{L} \) – gradient of the Loss Function with respect to parameters P (2)
TP – true positive: the classifier correctly assigned the object to the class under consideration
TN – true negative: the classifier correctly states that the object does not belong to the class under consideration
FP – false positive: the classifier incorrectly assigned the object to the class under consideration
FN – false negative: the classifier incorrectly states that the object does not belong to the class under consideration
Accuracy – the ratio of correct recognitions to all measured data. Good training result: 0.95 —1.0
\( \displaystyle Accuracy = \frac{TP + TN}{N} = \frac{TP + TN}{TP + TN + FP + FN} \) (3)
Error Rate – the ratio of incorrect recognitions to all measured data. Good result: 0 – 0.05
\( \displaystyle ErrorRate = \frac{FP + FN}{N}
= \frac{FP + FN}{TP + TN + FP + FN}
\) (4)
TPR – true positive rate. Shows the ratio of correctly classified objects of a class to the total number of elements of that class. Good result: 0.9 — 1.0
\( \displaystyle
TPR = \frac{TP}{TP + FN}
\) (5)
Precision – shows the fraction of correctly classified objects among all objects that the classifier assigned to this class. Good training result: 0.9 — 1.0
\( \displaystyle
Precision = \frac{TP}{TP + FP}
\) (6)
Specificity – shows the ratio of correct classifier responses to the total number of objects outside the class. In other words, how often the classifier correctly does not assign objects to the class. Good training result: 0.9 – 1.0
\( \displaystyle
Specificity = \frac{TN}{FP + TN}
\) (7)
FPR – false positive rate. Shows the fraction of incorrect classifier responses relative to the total number of objects outside the class. In other words, how often the classifier is mistaken when assigning an object to a class. Good result: 0.0 — 0.1
\( \displaystyle
FPR = \frac{FP}{FP + TN}
\) (8)
.
MCE – Mean Cross-entropy Error
Mean Loss value for the cross-entropy error function. Good result: 0.0 – 0.2
\(
\mathcal{L}_{\text{mean, CE}} = -\frac{1}{N} \sum_{n=1}^{N}\Big(y^{(n)} \cdot \log_{e}(\hat y^{(n)}) + (1-y^{(n)}) \cdot \log_{e}(1-\hat y^{(n)})\Big)
\) (9)
where
N — size of the training array or test array
.
MSE – Mean Squared Error
Mean Loss value for the squared error function. Good result: 0.0 – 0.2
\(
\mathcal{L}_{\text{mean, SE}} = \frac{1}{N} \sum_{n=1}^{N} \left( \hat{y}^{(n)} – y^{(n)} \right)^2
\) (10)
where
N – size of the training array or test array
.
Multiplication of two matrices of sizes n x k and k x m, resulting in an n x m matrix:
\(
A\cdot B
=
\begin{bmatrix}
a_{11} & a_{12} & \cdots & a_{1k} \\
a_{21} & a_{22} & \cdots & a_{2k} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} & a_{n2} & \cdots & a_{nk}
\end{bmatrix}
\cdot
\begin{bmatrix}
b_{11} & b_{12} & \cdots & b_{1m} \\
b_{21} & b_{22} & \cdots & b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
b_{k1} & b_{k2} & \cdots & b_{km}
\end{bmatrix}
=
\)
\(
=
\begin{bmatrix}
\displaystyle\sum_{p=1}^{k}a_{1p}b_{p1} & \displaystyle\sum_{p=1}^{k}a_{1p}b_{p2} & \cdots & \displaystyle\sum_{p=1}^{k}a_{1p}b_{pm} \\[1em]
\displaystyle\sum_{p=1}^{k}a_{2p}b_{p1} & \displaystyle\sum_{p=1}^{k}a_{2p}b_{p2} & \cdots & \displaystyle\sum_{p=1}^{k}a_{2p}b_{pm} \\[1em]
\vdots & \vdots & \ddots & \vdots \\[0.5em]
\displaystyle\sum_{p=1}^{k}a_{np}b_{p1} & \displaystyle\sum_{p=1}^{k}a_{np}b_{p2} & \cdots & \displaystyle\sum_{p=1}^{k}a_{np}b_{pm}
\end{bmatrix}
\) (11)
.
Addition of two matrices of the same size:
\(
A + B =
\begin{bmatrix}
a_{11} & a_{12} & \cdots & a_{1m} \\
a_{21} & a_{22} & \cdots & a_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} & a_{n2} & \cdots & a_{nm}
\end{bmatrix}
+
\begin{bmatrix}
b_{11} & b_{12} & \cdots & b_{1m} \\
b_{21} & b_{22} & \cdots & b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
b_{n1} & b_{n2} & \cdots & b_{nm}
\end{bmatrix}
=
\)
\(
=
\begin{bmatrix}
a_{11} + b_{11} & a_{12} + b_{12} & \cdots & a_{1m} + b_{1m} \\
a_{21} + b_{21} & a_{22} + b_{22} & \cdots & a_{2m} + b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} + b_{n1} & a_{n2} + b_{n2} & \cdots & a_{nm} + b_{nm}
\end{bmatrix}
\) (12)
.
Element-wise (Hadamard) multiplication of two matrices of the same size:
\(
A \odot B =
\begin{bmatrix}
a_{11} & a_{12} & \cdots & a_{1m} \\
a_{21} & a_{22} & \cdots & a_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} & a_{n2} & \cdots & a_{nm}
\end{bmatrix}
\odot
\begin{bmatrix}
b_{11} & b_{12} & \cdots & b_{1m} \\
b_{21} & b_{22} & \cdots & b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
b_{n1} & b_{n2} & \cdots & b_{nm}
\end{bmatrix}
=
\)
\(
=
\begin{bmatrix}
a_{11}\cdot b_{11} & a_{12}\cdot b_{12} & \cdots & a_{1m}\cdot b_{1m} \\
a_{21}\cdot b_{21} & a_{22}\cdot b_{22} & \cdots & a_{2m}\cdot b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1}\cdot b_{n1} & a_{n2}\cdot b_{n2} & \cdots & a_{nm}\cdot b_{nm}
\end{bmatrix}
\) (13)
.
Element-wise division of two matrices of the same size:
\(
A \oslash B =
\begin{bmatrix}
a_{11} & a_{12} & \cdots & a_{1m} \\
a_{21} & a_{22} & \cdots & a_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} & a_{n2} & \cdots & a_{nm}
\end{bmatrix}
\oslash
\begin{bmatrix}
b_{11} & b_{12} & \cdots & b_{1m} \\
b_{21} & b_{22} & \cdots & b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
b_{n1} & b_{n2} & \cdots & b_{nm}
\end{bmatrix}
=
\)
\(
=
\begin{bmatrix}
\frac{a_{11}}{b_{11}} & \frac{a_{12}}{b_{12}} & \cdots & \frac{a_{1m}}{b_{1m}} \\[1em]
\frac{a_{21}}{b_{21}} & \frac{a_{22}}{b_{22}} & \cdots & \frac{a_{2m}}{b_{2m}} \\[1em]
\vdots & \vdots & \ddots & \vdots \\[0.5em]
\frac{a_{n1}}{b_{n1}} & \frac{a_{n2}}{b_{n2}} & \cdots & \frac{a_{nm}}{b_{nm}}
\end{bmatrix}
\) (14)
.
Matrix transpose:
\(
A^T
=
\begin{bmatrix}
a_{11} & a_{12} & \cdots & a_{1k} \\
a_{21} & a_{22} & \cdots & a_{2k} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} & a_{n2} & \cdots & a_{nk}
\end{bmatrix}^T
=
\begin{bmatrix}
a_{11} & a_{21} & \cdots & a_{k1} \\
a_{12} & a_{22} & \cdots & a_{k2} \\
\vdots & \vdots & \ddots & \vdots \\
a_{1n} & a_{2n} & \cdots & a_{kn}
\end{bmatrix}
\) (15)
.
2. Introduction
Note. AI was used to help write this article / Octave Script / C code, as well as for review: Sonar 2, GPT 5.4, Gemini 3.1 Pro, Claude Sonnet 4.6 / 5 models
.
2.1. Problem Statement
In this article I want to build a neural network that solves a classification task. This means the network must determine whether an object with parameters (input data) “X” belongs to our class. The output produces only two values: 1 — the object belongs to the given class, or 0 — the object does not belong to our class.
Let’s take a simple and commonly used example task. The input is the coordinates of a point on a plane (x1, x2). The neural network must answer whether this point belongs to a given ellipse:
\[
\left(\frac{x_1 – x_{10}}{a}\right)^2 + \left(\frac{x_2 – x_{20}}{b}\right)^2 = 1
\tag{16}
\]
where
\[
x_{1,0} = 1 \; \text{(offset)},\quad
x_{2,0} = 2 \; \text{(offset)},\quad
a = 5 \; \text{(semi-axis a)},\quad
b = 10 \; \text{(semi-axis b)}
\tag{17}
\]
See the Figure 2-1:

Figure 2-1: Ellipse: \( \displaystyle \left(\frac{x_1 – x_{10}}{a}\right)^2 + \left(\frac{x_2 – x_{20}}{b}\right)^2 = 1 \)
\( x_{10} = 1 \; \text{(offset)},\quad x_{20} = 2 \; \text{(offset)},\quad a = 5 \; \text{(semi-axis a)},\quad b = 10 \; \text{(semi-axis b)} \)
.
Neural network inputs are usually normalized. For this purpose we use the following formulas for \( x_{1norm}, x_{2norm}\)
\[
\displaystyle x_{\text{1norm}} = \frac{x_1 – X_{1\min}}{X_{1\max} – X_{1\min}} \tag{18}
\]
\[
\displaystyle x_{\text{2norm}} = \frac{x_2 – X_{2\min}}{X_{2\max} – X_{2\min}} \tag{19}
\]
where
\( X_{1\max} = a + x_{10} \)
\( X_{1\min} = -a + x_{10} \)
\( X_{2\max} = b + x_{20} \)
\( X_{2\min} = -b + x_{20} \) (20)
In the reverse direction:
\[ x_1 = x_{\text{1norm}} \cdot (X_{1\max} – X_{1\min}) + X_{1\min} \tag{21} \]
\[ x_2 = x_{2\text{norm}} \cdot (X_{2\max} – X_{2\min}) + X_{2\min} \tag{22} \]
Note
Obviously, the normalized input variables: \( x_{1norm}, x_{2norm} \) take values in the range: [0, 1]
Substituting (21) and (22) into the ellipse formula (16):
\[ \displaystyle \frac{\left(x_{1\text{norm}}(X_{1\max}-X_{1\min}) + X_{1\min} – x_{10}\right)^2}{a^2} + \frac{\left(x_{2\text{norm}}(X_{2\max}-X_{2\min}) + X_{2\min} – x_{20}\right)^2}{b^2} = 1 \]
\[ \displaystyle \left(x_{\text{1norm}}-\frac{1}{2}\right)^2 + \left(x_{2\text{norm}}-\frac{1}{2}\right)^2 = \left(\frac{1}{2}\right)^2 \tag{23} \]

Figure 2-2: Normalized Ellipse: \( \displaystyle \left(x_{\text{1norm}}-\frac{1}{2}\right)^2 + \left(x_{2\text{norm}}-\frac{1}{2}\right)^2 = \left(\frac{1}{2}\right)^2 \)
.
Notes
-
After normalization, any ellipse is mapped to a circle centered at (0.5, 0.5) with radius 0.5
-
Using formulas (18), (19), input variables can be converted to normalized form, and using formulas (21), (22) the reverse transformation can be performed, returning to the original ellipse. Further in the article I will use the input variables already in normalized form and denote them as , without indicating that they are normalized
-
In this article I will build and train a simple Dense Neural Network that will determine, at the output, whether a given point defined in the unit square [0…1, 0…1] belongs to the closed disc (23). An output value of 1 means yes, it belongs; 0 means no, it does not belong
.
2.2. Software Implementation of a neuron
Let’s look at the implementation of a neuron. It is based on a strongly simplified model of a biological neuron. See Figure 2-3.

Figure 2-3: Neuron Implementation
.
The neuron receives input signals \( x_{1}, x_{2}, … , x_{m} \) which are multiplied by synaptic coefficients \( w_{1}, w_{2}, … , w_{m} \) after which a bias b is added:
\[ z = w _{1} \cdot x_{1} + w_{2} \cdot x_{2} + … + w_{m} \cdot x_{m} + b \tag{24} \]
This is the linear part of the computation. However, using only linear functions, it is impossible for a neuron or neural network to achieve separation of the decision space into complex classes of objects. Therefore, the neuron also has a nonlinear activation function at the output:
\[ \hat{y}=a(z) \tag{25} \]
Note
-
Further we will denote:
\( \hat{y} \) – the computed output value of the neural network
\( y \) – the correct answer for the neural network
-
The coefficients \( w_{i} \) are called synaptic weights, since in a biological neuron the input signals pass through synapses
.
2.3. Activation Functions
Here I will present the most commonly used activation functions for neurons. The description includes the function itself and its derivative, since the derivative is important for the gradient training method
1. Sigmoid Function:
\[
\sigma(z) = \frac{1}{1 + e^{-z}} \tag{26}
\]
Derivative of the Sigmoid Function:
\[ \sigma'(z) = \left(\frac{1}{1+e^{-z}}\right)’ = -\left(1+e^{-z}\right)^{-2}\cdot(-e^{-z}) = \sigma(z)\cdot\bigl(1-\sigma(z)\bigr) \tag{27} \]
Used in the output layer of a neural network for classification tasks and takes values in ]0, 1[. This output value can be interpreted as the probability that the decision corresponds to the given class.

Figure 2-4: Sigmoid(z) Function
.
2. Tanh Function:
\[ \tanh(z) = \frac{e^{z} – e^{-z}}{e^{z} + e^{-z}} \tag{28} \]
Derivative of the tanh Function:
\[ \tanh'(z) = \left(\frac{e^{z}-e^{-z}}{e^{z}+e^{-z}}\right)’ = \frac{(e^{z}+e^{-z})(e^{z}+e^{-z})-(e^{z}-e^{-z})(e^{z}-e^{-z})}{(e^{z}+e^{-z})^2} = 1- \tanh^2(z) \tag{29} \]
Used in the output layer of a neural network and takes values in ]-1, 1[. This activation function is used when a symmetric or zero-centered nonlinearity is needed.

Figure 2-5: Tanh(z) Function
.
3. Rectified Linear Unit (ReLU) Function:
\[ \operatorname{ReLU}(z) = \max(0, z) \tag{30} \]
Derivative of the ReLU Function:
\( \mathrm{ReLU}'(z)=1,\quad z>0 \)
\( \mathrm{ReLU}'(z)=0,\quad z\le 0 \) (31)
Note
The derivative at zero does not exist, but usually, for training with gradient methods, the derivative at zero (z=0) is taken to be zero
Used more often in the hidden layers of a neural network. Can also be used in the output layer if a positive regression response is required. Has a drawback: for values z ≤ 0, the neuron stops participating in computations and does not affect the neural network’s output.
Figure 2-6: ReLU(z) Function
.
4. Leaky Rectified Linear Unit (Leaky ReLU) Function:
\[ \operatorname{LeakyReLU}(z) = \max(0.01 \cdot z, z) \tag{32} \]
Derivative of the Leaky ReLU Function:
\( \mathrm{LeakyReLU}'(z)=1,\quad z>0 \)
\( \mathrm{LeakyReLU}'(z)=0.01,\quad z\le 0 \) (33)
Note
The derivative at zero does not exist, but usually, for training with gradient methods, the derivative at zero is taken equal to the derivative for negative values of z. The value is 0.01
Used more often in the hidden layers of a neural network.
Figure 2-7: LeakyReLU(z) Function
.
5. Heaviside Function:
\( \mathrm{H}(z)=1,\quad z \ge 0 \)
\( \mathrm{H}(z)=0,\quad z<0 \) (34)

Figure 2-8: Heaviside(z) Function
.
Note:
The Heaviside function is practically not used today where gradient methods are applied for training, since its derivative is zero almost everywhere, while at z = 0 the derivative goes to infinity.
.
2.4 Backpropagation for One Neuron using the Batch (or deterministic) Gradient Method
Let’s consider the training principle using the example of a single neuron (see the Figure 2-3). Training consists of the following steps:
-
Two arrays are generated: Training Array, Test Array. The structure of both arrays is the same: input parameters \( x_{1}, x_{2},…, x_{m} \), and the correct answer that the neuron should give, “y”. The first array is used for training the network, and the second for monitoring training.
There is an empirical formula for the size of the training array (see the [11]):
\[ TrainingNmb = 10 \cdot WeightCoefficientsNmb \tag{35} \]
where
\( TrainingNmb \) – size of the Training Array
\( WeightCoefficientsNmb \) – weight coefficients number: w, bNote:
For the neuron shown in Figure 2-3:\[ WeightCoefficientsNmb = m + 1 \tag{36} \]
The size of the training and test arrays is usually in a ratio of 80%, 20% (see [10]), that is:
\[
TestNmb = \frac{20\%}{80\%} \cdot TrainingNmb = \frac{TrainingNmb}{4} \tag{37}
\]where
\( TestNmb \) – size of the Test Array
-
Next, a loss function is chosen for training. In our classification task we will use the cross-entropy function:
\[
\mathcal{L}_{\text{CE}} = CrossEntropyLoss(y,\hat{y}) = -\left(y \cdot \log_{e} \hat{y} + (1-y) \cdot \log_{e}(1-\hat{y})\right) \tag{38}
\]where
\( \hat{y} \) – the answer computed by the neuron
\( y \) – the correct answerNote
For tasks with an analog output, the squared error loss function is often used (see the Appendix 1):\[
\mathcal{L}_{\text{SE}} = SquaredErrorLoss = \frac{1}{2} \cdot \left(\hat{y} – y\right)^2 \tag{39}
\] -
Next, the gradient of the loss function (38) is computed with respect to the various parameters of the neuron. Let our neuron have a sigmoid activation function. Then:
\[
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{y}} = \frac{\partial \mathrm{CrossEntropyLoss}}{\partial \hat{y}} = -\left(\frac{y}{\hat{y}} – \frac{1-y}{1-\hat{y}}\right) \tag{40}
\]Sigmoid function:
\[
\frac{\partial \hat{y}}{\partial z} =
\frac{\partial \sigma(z)}{\partial z} =
\sigma(z) \cdot \bigl(1-\sigma(z)\bigr) =
\hat{y} \cdot (1-\hat{y}) \tag{41}
\]
.
\[
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{y}} \cdot \frac{\partial \mathrm{\hat{y}}}{\partial z}=\frac{\partial \mathrm{CrossEntropyLoss}}{\partial \hat{y}} \cdot \frac{\partial \mathrm{\hat{y}}}{\partial z}= -\left(\frac{y}{\hat{y}} – \frac{1-y}{1-\hat{y}}\right) \cdot \hat{y} \cdot (1 – \hat{y}) = \hat{y} – y \tag{42}
\]
.
\[
\text{gradient}(w_i) =
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial w_i} =
\frac{\partial \mathrm{CrossEntropyLoss}}{\partial w_i} =
\]\[
=
\frac{\partial \mathrm{CrossEntropyLoss}}{\partial \hat{y}}
\cdot
\frac{\partial \hat{y}}{\partial z}
\cdot
\frac{\partial z}{\partial w_i} =
(\hat{y} – y)\cdot x_i \tag{43}
\]
.
\[
\text{gradient}(b) =
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial b} =
\frac{\partial \mathrm{CrossEntropyLoss}}{\partial b} =
\]\[
=
\frac{\partial \mathrm{CrossEntropyLoss}}{\partial \hat{y}}
\cdot
\frac{\partial \hat{y}}{\partial z}
\cdot
\frac{\partial z}{\partial b}
=
\hat{y} – y \tag{44}
\]These gradients (43), (44) are computed over the entire Training Array and then averaged:
\[
\overline{gradient(w_i)}=\frac{1}{TrainingNmb}\cdot\sum_{k=1}^{TrainingNmb} gradient^{(k)}(w_i)
\]\[
\overline{gradient(b)}=\frac{1}{TrainingNmb}\cdot\sum_{k=1}^{TrainingNmb} gradient^{(k)}(b) \tag{45}
\] -
Next, the neuron parameters w, b are adjusted using the gradient method. Formulas (45) show the sensitivity of the error to the parameters w, b, and to adjust these parameters one must multiply the sensitivity by a small delta (\( lr \)), and then subtract the obtained value from the previous parameter value:
\( w_{i}^{(t+1)} = w_{i}^{(t)} – lr \cdot \overline{gradient(w_i)} \)
\( b^{(t+1)} = b^{(t)} – lr \cdot \overline{gradient(b)} \) (46)
where
\( lr \) – learning rate: 0.001…0.1The correction is computed by subtraction, since the gradient shows the direction of maximum increase of the function, while our task is to minimize the error and move toward decreasing the function, thus finding its minimum.
Notes:
-
The algorithm described above demonstrates only one iteration — in this example, computing the correction to the neuron’s parameters. Training requires many iterative steps. One such pass of training over the array is called an epoch. To obtain a good result, many epochs must be passed. But here one must be careful. A small number of epochs leads to underfitting, meaning the neural network has not yet found the right w and b. Too many epochs lead to overfitting. Overfitting can be explained by the fact that the model stops learning from the training array and simply starts memorizing examples from the Training Array. To avoid these errors, the Test Array is used. After each training epoch, the quality of training is evaluated on the Test Array, for which the metrics from formulas (3)…(9) are computed. If subsequent epochs do not improve the training quality metrics or lead to worse quality, training should be stopped.
-
In [4] this algorithm is called the Batch (or deterministic) Gradient Method — classical Gradient Descent using the full training set for gradient averaging
-
t– iteration number; for the Batch (or deterministic) Gradient Method this number equals the epoch number
-
The same algorithm is used for training the neural network. See below
.
2.5. Dense Neural Network with Two Hidden Layers
Here the description relies on the article by Lippmann [1], which substantiates the construction of a neural network for solving a classification task. Figure 2-9 shows a neural network that has two inputs \( x_{1}, x_{2} \) – normalized input coordinates, corresponding to an Input Layer with \( h_{0} = 2 \). Next, there are two layers of neurons \( h_{1}, h_{2} \), called hidden layers. The third layer of neurons is the Output Layer. Since our task reduces to obtaining an answer about whether the input coordinates belong to the normalized ellipse — that is, obtaining a yes (1) or no (0) answer — only one output neuron is needed.
.

Figure 2-9: Dense Neural Network with Two Hidden Layers
.
Lippmann in [1] uses the term “hard limiting nonlinearity: hard limiter / threshold logic” for the activation function, which is mathematically equivalent to the Heaviside function — a step function with a binary output. Each neuron in the first hidden layer defines a line z that separates the space into two half-planes, and the nonlinearity (Heaviside function) maps points from one half-plane to 1 and the other to 0, thereby encoding the point’s membership in that half-plane. Each neuron in the second hidden layer combines, via a logical AND operation, the half-planes defined by the first hidden layer’s neurons, forming a convex figure. The output layer combines, via a logical OR operation, the convex figures formed in the second hidden layer. If the input object (a point in space) belongs to the region formed after training, the output is 1, meaning the object belongs to this class. Otherwise, the output is 0 — the object does not belong to this class.
The main conclusion of this article is that the classification task is solved using a three-layer neural network with two hidden layers.
Notes:
-
Lippmann’s article considers the Heaviside function as the nonlinear activation. But as already mentioned above, backpropagation training requires smooth functions with nonzero derivatives. The ReLU(z) function is not smooth at the point z=0; however, we define the derivative at this special point to be zero, which allows it to be used in training via backpropagation. Therefore, to solve the task, the ReLU function will be used in both hidden layers, while the output layer will use the sigmoid activation function, which is a smooth analogue of the Heaviside function and allows the network’s output to be interpreted as the probability that a point belongs to the target convex region.
Using the ReLU function requires a new interpretation of the neural network’s operation. Here, instead of a logical one/zero from the Heaviside function, the output of the first hidden layer’s neurons gives an analog signal for \( z_{i} > 0 \), or, instead of a logical zero, an analog zero value for \( z_{i} \le 0 \), where \( i = 1…h_{1} \) is the neuron number in the first hidden layer. Each neuron of the first hidden layer computes a linear pre-activation:
\( z_{i}=\displaystyle\sum_{j=1}^{h_0} x_jw_{ji} + b_i \)
Boundary \( z_{i} = 0 \) is a straight line in the input-feature plane and divides it into two half-planes: \( z_{i} > 0 \) and \( z_{i} \le 0 \). Thus, a ReLU neuron of the first hidden layer encodes membership of a point in one of the half-planes not with a binary value, but with an analog positive response. The neurons of the second hidden layer receive weighted sums of the first layer’s responses and also apply the ReLU function. In the geometric interpretation, each such neuron implements a trainable soft analogue of logical conjunction (AND). Its parameters are tuned so that it activates for the combination of half-planes corresponding to one convex region. Unlike Lippmann’s network with a hard limiter, this operation is not a strict binary AND. It is formed during training as an analog dependency between the outputs of the first hidden layer’s neurons.
The output neuron forms a weighted sum of the second hidden layer’s responses, and the sigmoid function at the output gives a value in the range ]0,1[. This output “y” can be interpreted as an estimate of the probability that the object belongs to the target class. The output layer performs a trainable soft aggregation of convex regions, which geometrically corresponds to the analogue of logical disjunction OR in Lippmann’s original threshold-based construction. The classification threshold is 0.5. If \( \sigma(z) \ge 0.5 \), the object belongs to the given class; otherwise it does not.
-
For the ellipse problem we have a single convex figure, which means there is no need to construct several convex figures, and the second hidden layer can be dropped for our task. In this case the output layer must simply combine, via a soft analogue of logical conjunction (AND), the individual half-planes created by the lines from each neuron of the first layer. Thus, after training, the resulting figure will correspond to the ellipse. In this case, the approximation of the ellipse will be carried out with piecewise line segments. The more neurons in the first layer, the more accurate the approximation of the ellipse.
-
Note on existence and trainability. The universal approximation theorems of Cybenko (for sigmoid activations) [14] and Leshno et al. (for any non-polynomial activation, including ReLU) [15] state that a network with one hidden layer can approximate any continuous function on a compact set to arbitrary accuracy, provided the number of hidden neurons is sufficient. However, these theorems are existence results: they give neither an estimate of the required number of neurons nor a guarantee that gradient-based training will find suitable weights. Lippmann [1] offers a constructive alternative: for threshold (hard-limiter) units, the number of neurons in the first hidden layer equals the number of line segments bounding the decision region, and the number of neurons in the second hidden layer equals the number of convex regions. For this reason, this article relies on when choosing the network architecture. With ReLU and sigmoid units this construction serves as a guideline rather than a strict estimate.
.
3. Building and Training a Dense Neural Network for Point-In-Ellipse Classification
.
3.1 Dense Neural Network for Point-In-Ellipse Classification
As established above, solving the ellipse problem requires a two-layer dense neural network with one hidden layer. We will use the ReLU activation function for the hidden layer and the sigmoid function for the output layer neuron. See Figure 3-1:

Figure 3-1: Dense Neural Network with One Hidden Layer
.
Such a neural network is described by the following matrices:
\[
X \in \mathbb{R}^{1 \times h_0}, \quad
W_{h1} \in \mathbb{R}^{h_0 \times h_1}, \quad
B_{h1} \in \mathbb{R}^{1 \times h_1}, \quad
W_{h2} \in \mathbb{R}^{h_1 \times h_2}, \quad
B_{h2} \in \mathbb{R}^{1 \times h_2} \tag{47}
\]
The neural network’s input parameters:
\[
X =
\begin{bmatrix}
x_1 & x_2 & \cdots & x_{h_0}
\end{bmatrix} \tag{48}
\]
The matrix W for h1:
\[
W_{h1} =
\begin{bmatrix}
w_{11}^{(h1)} & w_{12}^{(h1)} & \cdots & w_{1h_1}^{(h1)} \\
w_{21}^{(h1)} & w_{22}^{(h1)} & \cdots & w_{2h_1}^{(h1)} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_01}^{(h1)} & w_{h_02}^{(h1)} & \cdots & w_{h_0h_1}^{(h1)}
\end{bmatrix} \tag{49}
\]
The columns of the matrix \( W_{h1} \) correspond to the synaptic coefficients of the neural layer \( h_{1} \), where the column number is the number of the neuron in the layer.
Bias for \( h_{1} \):
\[
B_{h1} =
\begin{bmatrix}
b_{1}^{(h1)} & b_{2}^{(h1)} & \cdots & b_{h_1}^{(h1)}
\end{bmatrix} \tag{50}
\]
where
\( b_{i}^{(h1)} \) – bias for neuron i in layer \( h_{1} \)
The matrix W for \( h_{2} \):
\[
W_{h2} =
\begin{bmatrix}
w_{11}^{(h2)} & w_{12}^{(h2)} & \cdots & w_{1h_2}^{(h2)} \\
w_{21}^{(h2)} & w_{22}^{(h2)} & \cdots & w_{2h_2}^{(h2)} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_11}^{(h2)} & w_{h_12}^{(h2)} & \cdots & w_{h_1h_2}^{(h2)}
\end{bmatrix} \tag{51}
\]
Bias for \( h_{2} \):
\[
B_{h2} =
\begin{bmatrix}
b_{1}^{(h2)}, & b_{2}^{(h2)} & \cdots & b_{h_2}^{(h2)}
\end{bmatrix} \tag{52}
\]
Let’s describe the computations of this neural network in matrix form (forward propagation):
\(
Z_{h1} = X \cdot W_{h1} + B_{h1} =
\)
\(
=
\begin{bmatrix} x_1 & x_2 & \cdots & x_{h_0} \end{bmatrix}
\cdot
\begin{bmatrix}
w_{11} & w_{12} & \cdots & w_{1h_1} \\
w_{21} & w_{22} & \cdots & w_{2h_1} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_01} & w_{h_02} & \cdots & w_{h_0h_1}
\end{bmatrix}
+
\begin{bmatrix} b_1 & b_2 & \cdots & b_{h_1} \end{bmatrix} =
\)
\(
=
\begin{bmatrix}
\displaystyle\sum_{i=1}^{h_0} x_iw_{i1} + b_1 & \displaystyle\sum_{i=1}^{h_0} x_iw_{i2} + b_2 & \cdots & \displaystyle\sum_{i=1}^{h_0} x_iw_{ih_1} + b_{h_1}
\end{bmatrix}
\) (53)
.
\(
A_{h1}
= \mathrm{ReLU}(Z_{h1}) =
\begin{bmatrix}
\mathrm{ReLU}(z_1) & \mathrm{ReLU}(z_2) & \cdots & \mathrm{ReLU}(z_{h_1})
\end{bmatrix}
=
\begin{bmatrix} a_1 & a_2 & \cdots & a_{h_1} \end{bmatrix}
\) (54)
.
\(
Z_{h2} = A_{h1} \cdot W_{h2} + B_{h2} =
\)
\(
=
\begin{bmatrix} a_1 & a_2 & \cdots & a_{h_1} \end{bmatrix}
\cdot
\begin{bmatrix}
w_{11} & w_{12} & \cdots & w_{1h_2} \\
w_{21} & w_{22} & \cdots & w_{2h_2} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_11} & w_{h_12} & \cdots & w_{h_1h_2}
\end{bmatrix}
+
\begin{bmatrix} b_1 & b_2 & \cdots & b_{h_2} \end{bmatrix} =
\)
\(
=
\begin{bmatrix}
\displaystyle\sum_{j=1}^{h_1} a_jw_{j1} + b_1 & \displaystyle\sum_{j=1}^{h_1} a_jw_{j2} + b_2 & \cdots & \displaystyle\sum_{j=1}^{h_1} a_jw_{jh_2} + b_{h_2}
\end{bmatrix}
\) (55)
.
\(
\hat{Y}
=
\sigma(Z_{h2})
=
\begin{bmatrix}
\sigma(z_1) & \sigma(z_2) & \cdots & \sigma(z_{h_2})
\end{bmatrix}
=
\begin{bmatrix} \hat{y}_1 & \hat{y}_2 & \cdots & \hat{y}_{h_2} \end{bmatrix}
\) (56)
where
\( \hat{Y} = \begin{bmatrix} \hat{y}_1 & \hat{y}_2 & \cdots & \hat{y}_{h_2} \end{bmatrix} \) – the computed value of the neural network
\( Y = \begin{bmatrix} y_{1} & y_{2} & \cdots & y_{h_2} \end{bmatrix} \) – the correct value, which should ideally coincide with the computed value. This value can be taken from the Training / Test Arrays
Note:
In our case \( h_{0}=2 \), \( h_{2}=1 \)
.
3.2 Back Propagation for Dense Neural Network with One Hidden Layer using the Batch (or deterministic) Gradient Method
Let’s consider the training principle for a Dense Neural Network with One Hidden Layer (see the Figure 3-1). Training consists of the same steps considered above for a single neuron:
-
Two arrays are developed: Training Array, Test Array. The structure of both arrays is the same: input parameters , correct answer that the neural network should give . The first array is used for training the network, the second for monitoring training.
To calculate the size of the Training Array, we use (35), taking into account that for Figure 3-1:
\[ WeightCoefficientsNmb = (h_{0} \cdot h_{1} + h_{1}) + (h_{1} \cdot h_{2} + h_{2}) \tag{57} \]
The size of the test array is calculated using formula (37).
-
Next, a loss function is chosen for training. In our classification task we will use the cross-entropy function:
\[
\mathcal{L}_{\text{CE}} = CrossEntropyLoss = -\left(Y \cdot \log_e \hat{Y} + (1-Y) \cdot \log_e(1-\hat{Y})\right) \tag{58}
\]where
\( \hat{Y} \) – the answer computed by the neural network
\( Y \) – the correct answer -
Next, the gradient of the loss function is computed with respect to the various parameters of the neural network.
Matrix dimensions:
\(
X \in \mathbb{R}^{1 \times h_{0}}, \quad
W_{h1} \in \mathbb{R}^{h_{0} \times h_{1}}, \quad
B_{h1} \in \mathbb{R}^{1 \times h_{1}}
\)\(
Z_{h1}, A_{h1} \in \mathbb{R}^{1 \times h_{1}}, \quad
W_{h2} \in \mathbb{R}^{h_1 \times h_{2}}, \quad
B_{h2} \in \mathbb{R}^{1 \times h_{2}}
\)\(
Z_{h2}, \hat{Y}, Y, \delta_{h2} \in \mathbb{R}^{1 \times h_{2}}, \quad
\delta_{h1} \in \mathbb{R}^{1 \times h_{1}}
\) (59)
.
\( \displaystyle
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}} = -\left(\frac{Y}{\hat{Y}} – \frac{1-Y}{1-\hat{Y}}\right)
\) (60)
.
\( \displaystyle
\frac{\partial \hat{Y}}{\partial Z_{h2}} =
\frac{\partial \sigma(Z_{h2})}{\partial Z_{h2}} =
\sigma(Z_{h2}) \cdot \bigl(1-\sigma(Z_{h2})\bigr) =
\hat{Y} \cdot (1-\hat{Y})
\) (61)
.
gradient(Zh2):
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial Z_{h2}} =
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
= -\left(\frac{Y}{\hat{Y}} – \frac{1-Y}{1-\hat{Y}}\right)\cdot\hat{Y}\cdot(1-\hat{Y})
= \hat{Y} – Y
\) (62)
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial Z_{h2}}
= \delta_{h2}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
=
\hat{Y} – Y
=
\begin{bmatrix}
\hat{y}_1 – y_1 & \hat{y}_2 – y_2 & \cdots & \hat{y}_{h_2} – y_{h_2}
\end{bmatrix}
=
\)\(
=
\begin{bmatrix}
\delta_{1}^{(h2)} & \delta_{2}^{(h2)} & \cdots & \delta_{h2}^{(h2)}
\end{bmatrix}
\) (63)
.
gradient(Wh2):\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial W_{h2}}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
\cdot\frac{\partial Z_{h2}}{\partial W_{h2}}
=
A_{h1}^{\top}\cdot\delta_{h2}
=
\)\(
=
\begin{bmatrix}
a_1\cdot(\hat{y}_1 – y_1) & a_1\cdot(\hat{y}_2 – y_2) & \cdots & a_1\cdot(\hat{y}_{h_2} – y_{h_2}) \\
a_2\cdot(\hat{y}_1 – y_1) & a_2\cdot(\hat{y}_2 – y_2) & \cdots & a_2\cdot(\hat{y}_{h_2} – y_{h_2}) \\
\vdots & \vdots & \ddots & \vdots \\
a_{h_1}\cdot(\hat{y}_1 – y_1) & a_{h_1}\cdot(\hat{y}_2 – y_2) & \cdots & a_{h_1}\cdot(\hat{y}_{h_2} – y_{h_2})
\end{bmatrix}
=
G_{W_{h2}}
\) (64).
gradient(Bh2):\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial B_{h2}}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
\cdot\frac{\partial Z_{h2}}{\partial B_{h2}}
=
\delta_{h2}
=
\begin{bmatrix}
\hat{y}_1 – y_1 & \hat{y}_2 – y_2 & \cdots & \hat{y}_{h_2} – y_{h_2}
\end{bmatrix}
=
\)
\(
=
\begin{bmatrix}
\delta_{1}^{(h2)} & \delta_{2}^{(h2)} & \cdots & \delta_{h2}^{(h2)}
\end{bmatrix}
=
G_{B_{h2}}
\) (65)
.
gradient(Ah1):\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial A_{h1}}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}
=
\delta_{h2} \cdot W_{h2}^{\top}
=
\begin{bmatrix}
\displaystyle\sum_{k=1}^{h_2} (\hat{y}_k – y_k)\cdot w_{1k} \\
\displaystyle\sum_{k=1}^{h_2} (\hat{y}_k – y_k)\cdot w_{2k} \\
\vdots \\
\displaystyle\sum_{k=1}^{h_2} (\hat{y}_k – y_k)\cdot w_{h_1k}
\end{bmatrix}^{\top}
=
\)\(
=
\begin{bmatrix}
\sum_{k=1}^{h_2}(\hat{y}_k-y_k)\cdot w_{1k} &
\sum_{k=1}^{h_2}(\hat{y}_k-y_k)\cdot w_{2k} &
\cdots &
\sum_{k=1}^{h_2}(\hat{y}_k-y_k)\cdot w_{h_1k}
\end{bmatrix}
\) (66)
.
gradient(Zh1):\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial Z_{h1}} = \delta_{h1}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}\cdot\frac{\partial A_{h1}}{\partial Z_{h1}}
=
\left(\frac{\partial \mathcal{L}_{\text{CE}}}{\partial A_{h1}}\right)\odot \mathrm{ReLU}'(Z_{h1})
=
\)\(
=
\begin{bmatrix}
\delta_{1}^{(h1)} & \delta_{2}^{(h1)} & \cdots & \delta_{h1}^{(h1)}
\end{bmatrix}
\) (67)
.
gradient(Wh1):\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial W_{h1}}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}\cdot\frac{\partial A_{h1}}{\partial Z_{h1}}\cdot\frac{\partial Z_{h1}}{\partial W_{h1}}
=
X^{\top}\cdot\delta_{h1}
=
\)\(
=
\begin{bmatrix}
x_1\cdot\delta_{1}^{(h1)} & x_1\cdot\delta_{2}^{(h1)} & \cdots & x_1\cdot\delta_{h1}^{(h1)} \\
x_2\cdot\delta_{1}^{(h1)} & x_2\cdot\delta_{2}^{(h1)} & \cdots & x_2\cdot\delta_{h1}^{(h1)} \\
\vdots & \vdots & \ddots & \vdots \\
x_{h_0}\cdot\delta_{1}^{(h1)} & x_{h_0}\cdot\delta_{2}^{(h1)} & \cdots & x_{h_0}\cdot\delta_{h1}^{(h1)}
\end{bmatrix}
=
G_{W_{h1}}
\) (68)
.
gradient(Bh1):\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial B_{h1}}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{CE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}\cdot\frac{\partial A_{h1}}{\partial Z_{h1}}\cdot\frac{\partial Z_{h1}}{\partial B_{h1}}
=
\delta_{h1}
=
\)\(
=
\begin{bmatrix}
\delta_{1}^{(h1)} & \delta_{2}^{(h1)} & \cdots & \delta_{h1}^{(h1)}
\end{bmatrix}
=
G_{B_{h1}}
\) (69)
.
These gradients (64), (65), (68), (69) are computed over the entire Training Array and then averaged:\( \displaystyle
\overline{G_{W_{h2}}}=\frac{1}{TrainingNmb}\cdot\sum_{k=1}^{TrainingNmb} G_{W_{h2}}^{(k)}
\)
.
\( \displaystyle
\overline{G_{B_{h2}}}=\frac{1}{TrainingNmb}\cdot\sum_{k=1}^{TrainingNmb} G_{B_{h2}}^{(k)}
\) (70)
.
\( \displaystyle
\overline{G_{W_{h1}}}=\frac{1}{TrainingNmb}\cdot\sum_{k=1}^{TrainingNmb} G_{W_{h1}}^{(k)}
\)
.
\( \displaystyle
\overline{G_{B_{h1}}}=\frac{1}{TrainingNmb}\cdot\sum_{k=1}^{TrainingNmb} G_{B_{h1}}^{(k)}
\) (71) -
Next, the neural network parameters W, B are adjusted using the gradient method. Formulas (64), (65), (67), (68) show the sensitivity of the error to the parameters W, B, and to adjust these parameters one must multiply the sensitivity by a small delta (\( lr \)), then subtract the obtained value from the previous parameter value:
\( W_{h2}^{(t+1)} = W_{h2}^{(t)} – lr \cdot \overline{G_{W_{h2}}} \)
.
\( B_{h2}^{(t+1)} = B_{h2}^{(t)} – lr \cdot \overline{G_{B_{h2}}} \) (72)
.
\( W_{h1}^{(t+1)} = W_{h1}^{(t)} – lr \cdot \overline{G_{W_{h1}}} \)
.
\( B_{h1}^{(t+1)} = B_{h1}^{(t)} – lr \cdot \overline{G_{B_{h1}}} \) (73)
.
where
lr – learning rate: 0.001…0.1
t – iteration number; for the Batch (or deterministic) Gradient Method this number equals the epoch number
.
The correction is computed by subtraction, since the gradient shows the direction of maximum increase of the function, while our task is to minimize the error and move toward decreasing the function to find its minimum.
Notes:
-
The algorithm described above demonstrates only one iteration – in this example, computing the correction to the neural network’s parameters. Training requires many iterative steps. One such pass of training over the array is called an epoch. To obtain a good result, many epochs must be passed. But here one must be careful. A small number of epochs leads to underfitting, meaning the neural network has not yet found the right W and B. Too many epochs lead to overfitting. Overfitting can be explained by the fact that the model stops learning from the training array and simply starts memorizing examples from the Training Array. To avoid these errors, the Test Array is used. After each training epoch, the quality of training is evaluated on the Test Array, for which the metrics from formulas (3)…(9) are computed. If subsequent epochs do not improve the training quality metrics or lead to worse quality, training should be stopped.
-
In [4] this algorithm is called the Batch (or deterministic) Gradient Method — classical Gradient Descent using the full training set.
-
In our case \( h_{0}=2 \), \( h_{2}=1 \)
.
3.3 Optimizers that Improve Convergence of the Gradient Method
Difficulties often arise in the gradient method when moving along the error surface, and the task arises of helping the gradient method reach the result more efficiently in rough or narrow regions of the error function. Here is a brief description of these problems:
-
Plateau — a place where the gradient is small, so the step along the gradient is very small and training slows down. If the plateau is perfectly flat and the gradient is zero everywhere, then no optimization method by itself will help, because there is simply nowhere to move.
-
Narrow ravine — a section of the error surface that is a long narrow valley with an almost flat bottom, while the walls across the valley are steep. Because of this, ordinary gradient descent often starts zigzagging between the walls of the ravine and slowly progresses forward. The problem is not that there is “no descent at all”, but that one descent is too steep while the other is too gentle. Because of this, the algorithm’s steps become inefficient: it either oscillates or moves very slowly along the bottom.
-
Saddle points, where the error function increases in some directions and decreases in others, while the gradient is zero, but this is not a minimum. The algorithm can “get stuck” or oscillate for a long time. In multidimensional problems there are usually very many such points, so the probability of encountering them is high. In the vicinity of a saddle point there are directions of descent, but finding them requires an intelligent optimizer. Using the Hessian (see Appendix 2) a saddle point can be recognized.
Note: a stationary point is classified using the Hessian: a positive definite Hessian corresponds to a local minimum, a negative definite one to a local maximum, and an indefinite Hessian indicates a saddle point.
-
Local minimum are a common problem of the gradient method, and an optimizer can help to “jump over” a local minimum and eventually reach the global minimum.
To solve these problems, the following optimizers are most commonly used: SGD, Mini-Batch, Momentum, Adam:
-
Stochastic Gradient Descent (SGD). The gradient is computed not over the entire database at once, but over individual samples of the training array. This creates “noise” in the gradient, which leads to jumping and shaking, which helps avoid getting stuck in small cracks. Thus SGD adds stochasticity, because the gradient is computed not over the entire training array, but for each element of that array. This can help “jump out” of bad regions of the error landscape, but not with a guarantee.
Drawbacks:
In narrow ravines, SGD often oscillates between the walls, whereas Momentum and Adam help pass through such regions faster and more steadily due to inertia and adaptive step size. Training on a single object leads to high variance of gradient estimates, since each weight update is based on only one training example rather than an averaged gradient over a group of examples. This causes fluctuations in the loss function and makes precise convergence to the minimum difficult, and also increases the sensitivity of the training process to the choice of learning rate. Therefore, mini-batch training is often used.
-
Mini-Batch SGD — here the gradient is computed not for individual samples of the training array, but for averaged gradients of a group of examples, for example 8, 16, 32, or 64 objects.
Note: Mini-Batch in [4] is singled out as a separate method, but in software implementations Mini-Batch is often combined with SGD, Momentum, Adam. In the software presented here, each method has a Batch Size parameter that can be set in the range: 1 … TrainingSize.
-
Inertia (Momentum): Here mass and velocity are assigned to the weights. If the gradient has been rolling downhill for a long time, it accumulates speed and helps pass small local minima, plateaus, and narrow pits. Momentum helps reduce zigzagging in narrow ravines because the method remembers past steps.
-
Adam — Adaptive Moment Estimation. The algorithm automatically selects the learning rate for each weight individually. Adam combines inertia and an adaptive learning step, so it usually makes training more stable and faster, but also does not give a mathematical guarantee of escaping any bad regions of the error landscape. Adam can increase the effective step in coordinates where gradients have long been small. It often passes through regions with different curvature faster, and usually performs better at the start, because it combines momentum and an adaptive step. Adam helps to better pass through regions with plateaus, narrow ravines, and strong gradient oscillations.
.
3.3.1 Stochastic Gradient Descent (SGD)
Using formula (68) we compute the gradient Wh1:
\[ \displaystyle
G_{W_{h1}}^{(t)} = \nabla_{W_{h1}}\mathcal{L}^{(t)} \in \mathbb{R}^{h_0\times h_1} \tag{74}
\]
We adjust Wh1 using the gradient method:
\[ \displaystyle
W_{h1}^{(t)} = W_{h1}^{(t-1)} – lr\cdot G_{W_{h1}}^{(t)}
=
\begin{bmatrix}
w_{11}^{(t-1)}-lr\cdot g_{11} & \cdots & w_{1h_1}^{(t-1)}-lr\cdot g_{1h_1} \\
\vdots & \ddots & \vdots \\
w_{h_01}^{(t-1)}-lr\cdot g_{h_01} & \cdots & w_{h_0h_1}^{(t-1)}-lr\cdot g_{h_0h_1}
\end{bmatrix} \tag{75}
\]
Using formula (69) we compute the gradient Bh1:
\[
G_{B_{h1}}^{(t)} = \nabla_{B_{h1}}\mathcal{L}^{(t)} \in \mathbb{R}^{1\times h_1} \tag{76}
\]
We adjust Bh1 using the gradient method:
\[
B_{h1}^{(t)} = B_{h1}^{(t-1)} – lr\cdot\ G_{B_{h1}}^{(t)}
=
\begin{bmatrix} b_1^{(t-1)}-lr\cdot g_1 & \cdots & b_{h_1}^{(t-1)}-lr\cdot g_{h_1} \end{bmatrix} \tag{77}
\]
Using formula (64) we compute the gradient Wh2:
\[
G_{W_{h2}}^{(t)} = \nabla_{W_{h2}}\mathcal{L}^{(t)} \in \mathbb{R}^{h_1\times h_2} \tag{78}
\]
We adjust Wh2 using the gradient method:
\[
W_{h2}^{(t)} = W_{h2}^{(t-1)} – lr\cdot\ G_{W_{h2}}^{(t)}
=
\begin{bmatrix}
w_{11}^{(t-1)}-lr\cdot g_{11} & \cdots & w_{1h_2}^{(t-1)}-lr\cdot g_{1h_2} \\
\vdots & \ddots & \vdots \\
w_{h_11}^{(t-1)}-lr\cdot g_{h_11} & \cdots & w_{h_1h_2}^{(t-1)}-lr\cdot g_{h_1h_2}
\end{bmatrix} \tag{79}
\]
Using formula (65) we compute the gradient Bh2:
\[
G_{B_{h2}}^{(t)} = \nabla_{B_{h2}}\mathcal{L}^{(t)} \in \mathbb{R}^{1\times h_2} \tag{80}
\]
We adjust Bh2 using the gradient method:
\[
B_{h2}^{(t)} = B_{h2}^{(t-1)} – lr\cdot\ G_{B_{h2}}^{(t)}
=
\begin{bmatrix} b_1^{(t-1)}-lr\cdot g_1 & \cdots & b_{h_2}^{(t-1)}-lr\cdot g_{h_2} \end{bmatrix} \tag{81}
\]
Note
-
See [4], [7] for more details.
-
In SGD training, the parameters Wh, Bh are updated after processing each training example. Before the start of each new epoch, the training examples are randomly shuffled. This eliminates the influence of the original order of objects and makes the sequence of gradient updates less dependent on the data structure, which usually promotes more stable training.
-
t – the iteration number at which new values of the neural network parameters Wh, Bh are computed.
.
3.3.2 Mini Batch Stochastic Gradient Descent
Using formula (68) we compute the gradient Wh1 for the current k-th mini-batch of size N:
\( n=k \cdot N+1,…, k \cdot N+N \) from the training array
\(
G_{W_{h1}}^{(t,n)} = \nabla_{W_{h1}}\mathcal{L}^{(t,n)} \in \mathbb{R}^{h_0\times h_1}
\) (82)
We average the gradient Wh1 over the Mini-Batch:
\(
\bar G_{W_{h1}}^{(t)} = \frac{1}{N} \cdot \sum_{n=1}^{N} G_{W_{h1}}^{(t,n)} =
\begin{bmatrix}
\dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{11}^{(n)} & \dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{12}^{(n)} & \cdots & \dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{1h_1}^{(n)} \\[1em]
\dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{21}^{(n)} & \dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{22}^{(n)} & \cdots & \dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{2h_1}^{(n)} \\[1em]
\vdots & \vdots & \ddots & \vdots \\[0.5em]
\dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{h_01}^{(n)} & \dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{h_02}^{(n)} & \cdots & \dfrac{1}{N} \cdot \displaystyle\sum_{n=1}^{N} g_{h_0h_1}^{(n)}
\end{bmatrix} =
\)
\(
=
\begin{bmatrix}
\bar g_{11} & \bar g_{12} & \cdots & \bar g_{1h_1} \\
\bar g_{21} & \bar g_{22} & \cdots & \bar g_{2h_1} \\
\vdots & \vdots & \ddots & \vdots \\
\bar g_{h_01} & \bar g_{h_02} & \cdots & \bar g_{h_0h_1}
\end{bmatrix}
\in \mathbb{R}^{h_0\times h_1}
\) (83)
where
\(
\bar g_{ij} = \frac{1}{N} \cdot \sum_{n=1}^{N} g_{ij}^{(n)}
\)
\( N – Batch Size \) (84)
We adjust Wh1 using the gradient method:
\[
W_{h1}^{(t)} = W_{h1}^{(t-1)} – lr\cdot\,\bar G_{W_{h1}}^{(t)}
=
\begin{bmatrix}
w_{11}^{(t-1)}-lr\cdot\bar g_{11} & \cdots & w_{1h_1}^{(t-1)}-lr\cdot\bar g_{1h_1} \\
\vdots & \ddots & \vdots \\
w_{h_01}^{(t-1)}-lr\cdot\bar g_{h_01} & \cdots & w_{h_0h_1}^{(t-1)}-lr\cdot\bar g_{h_0h_1}
\end{bmatrix} \tag{85}
\]
Bh1, Wh2, Bh2 are computed analogously:
\[
G_{B_{h1}}^{(t,n)} = \nabla_{B_{h1}}\mathcal{L}^{(t,n)} \in \mathbb{R}^{1\times h_1} \tag{86}
\]
.
\[
\bar G_{B_{h1}}^{(t)} = \frac{1}{N} \cdot \sum_{n=1}^{N} G_{B_{h1}}^{(t,n)} \in \mathbb{R}^{1\times h_1} \tag{87}
\]
.
\[
B_{h1}^{(t)} = B_{h1}^{(t-1)} – lr\cdot\,\bar G_{B_{h1}}^{(t)}
=
\begin{bmatrix} b_1^{(t-1)}-lr\cdot\bar g_1 & \cdots & b_{h_1}^{(t-1)}-lr\cdot\bar g_{h_1} \end{bmatrix} \tag{88}
\]
.
\[
G_{W_{h2}}^{(t,n)} = \nabla_{W_{h2}}\mathcal{L}^{(t,n)} \in \mathbb{R}^{h_1\times h_2} \tag{89}
\]
.
\[
\bar G_{W_{h2}}^{(t)} = \frac{1}{N} \cdot \sum_{n=1}^{N} G_{W_{h2}}^{(t,n)} \in \mathbb{R}^{h_1\times h_2} \tag{90}
\]
.
\[
W_{h2}^{(t)} = W_{h2}^{(t-1)} – lr\cdot\,\bar G_{W_{h2}}^{(t)}
=
\begin{bmatrix}
w_{11}^{(t-1)}-lr\cdot\bar g_{11} & \cdots & w_{1h_2}^{(t-1)}-lr\cdot\bar g_{1h_2} \\
\vdots & \ddots & \vdots \\
w_{h_11}^{(t-1)}-lr\cdot\bar g_{h_11} & \cdots & w_{h_1h_2}^{(t-1)}-lr\cdot\bar g_{h_1h_2}
\end{bmatrix} \tag{91}
\]
.
\[
G_{B_{h2}}^{(t,n)} = \nabla_{B_{h2}}\mathcal{L}^{(t,n)} \in \mathbb{R}^{1\times h_2} \tag{92}
\]
.
\[
\bar G_{B_{h2}}^{(t)} = \frac{1}{N} \cdot \sum_{n=1}^{N} G_{B_{h2}}^{(t,n)} \in \mathbb{R}^{1\times h_2} \tag{93}
\]
.
\[
B_{h2}^{(t)} = B_{h2}^{(t-1)} – lr\cdot\,\bar G_{B_{h2}}^{(t)}
=
\begin{bmatrix} b_1^{(t-1)}-lr\cdot\bar g_1 & \cdots & b_{h_2}^{(t-1)}-lr\cdot\bar g_{h_2} \end{bmatrix} \tag{94}
\]
.
Note
-
See [4] for more details
-
In mini-batch training, the parameters Wh, Bh are updated after processing each mini-batch. Before the start of each new epoch, the training examples are randomly shuffled. This eliminates the influence of the original order of objects and makes the sequence of gradient updates less dependent on the data structure, which usually promotes more stable training.
-
t – the iteration number at which new values of the neural network parameters Wh, Bh are computed
.
3.3.3 Momentum
Here inertia γ (gamma) is additionally introduced, and velocity V is computed at each step. Let there be some parameter P that needs to be corrected/adjusted. In our case these are the parameters: Wh1, Bh1, Wh2, Bh2. Then the computations are performed as follows:
-
We accumulate velocity V:
\[ V_{P}^{(t)} = \gamma \cdot V_{P}^{(t-1)} + lr \cdot \nabla_{P}\mathcal{L} \tag{95} \]
-
We update parameter P:
\[ P^{(t)} = P^{(t-1)} – V_{P}^{(t)} \tag{96} \]
.

Table 3-1: Choice of γ Values for Momentum
.
Note
In our example the following values are used: \( \gamma = 0.9, lr = 0.05 \) (97)
Computations for Wh1:
\[
G_{W_{h1}}^{(t)} = \nabla_{W_{h1}}\mathcal{L}^{(t)} \in \mathbb{R}^{h_0\times h_1}, \quad
V_{W_{h1}}^{(t)} \in \mathbb{R}^{h_0\times h_1} \tag{98}
\]
.
\[
V_{W_{h1}}^{(t)} = \gamma V_{W_{h1}}^{(t-1)} + lr\cdot\,G_{W_{h1}}^{(t)}
=
\begin{bmatrix}
\gamma v_{11}^{(t-1)}+lr\cdot g_{11} & \cdots & \gamma v_{1h_1}^{(t-1)}+lr\cdot g_{1h_1} \\
\vdots & \ddots & \vdots \\
\gamma v_{h_01}^{(t-1)}+lr\cdot g_{h_01} & \cdots & \gamma v_{h_0h_1}^{(t-1)}+lr\cdot g_{h_0h_1}
\end{bmatrix} \tag{99}
\]
.
\[
W_{h1}^{(t)} = W_{h1}^{(t-1)} – V_{W_{h1}}^{(t)}
=
\begin{bmatrix}
w_{11}^{(t-1)}-v_{11}^{(t)} & \cdots & w_{1h_1}^{(t-1)}-v_{1h_1}^{(t)} \\
\vdots & \ddots & \vdots \\
w_{h_01}^{(t-1)}-v_{h_01}^{(t)} & \cdots & w_{h_0h_1}^{(t-1)}-v_{h_0h_1}^{(t)}
\end{bmatrix} \tag{100}
\]
.
Computations for Bh1:
\[
G_{B_{h1}}^{(t)} = \nabla_{B_{h1}}\mathcal{L}^{(t)} \in \mathbb{R}^{1\times h_1}, \quad
V_{B_{h1}}^{(t)} \in \mathbb{R}^{1\times h_1} \tag{101}
\]
.
\[
V_{B_{h1}}^{(t)} = \gamma V_{B_{h1}}^{(t-1)} + lr\cdot\,G_{B_{h1}}^{(t)}
=
\begin{bmatrix} \gamma v_1^{(t-1)}+ lr\cdot g_1 & \cdots & \gamma v_{h_1}^{(t-1)}+ lr\cdot g_{h_1} \end{bmatrix} \tag{102}
\]
.
\[
B_{h1}^{(t)} = B_{h1}^{(t-1)} – V_{B_{h1}}^{(t)}
=
\begin{bmatrix} b_1^{(t-1)}-v_1^{(t)} & \cdots & b_{h_1}^{(t-1)}-v_{h_1}^{(t)} \end{bmatrix} \tag{103}
\]
Computations for Wh2:
\[
G_{W_{h2}}^{(t)} = \nabla_{W_{h2}}\mathcal{L}^{(t)} \in \mathbb{R}^{h_1\times h_2}, \quad
V_{W_{h2}}^{(t)} \in \mathbb{R}^{h_1\times h_2} \tag{104}
\]
.
\[
V_{W_{h2}}^{(t)} = \gamma V_{W_{h2}}^{(t-1)} + lr\cdot\,G_{W_{h2}}^{(t)}
=
\begin{bmatrix}
\gamma v_{11}^{(t-1)}+ lr\cdot g_{11} & \cdots & \gamma v_{1h_2}^{(t-1)}+ lr\cdot g_{1h_2} \\
\vdots & \ddots & \vdots \\
\gamma v_{h_11}^{(t-1)}+ lr\cdot g_{h_11} & \cdots & \gamma v_{h_1h_2}^{(t-1)}+ lr\cdot g_{h_1h_2}
\end{bmatrix} \tag{105}
\]
.
\[
W_{h2}^{(t)} = W_{h2}^{(t-1)} – V_{W_{h2}}^{(t)}
=
\begin{bmatrix}
w_{11}^{(t-1)}-v_{11}^{(t)} & \cdots & w_{1h_2}^{(t-1)}-v_{1h_2}^{(t)} \\
\vdots & \ddots & \vdots \\
w_{h_11}^{(t-1)}-v_{h_11}^{(t)} & \cdots & w_{h_1h_2}^{(t-1)}-v_{h_1h_2}^{(t)}
\end{bmatrix} \tag{106}
\]
.
Computations for Bh2:
\[
G_{B_{h2}}^{(t)} = \nabla_{B_{h2}}\mathcal{L}^{(t)} \in \mathbb{R}^{1\times h_2}, \quad
V_{B_{h2}}^{(t)} \in \mathbb{R}^{1\times h_2} \tag{107}
\]
.
\[
V_{B_{h2}}^{(t)} = \gamma V_{B_{h2}}^{(t-1)} + lr\cdot\,G_{B_{h2}}^{(t)}
=
\begin{bmatrix} \gamma v_1^{(t-1)}+ lr\cdot g_1 & \cdots & \gamma v_{h_2}^{(t-1)}+ lr\cdot g_{h_2} \end{bmatrix} \tag{108}
\]
.
\[
B_{h2}^{(t)} = B_{h2}^{(t-1)} – V_{B_{h2}}^{(t)}
=
\begin{bmatrix} b_1^{(t-1)}-v_1^{(t)} & \cdots & b_{h_2}^{(t-1)}-v_{h_2}^{(t)} \end{bmatrix} \tag{109}
\]
.
Note
-
This shows the calculation for individual examples (single samples) from the training array. As shown above, the method also allows averaging gradients within a Mini-Batch or over the entire array at once.
-
In stochastic or mini-batch training, the parameters Wh, Bh are updated after processing each training example or each mini-batch, respectively. Before the start of each new epoch, the training examples are randomly shuffled. This eliminates the influence of the original order of objects and makes the sequence of gradient updates less dependent on the data structure, which usually promotes more stable training.
-
t – the iteration number at which new values of the neural network parameters Wh, Bh are computed
-
See [4], [8], [12] for more details
.
3.3.4 Adam
-
Accumulation of Moments
Adam maintains two vectors for each weight:
\( M_{W,B}^{(t)} \) (analogue of velocity) – the mean value of the gradient.
\( V_{W,B}^{(t)} \) – the mean value of the squared gradient (variance estimate).
\( M_{W,B}^{(t)} = \beta_1 \cdot M_{W,B}^{(t-1)} + (1 – \beta_1) \cdot G_{W,B}^{(t)} \) (110)
\( V_{W,B}^{(t)} = \beta_2 \cdot V_{W,B}^{(t-1)} + (1 – \beta_2) \cdot G_{W,B}^{(t)} \odot G_{W,B}^{(t)} \) (111)Here \( G_{W,B}^{(t)} \) is the current gradient \( {\nabla}_{W,B} L^{(t)} \). Note that both formulas use the structure of a first-order IIR filter.
. -
Bias Correction
Since M and V are zero at the start of training, they will “pull” the values down. Adam — Adaptive Moment Estimation — corrects this in the first steps:
\( \displaystyle
\hat{M}_{W,B}^{(t)} = \frac{M_{W,B}^{(t)}}{1 – \beta_1^t}, \quad \hat{V}_{W,B}^{(t)} = \frac{V_{W,B}^{(t)}}{1 – \beta_2^t}
\) (112)Here t is the iteration number. For example, at step t=100 these denominators become practically equal to 1, and the correction stops having an effect.
. -
Final Weight Update
The most important part, where adaptivity manifests itself:
\( \displaystyle
W_{W,B}^{(t+1)} = W_{W,B}^{(t)} – lr \cdot \frac{\hat{M}_{W,B}^{(t)}}{\sqrt{\hat{V}_{W,B}^{(t)}} + \epsilon}
\) (113)
.
Recommended Constants in Practice:
\( \beta_1 = 0.9 \) – analogue of \( \gamma \) for inertia in the case of Momentum
\( \beta_2 = 0.999 \) – very long memory for estimating the squared gradient (noise)
\( \epsilon = 10^{-8} \) – a small number to avoid division by zero
\( lr = 0.01 \) – standard initial step for Adam (114)
.
Computation for Wh1:
\(
G_{W_{h1}}^{(t)} = \nabla_{W_{h1}} \mathcal{L}^{(t)} \in \mathbb{R}^{h_0\times h_1}, \quad
M_{W_{h1}}^{(t)}, V_{W_{h1}}^{(t)} \in \mathbb{R}^{h_0\times h_1}, \quad
\hat M_{W_{h1}}^{(t)}, \hat V_{W_{h1}}^{(t)} \in \mathbb{R}^{h_0\times h_1}
\) (115)
.
\(
M_{W_{h1}}^{(t)} = \beta_1 \cdot M_{W_{h1}}^{(t-1)} + (1-\beta_1) \cdot G_{W_{h1}}^{(t)}
=
\)
\(
=
\begin{bmatrix}
\beta_1 \cdot m^{(t-1)}_{11}+(1-\beta_1) \cdot g_{11} & \cdots & \beta_1 \cdot m^{(t-1)}_{1h_1}+(1-\beta_1) \cdot g_{1h_1} \\
\vdots & \ddots & \vdots \\
\beta_1 \cdot m^{(t-1)}_{h_01}+(1-\beta_1) \cdot g_{h_01} & \cdots & \beta_1 \cdot m^{(t-1)}_{h_0h_1}+(1-\beta_1) \cdot g_{h_0h_1}
\end{bmatrix}
\) (116)
.
.
\(
V_{W_{h1}}^{(t)} = \beta_2 \cdot V_{W_{h1}}^{(t-1)} + (1-\beta_2) \cdot (G_{W_{h1}}^{(t)}\odot G_{W_{h1}}^{(t)})
=
\)
.
\(
=
\begin{bmatrix}
\beta_2 \cdot v^{(t-1)}_{11}+(1-\beta_2) \cdot g_{11}^2 & \cdots & \beta_2 \cdot v^{(t-1)}_{1h_1}+(1-\beta_2) \cdot g_{1h_1}^2 \\
\vdots & \ddots & \vdots \\
\beta_2 \cdot v^{(t-1)}_{h_01}+(1-\beta_2) \cdot g_{h_01}^2 & \cdots & \beta_2 \cdot v^{(t-1)}_{h_0h_1}+(1-\beta_2) \cdot g_{h_0h_1}^2
\end{bmatrix}
\) (117)
.
.
\( \displaystyle
\hat M_{W_{h1}}^{(t)} = \frac{M_{W_{h1}}^{(t)}}{1-\beta_1^t}
=
\begin{bmatrix}
\dfrac{m^{(t)}_{11}}{1-\beta_1^t} & \cdots & \dfrac{m^{(t)}_{1h_1}}{1-\beta_1^t} \\
\vdots & \ddots & \vdots \\
\dfrac{m^{(t)}_{h_01}}{1-\beta_1^t} & \cdots & \dfrac{m^{(t)}_{h_0h_1}}{1-\beta_1^t}
\end{bmatrix}
\) (118)
.
\( \displaystyle
\hat V_{W_{h1}}^{(t)} = \frac{V_{W_{h1}}^{(t)}}{1-\beta_2^t}
=
\begin{bmatrix}
\dfrac{v^{(t)}_{11}}{1-\beta_2^t} & \cdots & \dfrac{v^{(t)}_{1h_1}}{1-\beta_2^t} \\
\vdots & \ddots & \vdots \\
\dfrac{v^{(t)}_{h_01}}{1-\beta_2^t} & \cdots & \dfrac{v^{(t)}_{h_0h_1}}{1-\beta_2^t}
\end{bmatrix}
\) (119)
.
\(
W_{h1}^{(t+1)} = W_{h1}^{(t)} – lr \cdot \,\big(\hat M_{W_{h1}}^{(t)} \oslash (\sqrt{\hat V_{W_{h1}}^{(t)}}+\epsilon)\big) =
\)
.
\(
=
\begin{bmatrix}
w^{(t)}_{11}-lr \cdot \dfrac{\hat m_{11}}{\sqrt{\hat v_{11}}+\epsilon} & \cdots & w^{(t)}_{1h_1}-lr \cdot \dfrac{\hat m_{1h_1}}{\sqrt{\hat v_{1h_1}}+\epsilon} \\
\vdots & \ddots & \vdots \\
w^{(t)}_{h_01}-lr \cdot \dfrac{\hat m_{h_01}}{\sqrt{\hat v_{h_01}}+\epsilon} & \cdots & w^{(t)}_{h_0h_1}-lr \cdot \dfrac{\hat m_{h_0h_1}}{\sqrt{\hat v_{h_0h_1}}+\epsilon}
\end{bmatrix}
\) (120)
.
Computation for Bh1:
\(
G_{B_{h1}}^{(t)} = \nabla_{B_{h1}} \mathcal{L}^{(t)} \in \mathbb{R}^{1\times h_1}, \quad
M_{B_{h1}}^{(t)}, V_{B_{h1}}^{(t)} \in \mathbb{R}^{1\times h_1}, \quad
\hat M_{B_{h1}}^{(t)}, \hat V_{B_{h1}}^{(t)} \in \mathbb{R}^{1\times h_1}
\) (121)
.
\(
M_{B_{h1}}^{(t)} = \beta_1 \cdot M_{B_{h1}}^{(t-1)} + (1-\beta_1) \cdot G_{B_{h1}}^{(t)}
=
\)
\(
=
\begin{bmatrix} \beta_1 \cdot m^{(t-1)}_1+(1-\beta_1) \cdot g_1 & \cdots & \beta_1 \cdot m^{(t-1)}_{h_1}+(1-\beta_1) \cdot g_{h_1}\end{bmatrix}
\) (122)
.
\(
V_{B_{h1}}^{(t)} = \beta_2 \cdot V_{B_{h1}}^{(t-1)} + (1-\beta_2) \cdot \big(G_{B_{h1}}^{(t)}\odot G_{B_{h1}}^{(t)}\big)
=
\)
\(
=
\begin{bmatrix} \beta_2 \cdot v_1^{(t-1)}+(1-\beta_2) \cdot g_1^2 & \cdots & \beta_2 \cdot v_{h_1}^{(t-1)}+(1-\beta_2) \cdot g_{h_1}^2 \end{bmatrix}
\) (123)
.
\( \displaystyle
\hat M_{B_{h1}}^{(t)} = \frac{M_{B_{h1}}^{(t)}}{1-\beta_1^t}
=
\begin{bmatrix} \dfrac{m_1^{(t)}}{1-\beta_1^t} & \cdots & \dfrac{m_{h_1}^{(t)}}{1-\beta_1^t} \end{bmatrix}
\) (124)
.
\(
\hat V_{B_{h1}}^{(t)} = \frac{V_{B_{h1}}^{(t)}}{1-\beta_2^t}
=
\begin{bmatrix} \dfrac{v_1^{(t)}}{1-\beta_2^t} & \cdots & \dfrac{v_{h_1}^{(t)}}{1-\beta_2^t} \end{bmatrix}
\) (125)
.
\(
B_{h1}^{(t+1)} = B_{h1}^{(t)} – lr \cdot \,\big(\hat M_{B_{h1}}^{(t)}\oslash(\sqrt{\hat V_{B_{h1}}^{(t)}}+\epsilon)\big)
=
\)
.
\( \displaystyle
=
\begin{bmatrix}
b_1^{(t)}-lr \cdot \dfrac{\hat m_1}{\sqrt{\hat v_1}+\epsilon} & \cdots & b_{h_1}^{(t)}-lr \cdot \dfrac{\hat m_{h_1}}{\sqrt{\hat v_{h_1}}+\epsilon}
\end{bmatrix}
\) (126)
.
Computation for Wh2:
\(
G_{W_{h2}}^{(t)} = \nabla_{W_{h2}} \mathcal{L}^{(t)} \in \mathbb{R}^{h_1\times h_2}, \quad
M_{W_{h2}}^{(t)}, V_{W_{h2}}^{(t)} \in \mathbb{R}^{h_1\times h_2}, \quad
\hat M_{W_{h2}}^{(t)}, \hat V_{W_{h2}}^{(t)} \in \mathbb{R}^{h_1\times h_2}
\) (127)
.
\(
M_{W_{h2}}^{(t)} = \beta_1 \cdot M_{W_{h2}}^{(t-1)} + (1-\beta_1) \cdot G_{W_{h2}}^{(t)}
=
\)
.
\(
=
\begin{bmatrix}
\beta_1 \cdot m^{(t-1)}_{11}+(1-\beta_1) \cdot g_{11} & \cdots & \beta_1 \cdot m^{(t-1)}_{1h_2}+(1-\beta_1) \cdot g_{1h_2} \\
\vdots & \ddots & \vdots \\
\beta_1 \cdot m^{(t-1)}_{h_11}+(1-\beta_1) \cdot g_{h_11} & \cdots & \beta_1 \cdot m^{(t-1)}_{h_1h_2}+(1-\beta_1) \cdot g_{h_1h_2}
\end{bmatrix}
\) (128)
.
\(
V_{W_{h2}}^{(t)} = \beta_2 \cdot V_{W_{h2}}^{(t-1)} + (1-\beta_2) \cdot (G_{W_{h2}}^{(t)}\odot G_{W_{h2}}^{(t)})
=
\)
.
\(
=
\begin{bmatrix}
\beta_2 \cdot v^{(t-1)}_{11}+(1-\beta_2) \cdot g_{11}^2 & \cdots & \beta_2 \cdot v^{(t-1)}_{1h_2}+(1-\beta_2) \cdot g_{1h_2}^2 \\
\vdots & \ddots & \vdots \\
\beta_2 \cdot v^{(t-1)}_{h_11}+(1-\beta_2) \cdot g_{h_11}^2 & \cdots & \beta_2 \cdot v^{(t-1)}_{h_1h_2}+(1-\beta_2) \cdot g_{h_1h_2}^2
\end{bmatrix}
\) (129)
.
\( \displaystyle
\hat M_{W_{h2}}^{(t)} = \frac{M_{W_{h2}}^{(t)}}{1-\beta_1^t}
=
\begin{bmatrix}
\dfrac{m^{(t)}_{11}}{1-\beta_1^t} & \cdots & \dfrac{m^{(t)}_{1h_2}}{1-\beta_1^t} \\
\vdots & \ddots & \vdots \\
\dfrac{m^{(t)}_{h_11}}{1-\beta_1^t} & \cdots & \dfrac{m^{(t)}_{h_1h_2}}{1-\beta_1^t}
\end{bmatrix}
\) (130)
.
\( \displaystyle
\hat V_{W_{h2}}^{(t)} = \frac{V_{W_{h2}}^{(t)}}{1-\beta_2^t}
=
\begin{bmatrix}
\dfrac{v^{(t)}_{11}}{1-\beta_2^t} & \cdots & \dfrac{v^{(t)}_{1h_2}}{1-\beta_2^t} \\
\vdots & \ddots & \vdots \\
\dfrac{v^{(t)}_{h_11}}{1-\beta_2^t} & \cdots & \dfrac{v^{(t)}_{h_1h_2}}{1-\beta_2^t}
\end{bmatrix}
\) (131)
.
\(
W_{h2}^{(t+1)} = W_{h2}^{(t)} – lr \cdot \,\big(\hat M_{W_{h2}}^{(t)} \oslash (\sqrt{\hat V_{W_{h2}}^{(t)}}+\epsilon)\big) =
\)
.
\( \displaystyle
=
\begin{bmatrix}
w^{(t)}_{11}-lr \cdot \dfrac{\hat m_{11}}{\sqrt{\hat v_{11}}+\epsilon} & \cdots & w^{(t)}_{1h_2}-lr \cdot \dfrac{\hat m_{1h_2}}{\sqrt{\hat v_{1h_2}}+\epsilon} \\
\vdots & \ddots & \vdots \\
w^{(t)}_{h_11}-lr \cdot \dfrac{\hat m_{h_11}}{\sqrt{\hat v_{h_11}}+\epsilon} & \cdots & w^{(t)}_{h_1h_2}-lr \cdot \dfrac{\hat m_{h_1h_2}}{\sqrt{\hat v_{h_1h_2}}+\epsilon}
\end{bmatrix}
\) (132)
.
Computation for Bh2:
\(
G_{B_{h2}}^{(t)} = \nabla_{B_{h2}}\mathcal{L}^{(t)} \in \mathbb{R}^{1\times h_2}, \quad
M_{B_{h2}}^{(t)}, V_{B_{h2}}^{(t)} \in \mathbb{R}^{1\times h_2}, \quad
\hat M_{B_{h2}}^{(t)}, \hat V_{B_{h2}}^{(t)} \in \mathbb{R}^{1\times h_2}
\) (133)
.
\(
M_{B_{h2}}^{(t)} = \beta_1 \cdot M_{B_{h2}}^{(t-1)} + (1-\beta_1) \cdot G_{B_{h2}}^{(t)}
=
\)
.
\(
=
\begin{bmatrix} \beta_1 \cdot m_1^{(t-1)}+(1-\beta_1) \cdot g_1 & \cdots & \beta_1 \cdot m_{h_2}^{(t-1)}+(1-\beta_1) \cdot g_{h_2} \end{bmatrix}
\) (134)
.
\(
V_{B_{h2}}^{(t)} = \beta_2 \cdot V_{B_{h2}}^{(t-1)} + (1-\beta_2) \cdot \big(G_{B_{h2}}^{(t)}\odot G_{B_{h2}}^{(t)}\big)
=
\)
.
\(
=
\begin{bmatrix} \beta_2 \cdot v_1^{(t-1)}+(1-\beta_2) \cdot g_1^2 & \cdots & \beta_2 \cdot v_{h_2}^{(t-1)}+(1-\beta_2) \cdot g_{h_2}^2 \end{bmatrix}
\) (135)
.
\( \displaystyle
\hat M_{B_{h2}}^{(t)} = \frac{M_{B_{h2}}^{(t)}}{1-\beta_1^t}
=
\begin{bmatrix} \dfrac{m_1^{(t)}}{1-\beta_1^t} & \cdots & \dfrac{m_{h_2}^{(t)}}{1-\beta_1^t} \end{bmatrix}
\) (136)
.
\( \displaystyle
\hat V_{B_{h2}}^{(t)} = \frac{V_{B_{h2}}^{(t)}}{1-\beta_2^t}
=
\begin{bmatrix} \dfrac{v_1^{(t)}}{1-\beta_2^t} & \cdots & \dfrac{v_{h_2}^{(t)}}{1-\beta_2^t} \end{bmatrix}
\) (137)
.
\(
B_{h2}^{(t+1)} = B_{h2}^{(t)} – lr \cdot \,\big(\hat M_{B_{h2}}^{(t)}\oslash(\sqrt{\hat V_{B_{h2}}^{(t)}}+\epsilon)\big)
=
\)
.
\( \displaystyle
=
\begin{bmatrix}
b_1^{(t)} – lr \cdot \dfrac{\hat m_1}{\sqrt{\hat v_1}+\epsilon} & \cdots & b_{h_2}^{(t)}-lr \cdot \dfrac{\hat m_{h_2}}{\sqrt{\hat v_{h_2}}+\epsilon}
\end{bmatrix}
\) (138)
.
Notes
-
This shows the calculation for individual examples (single samples) from the training dataset. Just as shown above, the method allows for averaging gradients within a Mini‑Batch or across the entire dataset at once.
-
In stochastic or mini-batch training the parameters Wh, Bh are updated after processing each training example or mini-batch, respectively. Before the start of each new epoch, the training examples are randomly shuffled. This eliminates the influence of the original order of objects and makes the sequence of gradient updates less dependent on the data structure, which usually promotes more stable training.
-
t– the iteration number at which new values of the neural network parameters Wh, Bh are computed.
-
See [4], [9], [12] for more details.
.
3.4 Estimation of the Training Results with Test Array
After completing the training set (Training Array) or finishing the current epoch, the model’s quality is assessed. For this purpose, the training and test sets (Training Array and Test Array) are used. The assessment can be carried out using formulas (2), …, (9). In the developed software, the average value of the loss function Loss is calculated using formula (9), and the Accuracy metric is calculated using formula (3).
During successful training, the value of the loss function Loss should, on average, decrease, while the value of Accuracy should increase.
When performing parameter updates on individual examples or mini-batches, the Loss and Accuracy values may temporarily deteriorate during certain iterations or epochs, and then improve again. This is due to the stochastic nature of gradient estimation: the gradient calculated on a single example or mini-batch may differ from the gradient calculated on the entire Training Array. This property applies to the SGD, Momentum, and Adam methods when they use the stochastic or mini-batch training mode.
If a trend emerges where the quality on the training set (Training Array) continues to improve, but the quality of training on the Test Array deteriorates, this indicates that an overfitting effect has occurred and the training process should be stopped. In the software, training is carried out as long as it is effective, i.e., the quality on the Test Array is improving. At the end of training, the best result among all epochs is selected.
Good training quality:
for Loss 0.0 – 0.2 (139)
for Accuracy 0.95 – 1.0 (140)
.
3.5 Initialization of Wh and Bh
There are two papers [2], [3] that justify the initialization of Wh and Bh. The initialization depends on the activation function. Poorly chosen initial values can lead to vanishing or exploding gradients.
Paper [2] justifies the initialization for a neural layer that uses ReLU as its activation function. For the hidden layer that uses the ReLU activation function, the Kaiming (He) initialization is used for Wh1, each element is drawn from a Gaussian distribution with mean 0.
ReLU: Kaiming He:
\( \displaystyle
W_{h1} \sim \mathcal{N} \left(0, \frac{2}{h_{0}}\right)
\) (141)
where
\( mean = 0 \)
\( \displaystyle variance = \frac{2}{h_{0}} \)
\( h_{0} \) – the number of neurons in the Input Layer (142)
The bias is initialized as:
\( B_{h1}=0.01 \) (143)
A small positive value of 0.01 is used for the bias so that the ReLU neurons start in their active region.
Paper [3] justifies the initialization for a neural layer that uses Sigmoid as its activation function. For the output layer that uses the Sigmoid activation function, the Xavier (Glorot) initialization is used for Wh2 each element is drawn from a Gaussian distribution with mean 0.
Sigmoid: Xavier:
\( \displaystyle
W_{h2} \sim \mathcal{N} \left(0, \frac{2}{h_{1}+h_{2}}\right)
\) (144)
where
\( mean = 0 \)
\( \displaystyle
variance = \frac{2}{h_{1}+h_{2}}
\)
\( h_{1} \) – the number of neurons in the Hidden Layer
\( h_{2} \) – the number of neurons in the Output Layer (145)
\( B_{h2} = 0 \) (146)
.
Octave Script:
% Choice the start w and b
% ReLU: Kaiming He: Wh1(:,:) = Gaussian(0, 2/h0), bh1=epsilon_h1=0.01
% Sigmoid: Xavier: Wh2(:,:) = Gaussian(0, 2/(h1+h2)), bh2=epsilon_h2=0.00
epsilon_h1 = 0.01;
epsilon_h2 = 0.00;
sigma_h1 = sqrt(2/h0);
sigma_h2 = sqrt(2/(h1+h2));
% Hidden Layer for ReLU
Wh1 = randn(h0, h1) * sigma_h1;
Bh1 = ones(1, h1) * epsilon_h1;
% Output for Sigmoid
Wh2 = randn(h1, h2) * sigma_h2;
Bh2 = ones(1, h2) * epsilon_h2;
.
4. Dense Neural Network Classification: Summary
Summary:
-
Normalization of the input signals in the range: 0 … 1
-
Normalization of the output signal for the classification task. Output value: 0…1, which is interpreted as the probability that the given object belongs to the target class.
-
A neural network with two hidden layers and the ReLU activation function allows solving any classification task. The output layer, consisting of one neuron with a sigmoid function, provides a normalized output: 0…1. If Output > 0.5, then the object described by the input data belongs to the given class. Otherwise – it does not belong.
Note
Our problem with the ellipse is solved using a neural network with only one hidden layer
-
Before training the network, an initial random initialization of the matrices Wh, Bh is performed in accordance with the Kaiming He and Xavier rules
-
Training the network using the Back Propagation method, employing gradient methods.
.
5. Results and Conclusions
The code for implementing the ellipse task was developed with the help of artificial intelligence:
-
Octave Script:
DenseNeuralNetworkEllipse.m
-
C code:
DenseNeuralNetworkEllipse.c/h
Results from Octave Script.
After random initialization of the matrices Wh, Bh, the starting performance indicators of the neural network were computed. They turned out to be unsatisfactory:
startTrainingLoss = 7.259312577598513e-01
startTestLoss = 7.160901358810766e-01
startTrainingAccuracy = 5.447204968944099e-01
startTestAccuracy = 5.646766169154229e-01
Training was tested for SGD, Momentum and Adam. Switching between methods was performed using the software switch: cfg.OptimizationAlgorithm. The best results were obtained using the Adam method.
After training the neural network using the Adam method, the optimal indicators were obtained at epoch 19. The Loss function is close to zero, and Accuracy approaches one, which indicates good training quality:
best.Epoch = 19
best.TrainingLoss = 0.081811
best.TestLoss = 0.070266
best.TrainingAccuracy = 0.959627
best.TestAccuracy = 0.975124
Figure 5-1 graphically shows the training results for normalized inputs. The red points do not belong to the ellipse, while the green points belong to our class (the ellipse), demonstrating a good result:

Figure 5-1: Training Results with Octave Script
.
Figures 5-2 and 5-3 show the training results for each epoch. The graphs show that the best result corresponds to epoch 19.

Figure 5-2: Adam: Training Process for Loss with Octave Script
.

Figure 5-3: Adam: Training Process for Accuracy with Octave Script
.
Note:
Similar results were obtained for the C code as well

Figure 5-4: Adam: Training Process with C Code
.
Note
Unfortunately, I was unable to train the neural network using the Batch (or deterministic) Gradient Method. It is possible that I was unable to select the training parameters correctly.
.
6. Octave GNU file DenseNeuralNetworkEllipse.m
The script builds a fully connected neural network with one hidden layer to solve the ellipse classification problem. Training is performed using gradient backpropagation methods. AI was used to generate the script and for review.
% Sigmoid Function
% Input parameters:
% InArray – input array
% Output parameters:
% OutArray – output array
function [OutArray] = Sigmoid_Function(InArray)
% Derivative of the Sigmoid Function
% Input parameters:
% InArray – input array
% Output parameters:
% OutArray – output array
function [OutArray] = Derivative_of_Sigmoid_Function(InArray)
% ReLU Function
% Input parameters:
% InArray – input array
% Output parameters:
% OutArray – output array
function [OutArray] = ReLU_Function(InArray)
% Derivative of the ReLU Function
% Input parameters:
% InArray – input array
% Output parameters:
% OutArray – output array
function [OutArray] = Derivative_of_ReLU_Function(InArray)
% Metrics calculation: Loss and Accuracy
% Input parameters:
% InArray – input array
% X1_Field – X1 column index
% X2_Field – X2 column index
% Y_Field – Y column index
% Wh1 – h1 matrix
% Bh1 – h1 bias matrix
% Wh2 – h2 matrix
% Bh2 – h2 bias matrix
% Output parameters:
% LossResult – loss
% AccuracyResult – accuracy
function [LossResult AccuracyResult] = CalculateMetrics_Function(InArray,X1_Field,X2_Field,Y_Field,Wh1,Bh1,Wh2,Bh2)
% Make the TrainingTestArrays.mat
% Input parameters:
% X1_Field – X1 column index
% X2_Field – X2 column index
% Y_Field – Y column index
% h – Layer list
% SeedVal – rand/randn
% Output parameters:
% nothing
function MakeTrainingTestArraysMat_Function(X1_Field,X2_Field,Y_Field,h,SeedVal)
% Make the WhBh.mat
% Input parameters:
% h – Layer list
% SeedVal – rand/randn
% Output parameters:
% nothing
function MakeWhBhMat_Function(h,SeedVal)
% Train Network: Deep Learning
% Input parameters:
% TrainingArr – input array
% X1_Field – X1 column index
% X2_Field – X2 column index
% Y_Field – Y column index
% h – Layer list
% cfg – optimization method
% Wh1 – h1 matrix
% Bh1 – h1 bias matrix
% Wh2 – h2 matrix
% Bh2 – h2 bias matrix
% SeedVal – rand/randn
% Output parameters:
% best.Wh1
% best.Bh1
% best.Wh2
% best.Bh2
% best.Epoch
% best.TrainingLoss
% best.TrainingAccuracy
% best.TestLoss – best
% best.TestAccuracy
% history.TrainingLoss
% history.TestLoss
% history.TrainingAccuracy
% history.TestAccuracy
function [best history] = TrainNetwork_Function(TrainingArr,TestArr,X1_Field,X2_Field,Y_Field,h,cfg,Wh1,Bh1,Wh2,Bh2,SeedVal)
% Calculation of the Network
% Input parameters:
% X – x1, x2
% Wh1 – h1 matrix
% Bh1 – h1 bias matrix
% Wh2 – h2 matrix
% Bh2 – h2 bias matrix
% Output parameters:
% Ypredict – prediction
function [Ypredict] = predictOutput_Function(X,Wh1,Bh1,Wh2,Bh2)
% Search Optimal Parameters
% Input parameters:
% TrainingArr – input array
% X1_Field – X1 column index
% X2_Field – X2 column index
% Y_Field – Y column index
% h – Layer list
% cfg – optimization method
% SeedVal – rand/randn
% Output parameters:
% optimal.Score = best.TestLoss – 0.01*best.TestAccuracy => min
% optimal.Epochs
% optimal.LearningRate
% optimal.BatchSize
% optimal.Result = best
function [optimal] = SearchOptimalParameters_Function(X1_Field,X2_Field,Y_Field,h,cfg,SeedVal)
.
7. C Language DenseNeuralNetworkEllipse.c/h
The C code models and trains a Dense Neural Network with one hidden layer to solve the ellipse classification problem. AI was used to generate the code and for review.
/*
Permuted Congruential Generator Initialization
Input
uint64_t seed – begin value
uint64_t increment – increment value
Return
void
*/
void PermutedCongruentialGenerator32_Init_FNC(uint64_t seed, uint64_t increment);
/*
Permuted Congruential Generator from the M. E. O’Neill
A uniformly distributed random
variable taking values in [0,0xFFFFFFFF]
M. E. O’Neill, “PCG: A Family of Simple Fast Space-Efficient Statistically
Good Algorithms for Random Number Generation”, Harvey Mudd College,
Technical Report HMC-CS-2014-0905, 2014
PCG – Permuted Congruential Generator
PRNG – Pseudo-Random Number Generator
Input
RandomStateStruct_t* RandomStatePtr – pointer on the RandomStateStruct_t
Return
uint32_t – random values 0…0xFFFFFFFF
*/
uint32_t PermutedCongruentialGenerator32_FNC(RandomStateStruct_t* RandomStatePtr);
/*
Permuted Congruential Generator
A uniformly distributed random
variable taking values in [0,1]
Input
void
Return
float – random values [0,1]
Note
4294967295 = 0xFFFFFFFF
*/
float RandomSingleFloat_FNC(void);
/*
A normally distributed random
variable with sigma=1, mean=0
Box-Muller Method
Input
void
Return
float – normally distributed random with sigma=1, mean=0
Note
General normal distribution with any mean and sigma values:
mean + sigma*NormalRandomSingleFloat_FNC()
*/
float NormalRandomSingleFloat_FNC(void);
/*
Fisher–Yates shuffle
randperm_u16()
Generates a random permutation of indices 0…n-1
Input
uint16_t *IndexArray_ptr – array for random indices
uint16_t n – number of elements
Return
void
*/
void randperm_u16(uint16_t *IndexArray_ptr, uint16_t n);
/*
Matrix from scalar
Input
uint16_t n
uint16_t m
float scalar
float (*result)[m] – pointer on the result matrix
result[n][m]
Return
void
*/
void matrixFromScalar(uint16_t n, uint16_t m, float scalar, float (*result)[m]);
/*
Matrix assign
Input
uint16_t n
uint16_t m
float (*matrix)[m] – pointer on the matrix[n][m]
float (*result)[m] – pointer on the result matrix
result[n][m] = matrix[n][m]
Return
void
*/
void matrixAssign(uint16_t n, uint16_t m, float (*matrix)[m], float (*result)[m]);
/*
Matrix multiplication
Input
uint16_t n
uint16_t m
uint16_t k
float (*mul1)[m] – pointer on the matrix mul1[n][m]
float (*mul2)[k] – pointer on the matrix mul2[m][k]
float (*result)[k] – pointer on the result matrix
result[n][k] = mul1[n][m] * mul2[m][k]
Return
void
*/
void matrixMul(uint16_t n, uint16_t m, uint16_t k, float (*mul1)[m], float (*mul2)[k], float (*result_ptr)[k]);
/*
Matrix Hadamard multiplication
Input
uint16_t n
uint16_t m
float (*mul1)[m] – pointer on the matrix mul1[n][m]
float (*mul2)[m] – pointer on the matrix mul2[n][m]
float (*result)[m] – pointer on the result matrix
result[n][m] = mul1[n][m]*mul2[n][m]
Return
void
*/
void matrixHadamardMul(uint16_t n, uint16_t m, float (*mul1)[m], float (*mul2)[m], float (*result)[m]);
/*
Matrix Hadamard division
Input
uint16_t n
uint16_t m
float (*div1)[m] – pointer on the matrix div1[n][m]
float (*div2)[m] – pointer on the matrix div2[n][m]
float (*result)[m] – pointer on the result matrix
result[n][m] = div1[n][m]/div2[n][m]
Return
void
*/
void matrixHadamardDiv(uint16_t n, uint16_t m, float (*div1)[m], float (*div2)[m], float (*result)[m]);
/*
Matrix addition
Input
uint16_t n
uint16_t m
float (*add1)[m] – pointer on the matrix add1[n][m]
float (*add2)[m] – pointer on the matrix add2[n][m]
float (*result)[m] – pointer on the result matrix
result[n][m] = add1[n][m] + add2[n][m]
Return
void
*/
void matrixAddition(uint16_t n, uint16_t m, float (*add1)[m], float (*add2)[m], float (*result)[m]);
/*
Matrix subtraction
Input
uint16_t n
uint16_t m
float (*sub1)[m] – pointer on the matrix sub1[n][m]
float (*sub2)[m] – pointer on the matrix sub2[n][m]
float (*result)[m] – pointer on the result matrix
result[n][m] = sub1[n][m] – sub2[n][m]
Return
void
*/
void matrixSubtraction(uint16_t n, uint16_t m, float (*sub1)[m], float (*sub2)[m], float (*result)[m]);
/*
Matrix multiplication by a scalar
Input
uint16_t n
uint16_t m
float (*matrix)[m] – pointer on the matrix matrix[n][m]
float scalar – scalar
float (*result)[m] – pointer on the result matrix
result[n][m] = scalar*matrix[n][m]
Return
void
*/
void matrixScalarMul(uint16_t n, uint16_t m, float (*matrix)[m], float scalar, float (*result)[m]);
/*
Matrix transposition
Input
uint16_t n
uint16_t m
float (*matrix)[m] – pointer on the matrix[n][m]
float (*result)[m] – pointer on the result matrix
result[m][n] = matrix[n][m]
Return
void
*/
void matrixTransposition(uint16_t n, uint16_t m, float (*matrix)[m], float (*result)[n]);
/*
Max Matrix
Input
float maxVal
uint16_t n
uint16_t m
float (*matrix)[m] – pointer on the matrix[n][m]
float (*result)[m] – pointer on the result matrix
result[n][m] = max(matrix[n][m],max)
Return
void
*/
void MaxMatrix(float maxVal, uint16_t n, uint16_t m, float (*matrix)[m], float (*result)[m]);
/*
Min Matrix
Input
float minVal
uint16_t n
uint16_t m
float (*matrix)[m] – pointer on the matrix[n][m]
float (*result)[m] – pointer on the result matrix
result[n][m] = min(matrix[n][m],min)
Return
void
*/
void MinMatrix(float minVal, uint16_t n, uint16_t m, float (*matrix)[m], float (*result)[m]);
/*
Logf Function for Matrix
Input
uint16_t n
uint16_t m
InArray[n][m] – input array
OutArray[n][m] – output array
Return
void
*/
void LogfFloat_FNC(uint16_t n, uint16_t m, float (*InArray)[m], float (*OutArray)[m]);
/*
Sigmoid Function for Matrix
Input
uint16_t n
uint16_t m
InArray[n][m] – input array
OutArray[n][m] – output array
Return
void
*/
void SigmoidFloat_FNC(uint16_t n, uint16_t m, float (*InArray)[m], float (*OutArray)[m]);
/*
Sqrt Function for Matrix
Input
uint16_t n
uint16_t m
InArray[n][m] – input array
OutArray[n][m] – output array
Return
void
*/
void SqrtFloat_FNC(uint16_t n, uint16_t m, float (*InArray)[m], float (*OutArray)[m]);
/*
Derivative of the Sigmoid Function for Matrix
Input
uint16_t n
uint16_t m
InArray[n][m] – input array
OutArray[n][m] – output array
Return
void
*/
void Derivative_of_SigmoidFloat_FNC(uint16_t n, uint16_t m, float (*InArray)[m], float (*OutArray)[m]);
/*
ReLU Function for Matrix
Input
uint16_t n
uint16_t m
InArray[n][m] – input array
OutArray[n][m] – output array
Return
void
*/
void ReLUFloat_FNC(uint16_t n, uint16_t m, float (*InArray)[m], float (*OutArray)[m]);
/*
Derivative of the ReLU Function for Matrix
Input
uint16_t n
uint16_t m
InArray[n][m] – input array
OutArray[n][m] – output array
Return
void
*/
void Derivative_of_ReLUFloat_FNC(uint16_t n, uint16_t m, float (*InArray)[m], float (*OutArray)[m]);
/*
Generate the Training and Test Arrays
Input
TrainingTestElement_t* Array – Array[Length]
uint16_t Length
Return
void
*/
void TrainingTestArraysInit_FNC(TrainingTestElement_t* Array, uint16_t Length);
/*
The Wh1, Bh1, Wh2, Bh2 Initialization
Input
uint16_t h0
uint16_t h1
uint16_t h2
Wh1 – Wh1[h0][h1]
Bh1 – Bh1[1][h1]
Wh2 – Wh2[h1][h2]
Bh2 – Bh2[1][h2]
Return
void
*/
void WhBhInit_FNC(uint16_t h0, uint16_t h1, uint16_t h2, float (*Wh1)[h1], float (*Bh1)[h1], float (*Wh2)[h2], float (*Bh2)[h2]);
/*
Calculate the Loss, Accuracy
Input
uint16_t Length
TrainingTestElement_t* Array
uint16_t h0
uint16_t h1
uint16_t h2
Wh1 – Wh1[h0][h1]
Bh1 – Bh1[1][h1]
Wh2 – Wh2[h1][h2]
Bh2 – Bh2[1][h2]
Return
LossAccuracyStruct_t – Metrics: Loss, Accuracy
*/
LossAccuracyStruct_t CalculateMetrics_FNC(uint16_t Length, TrainingTestElement_t* Array, uint16_t h0, uint16_t h1, uint16_t h2, float (*Wh1)[h1], float (*Bh1)[h1], float (*Wh2)[h2], float (*Bh2)[h2]);
/*
Train Network
Input
uint16_t TrainingLength
TrainingTestElement_t* TrainingArray
uint16_t TestLength
TrainingTestElement_t* TestArray
uint16_t h0
uint16_t h1
uint16_t h2
Wh1 – Wh1[h0][h1]
Bh1 – Bh1[1][h1]
Wh2 – Wh2[h1][h2]
Bh2 – Bh2[1][h2]
Return
Best_t – Best Results of the Training
*/
Best_t TrainNetwork_FNC(uint16_t TrainingLength, TrainingTestElement_t* TrainingArray, uint16_t TestLength, TrainingTestElement_t* TestArray, uint16_t h0, uint16_t h1, uint16_t h2, float (*Wh1)[h1], float (*Bh1)[h1], float (*Wh2)[h2], float (*Bh2)[h2]);
.
8. Download the DenseNeuralNetworkEllipse.m/c/h
You can download the files:
DenseNeuralNetworkEllipse.m/c/h
with the button:
.
9. Literature / References
[1] Richard P. Lippmann “An Introduction to Computing with Neural Nets“, IEEE ASSP Magazine, April 1987
[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun “Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification“, IEEE International Conference on Computer Vision, 6 February 2015
[3] Xavier Glorot, Yoshua Bengio “Understanding the difficulty of training deep freedforward neural networks“, JMLR Workshop and Conference Proceedings, vol. 9, 2010, pp. 249-256
[4] Ian Goodfellow, Yoshua Bengio, Aaron Courville “Deep Learning“, MIT Press, 2016
[5] Konstantin Vorontsov “Mathematical Methods of Pattern Learning“, Fizmatlit, MAI (Moscow Aviation Institute), Moscow, 2003
[6] Simon Haykin “Neural Networks. A Comprehensive Foundation“, Second Edition, Prentice Hall, Upper Saddle River, New Jersey, 1999
[7] Herbert Robbins, Sutton Monro “A Stochastic Approximation Method“, The Annals of Mathematical Statistics, 22(3), 400-407, New York, 1951
[8] B. T. Polyak “Some Methods of speeding up the Convergence of Iteration Methods“, USSR, Zhurnal Vychislitel’noi Matematiki i Matematicheskoi Fiziki (Computational Mathematics and Mathematical Physics), No. 5, 791-803, USSR, Moscow, 1962
[9] Diederik P. Kingma, Jimmy Lei Ba “Adam: A Method for Stochastic Optimization“, Proceedings of Intermational Conference on Learning Represantations (ICLR), San Diego, 2015
[10] Joseph, V. R. “Optimal ratio for data splitting.“ Statistical Analysis and Data Mining: The ASA Data Science Journal. 2022. Vol. 15, No. 4. P. 531–538. DOI
[11] Baum E. B., Haussler D. “What Size Net Gives Valid Generalization?“ Neural Computation. 1989. Vol. 1, No. 1. P. 151–160. DOI
[12] Poole D. L., Mackworth A. K. Artificial Intelligence: Foundations of Computational Agents. 3rd ed. Cambridge: Cambridge University Press, 2023. Section 8.2, “Improved Optimization”
[13] R. A. Horn, C. R. Johnson, “Matrix Analysis”, 2nd edition, Cambridge University Press, 2013
[14] G. Cybenko, “Approximation by Superpositions of a Sigmoidal Function”, Mathematics of Control, Signals and Systems, 2, 303–314, 1989.
[15] M. Leshno, V. Y. Lin, A. Pinkus, S. Schocken, “Multilayer Feedforward Networks with a Nonpolynomial Activation Function Can Approximate Any Function”, Neural Networks, 6(6), 861–867, 1993.
.
Appendix 1. Loss Function for \( \mathbf{\mathcal{L}_{\text{SE}}} = SquaredErrorLoss = \frac{1}{2}\cdot \left(\hat{Y} – Y\right)^2 \)
The squared error loss function is used when the output layer of the neural network produces a real number (or several real numbers, if the output layer has multiple outputs), i.e. when the neural network computes a continuous target quantity, such as a physical quantity or another numerical indicator. In this case, the activation in the output layer is linear: \( \hat{Y}= Z_{h2} \)
We consider a two-layer Dense Neural Network with one hidden layer:
\(
h_{0} \times h_{1} \times h_{2}
\) (A1-1)
.
Forward propagation.
Array Sizes:
\(
X \in \mathbb{R}^{1 \times h_0}, \quad
W_{h1} \in \mathbb{R}^{h_0 \times h_1}, \quad
B_{h1} \in \mathbb{R}^{1 \times h_1}, \quad
W_{h2} \in \mathbb{R}^{h_1 \times h_2}, \quad
B_{h2} \in \mathbb{R}^{1 \times h_2}
\) (A1-2)
.
\(
X =
\begin{bmatrix}
x_1 & x_2 & \cdots & x_{h_0}
\end{bmatrix}
\) (A1-3)
.
\(
W_{h1} =
\begin{bmatrix}
w_{11}^{h1} & w_{12}^{h1} & \cdots & w_{1h_1}^{h1} \\
w_{21}^{h1} & w_{22}^{h1} & \cdots & w_{2h_1}^{h1} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_01}^{h1} & w_{h_02}^{h1} & \cdots & w_{h_0h_1}^{h1}
\end{bmatrix}
\) (A1-4)
.
\(
B_{h1} =
\begin{bmatrix}
b_{1}^{h1} & b_{2}^{h1} & \cdots & b_{h_1}^{h1}
\end{bmatrix}
\) (A1-5)
.
\(
W_{h2} =
\begin{bmatrix}
w_{11}^{h2} & w_{12}^{h2} & \cdots & w_{1h_2}^{h2} \\
w_{21}^{h2} & w_{22}^{h2} & \cdots & w_{2h_2}^{h2} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_11}^{h2} & w_{h_12}^{h2} & \cdots & w_{h_1h_2}^{h2}
\end{bmatrix}
\) (A1-6)
.
\(
B_{h2} =
\begin{bmatrix}
b_{1}^{h2}, & b_{2}^{h2} & \cdots & b_{h_2}^{h2}
\end{bmatrix}
\) (A1-7)
.
\(
Z_{h1} = X \cdot W_{h1} + B_{h1} =
\)
\(
=
\begin{bmatrix} x_1 & x_2 & \cdots & x_{h_0} \end{bmatrix}
\cdot
\begin{bmatrix}
w_{11} & w_{12} & \cdots & w_{1h_1} \\
w_{21} & w_{22} & \cdots & w_{2h_1} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_01} & w_{h_02} & \cdots & w_{h_0h_1}
\end{bmatrix}
+
\begin{bmatrix} b_1 & b_2 & \cdots & b_{h_1} \end{bmatrix} =
\)
\(
=
\begin{bmatrix}
\displaystyle\sum_{i=1}^{h_0} x_iw_{i1} + b_1 & \displaystyle\sum_{i=1}^{h_0} x_iw_{i2} + b_2 & \cdots & \displaystyle\sum_{i=1}^{h_0} x_iw_{ih_1} + b_{h_1}
\end{bmatrix}
\) (A1-8)
.
\(
A_{h1}
= \mathrm{ReLU}(Z_{h1}) =
\begin{bmatrix}
\mathrm{ReLU}(z_1) & \mathrm{ReLU}(z_2) & \cdots & \mathrm{ReLU}(z_{h_1})
\end{bmatrix}
=
\begin{bmatrix} a_1 & a_2 & \cdots & a_{h_1} \end{bmatrix}
\) (A1-9)
.
\(
Z_{h2} = A_{h1} \cdot W_{h2} + B_{h2} =
\)
\(
=
\begin{bmatrix} a_1 & a_2 & \cdots & a_{h_1} \end{bmatrix}
\cdot
\begin{bmatrix}
w_{11} & w_{12} & \cdots & w_{1h_2} \\
w_{21} & w_{22} & \cdots & w_{2h_2} \\
\vdots & \vdots & \ddots & \vdots \\
w_{h_11} & w_{h_12} & \cdots & w_{h_1h_2}
\end{bmatrix}
+
\begin{bmatrix} b_1 & b_2 & \cdots & b_{h_2} \end{bmatrix} =
\)
\(
=
\begin{bmatrix}
\displaystyle\sum_{j=1}^{h_1} a_jw_{j1} + b_1 & \displaystyle\sum_{j=1}^{h_1} a_jw_{j2} + b_2 & \cdots & \displaystyle\sum_{j=1}^{h_1} a_jw_{jh_2} + b_{h_2}
\end{bmatrix}
\) (A1-10)
.
\(
\hat{Y}
=
Z_{h2}
=
\begin{bmatrix}
z_1 & z_2 & \cdots & z_{h_2}
\end{bmatrix}
=
\begin{bmatrix} \hat{y}_1 & \hat{y}_2 & \cdots & \hat{y}_{h_2} \end{bmatrix}
\) (A-11)
.
Back propagation.
Array Sizes:
.
\(
X \in \mathbb{R}^{1 \times h_{0}}, \quad
W_{h1} \in \mathbb{R}^{h_{0} \times h_{1}}, \quad
B_{h1} \in \mathbb{R}^{1 \times h_{1}}
\)
\(
Z_{h1}, A_{h1} \in \mathbb{R}^{1 \times h_{1}}, \quad
W_{h2} \in \mathbb{R}^{h_1 \times h_{2}}, \quad
B_{h2} \in \mathbb{R}^{1 \times h_{2}}
\)
\(
Z_{h2}, \hat{Y}, Y, \delta_{h2} \in \mathbb{R}^{1 \times h_{2}}, \quad
\delta_{h1} \in \mathbb{R}^{1 \times h_{1}}
\) (A1-12)
.
\(
\mathcal{L}_{\text{SE}} = SquaredErrorLoss
=
\)
\( \displaystyle
=
\frac{1}{2}\cdot\left(\hat{Y} – Y\right)^2 = \frac{1}{2}\cdot \begin{bmatrix} (\hat{y}_1-y_1)^2 & (\hat{y}_2-y_2)^2 & \cdots & (\hat{y}_{h_2}-y_{h_2})^2 \end{bmatrix}
\) (A1-13)
.
\( \displaystyle
\frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}} = \hat{Y} – Y
\) (A1-14)
.
\( \displaystyle
\frac{\partial \hat{Y}}{\partial Z_{h2}} =
\frac{\partial Z_{h2}}{\partial Z_{h2}} = 1
\) (A1-15)
.
gradient(Zh2):
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{SE}}}{\partial Z_{h2}} = \delta_{h2} =
\frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}
= \hat{Y} – Y =
\)
\(
=
\begin{bmatrix}
(\hat{y}_1 – y_1) & (\hat{y}_2 – y_2) & \cdots & (\hat{y}_{h_2} – y_{h_2})
\end{bmatrix}
\) (A1-16)
.
gradient(Wh2):
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{SE}}}{\partial W_{h2}} = \frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}\cdot\frac{\partial Z_{h2}}{\partial W_{h2}}
= A_{h1}^{\top}\cdot\delta_{h2}
=
\)
\( \displaystyle
=
\begin{bmatrix}
a_1\cdot(\hat{y}_1 – y_1) & a_1\cdot(\hat{y}_2 – y_2) & \cdots & a_1\cdot(\hat{y}_{h_2} – y_{h_2}) \\
a_2\cdot(\hat{y}_1 – y_1) & a_2\cdot(\hat{y}_2 – y_2)
& \cdots & a_2\cdot(\hat{y}_{h_2} – y_{h_2})\\
\vdots & \vdots & \ddots & \vdots \\
a_{h_1}\cdot(\hat{y}_1 – y_1) & a_{h_1}\cdot(\hat{y}_2 – y_2) & \cdots & a_{h_1}\cdot(\hat{y}_{h_2} – y_{h_2})
\end{bmatrix}
\) (A1-17)
.
gradient(Bh2):
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{SE}}}{\partial B_{h2}} = \frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}\cdot\frac{\partial Z_{h2}}{\partial B_{h2}}
= \delta_{h2}
=
\begin{bmatrix}
(\hat{y}_1 – y_1) & (\hat{y}_2 – y_2) & \cdots & (\hat{y}_{h_2} – y_{h_2})
\end{bmatrix}
\) (A1-18)
.
gradient(Ah1):
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{SE}}}{\partial A_{h1}}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}
=
\delta_{h2}\cdot W_{h2}^{\top}
=
\begin{bmatrix}
\displaystyle\sum_{k=1}^{h_2} \delta_{h2,k}\cdot w_{1k} \\
\displaystyle\sum_{k=1}^{h_2} \delta_{h2,k}\cdot w_{2k} \\
\vdots \\
\displaystyle\sum_{k=1}^{h_2} \delta_{h2,k}\cdot w_{h_1k}
\end{bmatrix}^{\top}
=
\)
\(
=
\begin{bmatrix}
\sum_{k=1}^{h_2}(\hat{y}_k-y_k)\cdot w_{1k} &
\sum_{k=1}^{h_2}(\hat{y}_k-y_k)\cdot w_{2k} &
\cdots &
\sum_{k=1}^{h_2}(\hat{y}_k-y_k)\cdot w_{h_1k}
\end{bmatrix}
\) (A1-19)
.
gradient(Zh1):
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{SE}}}{\partial Z_{h1}} = \delta_{h1}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}\cdot\frac{\partial A_{h1}}{\partial Z_{h1}}
=
\left(\frac{\partial \mathcal{L}_{\text{SE}}}{\partial A_{h1}}\right)\odot \mathrm{ReLU}'(Z_{h1})
=
\)
\(
=
\begin{bmatrix}
g_1 & g_2 & \cdots & g_{h_1}
\end{bmatrix}
\) (A1-20)
.
gradient(Wh1):
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{SE}}}{\partial W_{h1}}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}\cdot\frac{\partial A_{h1}}{\partial Z_{h1}}\cdot\frac{\partial Z_{h1}}{\partial W_{h1}}
=
X^{\top}\cdot\delta_{h1}
=
\)
\(
=
\begin{bmatrix}
x_1\cdot g_1 & x_1\cdot g_2 & \cdots & x_1\cdot g_{h_1} \\
x_2\cdot g_1 & x_2\cdot g_2 & \cdots & x_2\cdot g_{h_1} \\
\vdots & \vdots & \ddots & \vdots \\
x_{h_0}\cdot g_1 & x_{h_0}\cdot g_2 & \cdots & x_{h_0}\cdot g_{h_1}
\end{bmatrix}
\) (A1-21)
.
gradient(Bh1):
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{SE}}}{\partial B_{h1}}
= \delta_{h1}
=
\frac{\partial \mathrm{\mathcal{L}_{\text{SE}}}}{\partial \hat{Y}}\cdot\frac{\partial \hat{Y}}{\partial Z_{h2}}\cdot\frac{\partial Z_{h2}}{\partial A_{h1}}\cdot\frac{\partial A_{h1}}{\partial Z_{h1}}\cdot\frac{\partial Z_{h1}}{\partial B_{h1}}
=
\begin{bmatrix}
g_1 & g_2 & \cdots & g_{h_1}
\end{bmatrix}
\) (A1-22)
.
Correction of W and B using gradient method:
.
\( W_{h2}^{(t+1)} = W_{h2}^{(t)} – lr \cdot \text{gradient}(W_{h2}) = W_{h2}^{(t)} – lr \cdot A^{\top}_{h1} \cdot \delta_{h2} \)
\( B_{h2}^{(t+1)} = B_{h2}^{(t)} – lr \cdot \text{gradient}(B_{h2}) = B_{h2}^{(t)} – lr \cdot \delta_{h2} \)
\( W_{h1}^{(t+1)} = W_{h1}^{(t)} – lr \cdot \text{gradient}(W_{h1}) = W_{h1}^{(t)} – lr \cdot X^{\top} \cdot \delta_{h1} \)
\( B_{h1}^{(t+1)} = B_{h1}^{(t)} – lr \cdot \text{gradient}(B_{h1}) = B_{h1}^{(t)} – lr \cdot \delta_{h1} \) (A1-23)
.
Note
For more details on the squared loss function see the [4], [6]
.
Appendix 2. The Hessian Matrix for Classifying Critical Points
We consider a two-layer Dense Neural Network with one hidden layer:
.
\(
h_{0} \times h_{1} \times h_{2}
\) (A2-1)
.
The hidden layer \( h_{1} \) uses ReLU
The output layer uses \( h_{2} \) the sigmoid activation function \( \sigma \) .
.
Size of the Hessian:
.
\(
matrix_{size} = h_{0} \cdot h_{1} + h_{1} + h_{1} \cdot h_{2} + h_{2} = (h_{0} + h_{2} + 1) \cdot h_{1} + h_{2}
\) (A2-2)
.
Take a simple example:
.
\(
h_{0} =2, h_{1} = 4, h_{2} = 1
\) (A2-3)
.
Then:
.
\(
matrix_{size} = 2 \cdot 4 + 4 + 4 \cdot 1 + 1 = 17
\) (A2-4)
.
The variables that define the operation of the neural network:
.
\(
w_{11}^{(1)}, w_{21}^{(1)}, b_{1}^{(1)}, w_{12}^{(1)}, w_{22}^{(1)}, b_{2}^{(1)}, w_{13}^{(1)}, w_{23}^{(1)}, b_{3}^{(1)}, w_{14}^{(1)}, w_{24}^{(1)}, b_{4}^{(1)}, w_{11}^{(2)}, w_{21}^{(2)}, w_{31}^{(2)}, w_{41}^{(2)}, b^{(2)}
\) (A2-5)
.
These variables can be arranged along a row and the same variables along a column. At the intersection of a column variable and a row variable lies the Hessian matrix element equal to the second partial derivative with respect to the row and column variables. The Hessian then takes the form:
.
\( \mathbf{H} =
\begin{bmatrix}
\dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)} \partial w_{11}^{(1)}} & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)} \partial w_{21}^{(1)}} & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)} \partial b_{1}^{(1)}} & \cdots & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)} \partial b^{(2)}} \\[1.5em]
\dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{21}^{(1)} \partial w_{11}^{(1)}} & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{21}^{(1)} \partial w_{21}^{(1)}} & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{21}^{(1)} \partial b_{1}^{(1)}} & \cdots & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{21}^{(1)} \partial b^{(2)}} \\[1.5em]
\vdots & \vdots & \vdots & \ddots & \vdots \\[1em]
\dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial b^{(2)} \partial w_{11}^{(1)}} & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial b^{(2)} \partial w_{21}^{(1)}} & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial b^{(2)} \partial b_{1}^{(1)}} & \cdots & \dfrac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial b^{(2)} \partial b^{(2)}}
\end{bmatrix}
\) (A2-6)
.
The complete first row of the Hessian:
.
\( \displaystyle
\begin{aligned}
h_{1,1} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{11}^{(1)}}, &
h_{1,2} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{21}^{(1)}}, &
h_{1,3} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial b_{1}^{(1)}}, &
h_{1,4} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{12}^{(1)}} \\[8pt]
h_{1,5} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{22}^{(1)}}, &
h_{1,6} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial b_{2}^{(1)}}, &
h_{1,7} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{13}^{(1)}}, &
h_{1,8} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{23}^{(1)}} \\[8pt]
h_{1,9} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial b_{3}^{(1)}}, &
h_{1,10} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{14}^{(1)}}, &
h_{1,11} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{24}^{(1)}}, &
h_{1,12} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial b_{4}^{(1)}} \\[8pt]
h_{1,13} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{11}^{(2)}}, &
h_{1,14} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{21}^{(2)}}, &
h_{1,15} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{31}^{(2)}}, &
h_{1,16} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{41}^{(2)}} \\[8pt]
h_{1,17} &= \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial b^{(2)}}
\end{aligned}
\) (A2-7)
.
Worked example: computing \( h_{1,1} \) and \( h_{1,17} \)
Computing \( h_{1,1} \):
.
\( \displaystyle
h_{1,1} = \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{11}^{(1)}}
\) (A2-8)
.
First, take the first partial derivative:
.
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}} = \frac{\partial \mathcal{L}_{\text{CE}}}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z_{1}^{(2)}} \cdot \frac{\partial z_{1}^{(2)}}{\partial a_{1}^{(1)}} \cdot \frac{\partial a_{1}^{(1)}}{\partial z_{1}^{(1)}} \cdot \frac{\partial z_{1}^{(1)}}{\partial w_{11}^{(1)}} =
\)
\(
= (\hat{y} – y) \cdot w_{11}^{(2)} \cdot d_{1}^{(1)} \cdot x_{1}
\) (A2-9)
where
\( \displaystyle
\frac{\partial \mathcal{L}_{\text{CE}}}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z_{1}^{(2)}} = \hat{y} – y
\)
\( \displaystyle
\frac{\partial z_{1}^{(2)}}{\partial a_{1}^{(1)}} = w_{11}^{(2)}
\)
\( \displaystyle
\frac{\partial a_{1}^{(1)}}{\partial z_{1}^{(1)}} = d_{1}^{(1)}
\) where \( d_{1}^{(1)} = \mathrm{ReLU}'(z_{1}^{(1)}) \)
\( \displaystyle
\frac{\partial z_{1}^{(1)}}{\partial w_{11}^{(1)}} = x_{1}
\) (A2-10)
.
Now take the second partial derivative of (A2-9) with respect to \( w_{11}^{(1)} \). In this formula only depends on \( w_{11}^{(1)} \).
Then:
.
\( \displaystyle
\frac{\partial \hat{y}}{\partial w_{11}^{(1)}} = \frac{\partial \hat{y}}{\partial z_{1}^{(2)}} \cdot \frac{\partial z_{1}^{(2)}}{\partial a_{1}^{(1)}} \cdot \frac{\partial a_{1}^{(1)}}{\partial z_{1}^{(1)}} \cdot \frac{\partial z_{1}^{(1)}}{\partial w_{11}^{(1)}} = \hat{y} \cdot (1 – \hat{y}) \cdot w_{11}^{(2)} \cdot d_{1}^{(1)} \cdot x_{1}
\) (A2-11)
where
\( \displaystyle
\frac{\partial \hat{y}}{\partial z_{1}^{(2)}} = \hat{y} \cdot (1 – \hat{y})
\)
\( \displaystyle
\frac{\partial z_{1}^{(2)}}{\partial a_{1}^{(1)}} = w_{11}^{(2)}
\)
\( \displaystyle
\frac{\partial a_{1}^{(1)}}{\partial z_{1}^{(1)}} = d_{1}^{(1)}
\)
\( \displaystyle
\frac{\partial z_{1}^{(1)}}{\partial w_{11}^{(1)}} = x_{1}
\) (A2-12)
.
Then:
.
\( \displaystyle
h_{1,1} = \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial w_{11}^{(1)}} = \hat{y} \cdot (1 – \hat{y}) \cdot (w_{11}^{(2)})^2 \cdot (d_{1}^{(1)})^2 \cdot (x_{1})^2
\) (A2-13)
.
Computing \( h_{1,17} \):
.
\( \displaystyle
h_{1,17} = \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial b^{(2)}}
\) (A2-14)
.
Using the result (A2-9) and taking the partial derivative of \( \hat{y} \) with respect to \( b^{(2)} \):
.
\( \displaystyle
\frac{\partial \hat{y}}{\partial b^{(2)}} = \frac{\partial \hat{y}}{\partial z_{1}^{(2)}} \cdot \frac{\partial z_{1}^{(2)}}{\partial b^{(2)}} = \hat{y} \cdot (1 – \hat{y})
\) (A2-15)
where
\( \displaystyle
\frac{\partial \hat{y}}{\partial z_{1}^{(2)}} = \hat{y} \cdot (1 – \hat{y})
\)
\( \displaystyle
\frac{\partial z_{1}^{(2)}}{\partial b^{(2)}} = 1
\) (A2-16)
.
As a result we obtain:
.
\( \displaystyle
h_{1,17} = \frac{\partial^2 \mathcal{L}_{\text{CE}}}{\partial w_{11}^{(1)}\partial b^{(2)}} = \hat{y} \cdot (1 – \hat{y}) \cdot w_{11}^{(2)} \cdot d_{1}^{(1)} \cdot x_{1}
\) (A2-17)
.
Note
All remaining elements of the Hessian are computed in an analogous manner
The Hessian is used to analyze the critical (stationary) points of the loss function. A critical point is a point where the gradient of the loss function equals zero:
\( \nabla{\mathcal{L}}(\Theta) = 0 \) (A2-18)
where
\( \Theta \) – denotes the variables from (A2-5)
.
Table A2-1 below shows the classification of critical points of the loss function, based on computing and analyzing the eigenvalues of the Hessian matrix:
.

Table A2-1: Classification of Critical Points of the Loss Function by the Hessian
.
Practical Approximations for Large Networks:
Computing the second derivatives, and then the eigenvalues of the full Hessian, for a large neural network is, as a rule, computationally intractable. To make the problem solvable, a simplification is used that relies on computing second derivatives only within each layer, while the cross-derivatives — that is, the second derivatives with respect to variables from different layers — are taken to be zero. For our two-layer neural network, the full Hessian can be written as a block matrix:
\(
\mathbf H =
\begin{bmatrix}
\mathbf H_{11} & \mathbf H_{12} \\
\mathbf H_{21} & \mathbf H_{22}
\end{bmatrix}
\) (A2-19)
where
\( \mathbf H_{11} \) – the second derivatives for the first (hidden) layer
\( \mathbf H_{22} \) – the second derivatives for the second (output) layer
\( \mathbf H_{12} \), \( \mathbf H_{21} \) – the second cross-derivatives
.
The simplified Hessian looks like:
.
\(
\mathbf H \approx \widetilde{\mathbf H} =
\begin{bmatrix}
\mathbf H_{11} & \mathbf 0 \\
\mathbf 0 & \mathbf H_{22}
\end{bmatrix}
\) (A2-20)
.
In this case, all the necessary computations become far less demanding and make the required calculations feasible in practice.
This method is called K-FAC:
K-FAC — Kronecker-Factored Approximate Curvature.
Often, even the K-FAC simplification does not make the problem solvable due to the remaining computational burden. In that case, the Diagonal Hessian approximation (also called the Jacobi diagonal approximation) is used. Here, only the diagonal elements of the Hessian are computed, and they are taken as an approximation to the eigenvalues of the matrix. This works when the diagonal elements of the matrix dominate the corresponding row values. This follows from the theorem of Semyon Aronovich Gershgorin. See [13].
Gershgorin Circle Theorem (or “Gershgorin Disc Theorem”):
.
\(
|\lambda-a_{ii}|\le\sum_{j\ne i}|a_{ij}|=R_i
\) (A2-21)
.
Note
For more details on the Hessian, see [4], [6], [13]
.

