Skip to main content

Assignment 1

Write your own backpropagation code and keep track of your experiments using wandb.ai
Last updated: April 7, 2024

Introduction

  • The goal of this assignment is twofold:

    1. Implement and use gradient descent (and its variants) with backpropagation for a classification task.
    2. Get familiar with Wandb, a cool tool for running and keeping track of a large number of experiments.
  • I have used Python (NumPy and Pandas) for our implementation.

  • I have not used the following packages from Keras, PyTorch, TensorFlow: optimizers, layers.

  • I have used Keras and TensorFlow only for importing the data.

  • I have used sklearn for train-test-split only.





Problem Statement

In this assignment you need to implement a feedforward neural network and write the backpropagation code for training the network. We strongly recommend using numpy for all matrix/vector operations. You are not allowed to use any automatic differentiation packages. This network will be trained and tested using the Fashion-MNIST dataset. Specifically, given an input image (28 x 28 = 784 pixels) from the Fashion-MNIST dataset, the network will be trained to classify the image into 1 of 10 classes.


Question 1 (2 Marks)

Download the fashion-MNIST dataset and plot 1 sample image for each class as shown in the grid below. Use "from keras.datasets import fashion_mnist" for getting the fashion mnist dataset.




1 selected runs


Question 2 (10 Marks)

Implement a feedforward neural network which takes images from the fashion-mnist data as input and outputs a probability distribution over the 10 classes.

Your code should be flexible so that it is easy to change the number of hidden layers and the number of neurons in each hidden layer.

We will check the code for implementation and ease of use.



Answer

In this implementation, we have developed a fully customizable feedforward neural network that takes input data in the form of images and outputs a probability distribution over the 10 classes.

Key features of our implementation include:

  • Parameter Storage: We use a dictionary to store the parameter values (i.e., weights and biases) for each layer. For a single layer, weights are stored as a matrix and biases as a vector.
  • Customizable Architecture: The number of hidden layers and the number of neurons in each hidden layer can be easily adjusted as per the user's requirements.
  • Activation Functions: Users have the option to choose from three different activation functions: "Tanh," "Sigmoid," and "ReLU."
  • Initialization Methods: We have implemented two kinds of weight initialization methods: "Random" and "Xavier."

To execute the neural network:

  • With Hyperparameter Sweeps: Use the "Run all Cells" option to perform hyperparameter sweeps, which are logged into the Wandb workspace.
  • Without Hyperparameter Sweeps: For normal execution without hyperparameter tuning, you can directly execute the cell for test data, which contains all the best-chosen hyperparameters.


Question 3 (18 Marks)

Implement the backpropagation algorithm with support for the following optimisation functions

  • sgd
  • momentum based gradient descent
  • nesterov accelerated gradient descent
  • rmsprop
  • adam
  • nadam

(12 marks for the backpropagation framework and 2 marks for each of the optimisation algorithms above)

We will check the code for implementation and ease of use (e.g., how easy it is to add a new optimisation algorithm such as Eve). Note that the code should be flexible enough to work with different batch sizes.



Answer

All the given optimization functions have been implemented, along with an independently written backpropagation function.

Adding a new optimization function is quite straightforward. A template for creating a new optimization function has been included in the code (in the section following the implementation of the optimization functions). By following those steps, one can quite easily integrate any new optimization function.

Brief Steps:

  1. Define the function name.
  2. Declare an empty dictionary to store the gradients. (And other dictionaries and data structures like update histories, etc., based on the requirements of the optimization function used.) Initialize to zeros based on size.
  3. Inside the loop (as mentioned in the template code), call the grad_calculate_batchwise() function with the appropriate arguments. This function will calculate the gradients for the current batch (by doing forward and backpropagation).
  4. Write the parameter update statements and other update statements specific to the optimization function.

Then, enter the optimization function name in the train function only if you want to consider it as a hyperparameter. Otherwise, directly pass this function as an argument to the fit function to train the neural network.




Question 4 (10 Marks)

