You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In this tutorial we will train a neural network classifier to differentiate between images of horizontal and vertical lines.
We will code a neural network from scratch using only Python's numpy library, and we will go through all the steps of the classic machine learning training loop comprising the forward step, backpropagation, and parameters update.
The model will be evaluated on two validation sets.
Alternatively, open the notebook in Google Colab by clicking the "Open in Colab" button.
The data
The input (training) data $x^{[0]}$ comprises 24 3x3 pixel images grouped into two classes: vertical and horizontal lines. Each pixel assumes a grayscale value between 0 and 1:
The data is stored in a CSV file data/lines_3x3_train.csv (link), where each row contains pixel intensities of a single image.
The last column determines the class of the image: 0 for vertical, 1 for horizontal lines.
The image below depicts the entire batch of inputs with $M=24$ examples as columns of $N=9$ pixels corresponding to a single 3x3 pixel image:
The "ground truth" vector with class labels, 0 for vertical and 1 for horizontal lines, for all examples:
Rows correspond to the two classes.
The value 1 indicates the class that a particular example is lebeled with.
The first 12 examples belong to class 0 (vertical lines), hence the row for that class contains 1s.
These ground truth classification labeles will be used later to compare to class probabilities calculated by the network.
The training of our NN will aim to minimize the difference between the two distributions by changing parameters of the network.
The difference is quantified by a so-called loss function.
The network
Our neural-network has a two-layer, fully connected architecture.
The input layer $A^{[0]}$ has 9 nodes (neurons) that correspond to 9 pixels in every 3x3 input image.
The hidden layer $A^{[1]}$ has 6 neurons with a rectified linear unit (ReLU) activation function.
The output layer $A^{[2]}$ has 2 neurons that correspond to two classes.
The softmax normalization$S$ converts the output vector into a probability distribution of two possible outcomes: horizontal or vertical line.
This probability distirbution will be compared to the ground truth distribution $Y$ from the labeled data.
$x^{[0]}$, the input vector with $N=9$ pixels of a single image, i.e., an example; dimensions 9x1.
$W^{[1]}$, the weight matrix of the first (hidden) layer; comprises 6 rows corresponding to the number of neurons and 9 columns corresponding to the size of the input layer; dims. 6x9.
$b^{[1]}$, bias of the first layer; a vector with 6 elements; dims. 6x1.
$W^{[2]}$, the weight matrix of the second (output) layer; dims. 2x6.
$b^{[2]}$, bias vector; 2 elements corresponding to two classes; dims. 2x1.
The rectifier linear unit function ReLU is defined as follows:
The softmax function for a single element $x_i$ is given by:
$$
S(x_i) = e^{x_i} / \sum_{k=1}^{C} e^{x_k}
$$
Loss function
The loss function quantifies the disparity between two probability distributions: the calculated output and the true output given by the labeled data.
Here, we use the cross-entropy loss function:
Where $Y$ is the one-hot encoded vector of the ground truth classification labels, and $S$ is the output vector $A^{[2]}$ from the softmax function $S(z^{[2]})$, which in turn depends on all the weights and biases defined in equations for the forward propagation.
The sum is over classes, which in our case goes only from 1 to 2.
In layman's terms, $\mathcal{L}$ quantifies divergence between two discrete probability distributions.
If a labeled example belongs to class 0, the true probability distribution is $Y = [1, 0]$.
The cross-entropy for probability distributions $S$ calculated by the NN is then:
The loss function decreases, the closer the calculated probability distribution is to the ground truth.
The aim of the training (the optimization) is to make $\mathcal{L}$ as small as possible by cleverly changing network parameters.
Backward propagation
The loss function depends on many parameters that can be changed to minimize it.
Our small network has 74 "knobs" to manipulate ($W$ and $b$), which makes the task of minimizing $\mathcal{L}$ pretty daunting already for our tiny example.
But fortunately, not all is hopeless.
For the "clever changes" of network parameters we turn to calculus!
Turns out that the minima in the multidimensional landscape defined by the loss function can be identified by following the direction of the steepest gradient.
This means that for the optimization step, we need to compute gradients (more precisely, the Jacobian) of the loss function $\mathcal{L}$ with respect to all parameters of the model, i.e., all weights $W$ and biases $b$.
As an illustration, consider a plot of the Himmelblau's function that depends only on two parameters $x$ and $y$.
It has one local maximum and four identical local minima.
Starting from an arbitrary point we can find one of the minima by moving along the steepest gradient.
To achieve that we need to (1) calculate the gradients, i.e., partial derivatives with respect to all parameters and (2) find a way to iteratively update the parameters is a step-fashion.
The code for this illustration is in the scripts/himmelblau.ipynbnotebook.
Gradients
Using the chain rule, we obtain all partial derivatives of the loss function:
The size of each update is determined by $\alpha$, the learning ratehyperparameter.
Initialization
Weight matrices $W$ are initialized with random values drawn from a normal distribution with mean $\mu = 0$ and variance $\sigma^2 = 1 / n^{[l-1]}$, where $n^{[l-1]}$ is the number of neurons in layer $l-1$.
Biases are initialized with zeros.
This so-called Xavier initialization ensures that the mean activation across layers is zero and that the variance stays the same in every layer.
This prevents the gradients of the network’s activations from vanishing or exploding.
Training
After initializing the parameters, we will iteratively adjust them to minimize the loss function for the given input data.
The adjustments will follow the gradients.
The training of our neural network is a loop comprising the following steps:
Forward loop - calculate the output $A^{[2]}$ from the input $x^{[0]}$ using new parameters,
Backpropagation - calculate the gradients of the loss function at the new output,
Update the parameters using the gradients.
The loop is repeated for a fixed number of iterations or until desired accuracy is achieved.
Batch
In our example, owing to the tiny size of our dataset, the loss function is minimized over the entire input, i.e., losses are calculated for every example and then summed up over all examples.
This is unfeasible for real-life datasets, and the input must be split into batches.
The size of a batch is a hyperparameter and its choice may heavily impact the optimization.
The loop
The animation below shows parameter changes during the training.
Warm and cold colors corresponds to positive and negative values, respectively.
Gray scale colors are used for matrices with only positive values; black corresponds to 0 and white to 1.
The prediction matrix $A^{[2]}$ visualizes class probabilities calculated for every example in the input dataset.
Red and green dots indicate incorrect and correct predictions, respectively.
Observations
The parameter optimization achieves maximum accuracy at the 68th iteration.
Validation
Set 1
Similar to the training set, the validation set comprises 18 3x3 pixel images with horizontal and vertical lines, where the intensity of single pixels within lines are reduced from 1 to 0.4.
The validation data is stored in a CSV file data/lines_3x3_valid_1.csv (link).
The model achieves accuracy 1 on this validation set.
Set 2
The second validation set is just like the training set except pixel values have an additional Gaussian noise with mean 0 and standard deviation 0.2.
Values are still clipped to the [0,1] range.
The validation data is stored in a CSV file data/lines_3x3_valid_1.csv (link).
The model achieves accuracy 1.0 on this validation set.
Further reading
[1] Samson Zhang, Simple MNIST NN from scratch (numpy, no TF/Keras), Kaggle, 2018; HTML link.
[2] Jeremy Howard and Sylvain Gugger, Practical Deep Learning for Coders: Chapter 17 - A Neural Net from the Foundations, fast.ai; HTML link.
[3] Shivam Mehta, Deriving categorical cross entropy and softmax, 2023; HTML link.
[4] Eli Bendersky, The Softmax function and its derivative, 2016; HTML link.
[5] Katanforoosh & Kunin, Initializing neural networks, deeplearning.ai, 2019; HTML link
The first term on the r.h.s. equals to 1 only if $i = j$, and 0 otherwise, thus $\partial x_i / \partial x_k = \delta_{ik}$.
Since $\partial e^{x_k} / \partial x_k = e^{x_k}$, the entire second term is simply the softmax function of $x_k$.
Thus we obtain: