First, join a group in canvas with your group partners. Pick an avaliable group for Project 2 in the People page.
In canvas, deliver as a group and include:
A PDF file of the report
We want you to answer the three different projects by handing in reports written like a standard scientific/technical report. The links at https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects contain more information. There you can find examples of previous reports, the projects themselves, how we grade reports etc. How to write reports will also be discussed during the various lab sessions. Please do ask us if you are in doubt.
When using codes and material from other sources, you should refer to these in the bibliography of your report, indicating wherefrom you for example got the code, whether this is from the lecture notes, softwares like Scikit-Learn, TensorFlow, PyTorch or other sources. These sources should always be cited correctly. How to cite some of the libraries is often indicated from their corresponding GitHub sites or websites, see for example how to cite Scikit-Learn at https://scikit-learn.org/dev/about.html.
We enocurage you to use tools like ChatGPT or similar in writing the report. If you use for example ChatGPT, please do cite it properly and include (if possible) your questions and answers as an addition to the report. This can be uploaded to for example your website, GitHub/GitLab or similar as supplemental material.
If you would like to study other data sets, feel free to propose other sets. What we have proposed here are mere suggestions from our side. If you opt for another data set, consider using a set which has been studied in the scientific literature. This makes it easier for you to compare and analyze your results. Comparing with existing results from the scientific literature is also an essential element of the scientific discussion. The University of California at Irvine with its Machine Learning repository at https://archive.ics.uci.edu/ml/index.php is an excellent site to look up for examples and inspiration. Kaggle.com is an equally interesting site. Feel free to explore these sites.
The main aim of this project is to study both classification and regression problems by developing our own feed-forward neural network (FFNN) code. The exercises from week 41 and 42 (see https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek41.html and https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek42.html) as well as the lecture material from the same weeks (see https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html and https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html) should contain enough information for you to get started with writing your own code.
We will also reuse our codes on gradient descent methods from project 1.
The data sets that we propose here are (the default sets)
We will start with a regression problem and we will reuse our codes on gradient descent methods from project 1.
When using our gradient machinery from project 1, we will need the expressions for the cost/loss functions and their respective gradients. The functions whose gradients we need are:
Set up these three cost/loss functions and their respective derivatives and explain the various terms. In this project you will however only use the MSE and the Softmax cross entropy.
We will test three activation functions for our neural network setup, these are the
Set up their expressions and their first derivatives. You may consult the lecture notes (with codes and more) from week 42 at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html.
In the setup of a neural network code you will need your gradient descent codes from project 1. For neural networks we will recommend using stochastic gradient descent with either the RMSprop or the ADAM algorithms for updating the learning rates. But you should feel free to try plain gradient descent as well.
We recommend reading chapter 8 on optimization from the textbook of Goodfellow, Bengio and Courville at https://www.deeplearningbook.org/. This chapter contains many useful insights and discussions on the optimization part of machine learning. A useful reference on the back progagation algorithm is Nielsen's book at http://neuralnetworksanddeeplearning.com/.
You will find the Python Seaborn package useful when plotting the results as function of the learning rate \( \eta \) and the hyper-parameter \( \lambda \) .
Your aim now, and this is the central part of this project, is to write your own FFNN code implementing the back propagation algorithm discussed in the lecture slides from week 41 at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week41.html and week 42 at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/week42.html.
We will focus on a regression problem first, using the one-dimensional Runge function
$$ f(x) = \frac{1}{1+25x^2}, $$from project 1.
Use only the mean-squared error as cost function (no regularization terms) and write an FFNN code for a regression problem with a flexible number of hidden layers and nodes using only the Sigmoid function as activation function for the hidden layers. Initialize the weights using a normal distribution. How would you initialize the biases? And which activation function would you select for the final output layer? And how would you set up your design/feature matrix? Hint: does it have to represent a polynomial approximation as you did in project 1?
Train your network and compare the results with those from your OLS regression code from project 1 using the one-dimensional Runge function. When comparing your neural network code with the OLS results from project 1, use the same data sets which gave you the best MSE score. Moreover, use the polynomial order from project 1 that gave you the best result. Compare these results with your neural network with one and two hidden layers using \( 50 \) and \( 100 \) hidden nodes, respectively.
Comment your results and give a critical discussion of the results obtained with the OLS code from project 1 and your own neural network code. Make an analysis of the learning rates employed to find the optimal MSE score. Test both stochastic gradient descent with RMSprop and ADAM and plain gradient descent with different learning rates.
You should, as you did in project 1, scale your data.
You should test your results against a similar code using Scikit-Learn (see the examples in the above lecture notes from weeks 41 and 42) or tensorflow/keras or Pytorch (for Pytorch, see Raschka et al.'s text chapters 12 and 13).
Furthermore, you should also test that your derivatives are correctly calculated using automatic differentiation, using for example the Autograd library or the JAX library. It is optional to implement these libraries for the present project. In this project they serve as useful tests of our derivatives.
You should also test different activation functions for the hidden layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and discuss your results. Test your results as functions of the number of hidden layers and nodes. Do you see signs of overfitting? It is optional in this project to perform a bias-variance trade-off analysis.
Finally, still using the one-dimensional Runge function, add now the hyperparameters \( \lambda \) with the \( L_2 \) and \( L_1 \) norms. Find the optimal results for the hyperparameters \( \lambda \) and the learning rates \( \eta \) and neural network architecture and compare the \( L_2 \) results with Ridge regression from project 1 and the \( L_1 \) results with the Lasso calculations of project 1. Use again the same data sets and the best results from project 1 in your comparisons.
With a well-written code it should now be easy to change the activation function for the output layer.
Here we will change the cost function for our neural network code developed in parts b), d) and e) in order to perform a classification analysis. The classification problem we will study is the multiclass MNIST problem, see the description of the full data set at https://www.kaggle.com/datasets/hojjatk/mnist-dataset. We will use the Softmax cross entropy function discussed in a). The MNIST data set discussed in the lecture notes from week 42 is a downscaled variant of the full dataset.
Feel free to suggest other data sets. If you find the classic MNIST data set somewhat limited, feel free to try the MNIST-Fashion data set at for example https://www.kaggle.com/datasets/zalando-research/fashionmnist.
To set up the data set, the following python programs may be useful
from sklearn.datasets import fetch_openml
# Fetch the MNIST dataset
mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto')
# Extract data (features) and target (labels)
X = mnist.data
y = mnist.target
You should consider scaling the data. The Pixel values in MNIST range from 0 to 255. Scaling them to a 0-1 range can improve the performance of some models. That is, you could implement the following scaling
X = X / 255.0
And then perform the standard train-test splitting
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
To measure the performance of our classification problem we will use the so-called accuracy score. The accuracy is as you would expect just the number of correctly guessed targets \( t_i \) divided by the total number of targets, that is
$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(t_i = y_i)}{n} , $$where \( I \) is the indicator function, \( 1 \) if \( t_i = y_i \) and \( 0 \) otherwise if we have a binary classification problem. Here \( t_i \) represents the target and \( y_i \) the outputs of your FFNN code and \( n \) is simply the number of targets \( t_i \).
Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter \( \lambda \), various activation functions, number of hidden layers and nodes and activation functions.
Again, we strongly recommend that you compare your own neural Network code for classification and pertinent results against a similar code using Scikit-Learn or tensorflow/keras or pytorch.
If you have time, you can use the functionality of scikit-learn and compare your neural network results with those from Logistic regression. This is optional. The weblink here https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article. Your neural network code can implement the equivalent of logistic regression by simply setting the number of hidden layers to zero and keeping just the input and the output layers.
If you wish to compare with say Logisti Regression from scikit-learn, the following code uses the above data set
from sklearn.linear_model import LogisticRegression
# Initialize the model
model = LogisticRegression(solver='saga', multi_class='multinomial', max_iter=1000, random_state=42)
# Train the model
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
# Make predictions on the test set
y_pred = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.4f}")
After all these glorious calculations, you should now summarize the various algorithms and come with a critical evaluation of their pros and cons. Which algorithm works best for the regression case and which is best for the classification case. These codes can also be part of your final project 3, but now applied to other data sets.
Here follows a brief recipe and recommendation on how to write a report for each project.
The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:
Finally, we encourage you to collaborate. Optimal working groups consist of 2-3 students. You can then hand in a common report.