Use the sweep functionality provided by wandb to find the best values for the hyperparameters listed below. Use the standard train/test split of fashion_mnist (use (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()). Keep 10% of the training data aside as validation data for this hyperparameter search. Here are some suggestions for different values to try for hyperparameters. As you can quickly see that this leads to an exponential number of combinations. You will have to think about strategies to do this hyperparameter search efficiently. Check out the options provided by wandb.sweep and write down what strategy you chose and why.

  • number of epochs: 5, 10
  • number of hidden layers: 3, 4, 5
  • size of every hidden layer: 32, 64, 128
  • weight decay (L2 regularisation): 0, 0.0005, 0.5
  • learning rate: 1e-3, 1 e-4
  • optimizer: sgd, momentum, nesterov, rmsprop, adam, nadam
  • batch size: 16, 32, 64
  • weight initialisation: random, Xavier
  • activation functions: sigmoid, tanh, ReLU


Answer

Given the high number of hyperparameters, we explored various methods for carrying out these hyperparameter sweeps.

Wandb provides three options for carrying out these sweeps:

  • Grid Search: This is a brute force method wherein it evaluates all kinds of hyperparameter configurations (like points in a grid).
  • Random Search: This is a randomized version of grid search, wherein it randomly picks the hyperparameter configurations and evaluates them.
  • Bayes Search: This is a heuristic method (intelligent method). This method exploits the property that "Points in the same region tend to return similar performance." Bayesian search makes use of this fact and samples regions of better-performing points with a higher likelihood.

For our situation, the obvious choice is to use "Bayes Search" to conduct these hyperparameter sweeps.

I ran these hyperparameter sweeps using Bayes search overnight and completed around 190 sweeps in total (of which 10 are shown below).

Apart from the above-mentioned hyperparameters, we conducted some of our experimentation and included further values like 20 epochs, 128 batch size, etc.





190 selected runs



Question 5 (5 marks)

We would like to see the best accuracy on the validation set across all the models that you train.

wandb automatically generates this plot which summarises the test accuracy of all the models that you tested. Please paste this plot below using the "Add Panel to Report" feature




248 selected runs


Answer


Above is the highly zoomed-in view of the plot (i.e., only runs with accuracy values greater than 80 have been displayed).

Observations from the above plot:


  • The clear benefit of using Bayes Search is quite evident here. Barring a few hyperparameter configurations, the remaining all have reasonably good validation accuracy. Hence, the scatter plot is quite populated in the top (i.e., the region with high accuracy).
  • Some of the configurations that performed not so well for validation data are "maybe" because of overfitting of the data. They performed well for training data but did not achieve good accuracy with validation data.
  • The configurations that performed terribly are "maybe" because of very bad initialization. As a majority of the terribly performing runs are using random initialization.



Question 6 (20 Marks)

Based on the different experiments that you have run we want you to make some inferences about which configurations worked and which did not.

Here again, wandb automatically generates a "Parallel co-ordinates plot" and a "correlation summary" as shown below. Learn about a "Parallel co-ordinates plot" and how to read it.

By looking at the plots that you get, write down some interesting observations (simple bullet points but should be insightful). You can also refer to the plot in Question 5 while writing these insights. I would also like to see a recommendation for what configuration to use to get close to 95% accuracy.



Answer


Observations:


  • Because we ran Bayes Search, one thing is quite evident: Bayes almost immediately stops using those hyperparameter values that will not give us good validation accuracy. For example, in our below sweep, we observe that the majority of the runs are using "Xavier" initialization, and very few runs are using "Random" initialization. This is because, almost at the start, random was not performing as well as Xavier. Hence the sweep functionality stopped using this as the initialization function.
  • The most preferred number of epochs is 20.
  • Even though Adam didn't give us the highest validation accuracy, it worked extremely well on average. Keeping other hyperparameters fixed, Adam (also Nadam) was able to give excellent accuracies for fewer numbers of epochs as compared to its counterparts.
  • Adam, Momentum, and Nesterov started giving reasonably good accuracies right from 5 epochs onwards (in the majority of cases).
  • Mini Batch Gradient Descent (Vanilla GD) worked well but only when the epochs are high (for obvious reasons).
  • Nothing much could be inferred from the weight decay hyperparameter.
  • A mini-batch size of 128 didn't perform much well. Instead, mini-batch sizes of 32 and 64 gave really good results.
  • The most preferred choice of the number of hidden layers and the number of neurons is (4, 128) and (5, 128). Although we received reasonably good performances with 64 neurons also.
  • The preferred learning rate value is 0.0001 with higher epochs.
  • The best activation function is ReLU. Tanh worked well but ReLU is the best. The Sigmoid activation function, as expected, didn't give much good performance as compared to its counterparts.
  • As also inferred previously, Xavier initialization is the best and, as seen below, has the highest positive correlation with validation accuracy. Similarly, random initialization is bad as it has a high negative correlation with validation accuracy.




248 selected runs


Question 7 (10 Marks)

For the best model identified above, report the accuracy on the test set of fashion_mnist and plot the confusion matrix as shown below.



Answer


The best model used has the below hyperparameters:

  • Number of hidden layers: 5
  • Number of neurons in each hidden layer: 128
  • Learning Rate: 0.0001
  • Initialization type: Xavier
  • Activation Function: ReLU
  • Mini Batch Size: 32
  • Max Epochs: 20
  • Lambda (L2 Regularization): 0.0005
  • Optimization Function: Nadam

The Test Accuracy obtained for this hyperparameter configuration is 87.68%.

Observation:


  • As expected, the model had some difficulty in distinguishing between some pairs of clothing items like (coat and pullover), (pullover, shirt), (shirt, coat), (T-shirt/top, Shirt).
  • This is because these items are quite similar and often humans may also get confused between these pairs.

Therefore, we can conclude that our model is working very well for the Testing Data of Fashion MNIST and hence is a good Model for this particular task.





248 selected runs




Question 8 (5 Marks)

In all the models above you would have used cross entropy loss. Now compare the cross entropy loss with the squared error loss. I would again like to see some automatically generated plots or your own plots to convince me whether one is better than the other.



Answer


  • To compare the performance of different loss functions, we ran another hyperparameter sweep, this time including loss_function as a hyperparameter.

  • We chose a "Random" Sweep instead of a "Bayes" sweep. Had we used a "Bayes" Sweep, we may not have been able to arrive at a correct decision because eventually, the Bayes sweep would start preferring the loss function that has the best accuracy continuously, and its counterpart would not get enough sweeps. Hence, we used a Random Sweep here.

  • As it is quite evident from the parallel coordinates plot, the cross-entropy loss performs much better than the squared error loss function.

  • This can also be inferred from the correlation data given below: Cross-Entropy has a high positive correlation, whereas squared loss has a high negative correlation with respect to validation accuracy.

However, it's not correct to say that squared error loss never performs well. As we can see, there are some instances when the squared error loss did work reasonably well, although not as well as cross-entropy.





248 selected runs


Question 9 (10 Marks)

Link to the GitHub Code:


https://github.com/ahmecse/2024_DL_Assignment_1



Question 10 (10 Marks)

Based on your learnings above, give me 3 recommendations for what would work for the MNIST dataset (not Fashion-MNIST). Just to be clear, I am asking you to take your learnings based on extensive experimentation with one dataset and see if these learnings help on another dataset. If I give you a budget of running only 3 hyperparameter configurations as opposed to the large number of experiments you have run above then which 3 would you use and why. Report the accuracies that you obtain using these 3 configurations.



Answer

The 4 best configurations that were chosen are as listed below:

Configuration 1


  • Number of hidden layers = 5
  • Number of neurons in each hidden layer = 128
  • Learning Rate = 0.0001
  • Initialization type = Xavier
  • Activation Function = ReLU
  • Mini Batch Size = 16
  • Max Epochs = 20
  • Lamba (L2 Regularization) = 0.0005
  • Optimization Function = Nadam

Test Accuracy obtained = 96.54%


Configuration 2


  • Number of hidden layers = 5
  • Number of neurons in each hidden layer = 128
  • Learning Rate = 0.0001
  • Initialization type = Xavier
  • Activation Function = ReLU
  • Mini Batch Size = 64
  • Max Epochs = 20
  • Lamba (L2 Regularization) = 0.0005
  • Optimization Function = Nesterov

Test Accuracy obtained = 96.19%


Configuration 3


  • Number of hidden layers = 4
  • Number of neurons in each hidden layer = 128
  • Learning Rate = 0.0001
  • Initialization type = Xavier
  • Activation Function = ReLU
  • Mini Batch Size = 32
  • Max Epochs = 20
  • Lamba (L2 Regularization) = 0
  • Optimization Function = Momentum

Test Accuracy obtained = 96.67%


Configuration 3


  • Number of hidden layers = 4
  • Number of neurons in each hidden layer = 128
  • Learning Rate = 0.0001
  • Initialization type = Xavier
  • Activation Function = ReLU
  • Mini Batch Size = 32
  • Max Epochs = 20
  • Lamba (L2 Regularization) = 0
  • Optimization Function = Momentum

Test Accuracy obtained = 96.56%

We have also plotted the confusion matrix for Top 3 configurations (combined) which can be seen below.





248 selected runs


Self Declaration

I, Ahmed Shmels , swear on our honour that the above declaration is correct.