Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

CSCI3151 - Foundations of Machine Learning

Assignment 2

Winter 2022

Your assignment is to be submitted as a single  .ipynb file (please do not zip it when submitting to              brightspace) including your answers to both the math and the experimental questions, in the correct order, on Brightspace. Use markdown syntax (https://www.markdownguide.org/cheat-sheet/) to format your answers

Note: in solving the math questions, aim for general (symbolic) solutions and substitute the specific numbers at the end. This demonstrates a solid understanding of the key concepts. You can answer the math questions in   two ways:

  Use LaTeX to typeset the equations. Section H of this LaTeX reference sheet

(http://tug.ctan.org/info/latex-refsheet/LaTeX_RefSheet.pdf) is a good reference. Here is another LaTeX   reference sheet (https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick- reference). The equations in the questions are typeset in LaTeX, so you can use them as examples.

Use neat handwriting, scan your solution using Camscanner

(https://www.camscanner.com/user/download) on your mobile phone, upload the image file, and embed it   in your solution notebook. To this end (1) create an empty Markdown cell. 2) Drag-and-drop the image file   into the empty Markdown cell, or click on the image icon at the top of the cell and select the image file. The Markdown code that will embed the image, together with its content, then appears.

Your answers to the experimental questions should be in your solution notebook, in the form of code and text cells, using markdown for your text responses. You should also include the results of running your code.

The marking criteria are described in rubrics. There are two rubrics, for math questions, and for experimental questions, respectively.

You can submit multiple editions of your assignment. Only the last one will be marked. It is recommended to   upload a complete submission, even if you are still improving it, so that you have something into the system if your computer fails for whatever reason.

IMPORTANT: PLEASE NAME YOUR PYTHON NOTEBOOK FILE AS:

<LAST_NAME>-<FIRST_NAME>-Assignment-N.ipynb

for example: Milios-Evangelos-Assignment-2.ipynb \

1. Gradient descent - Logistic regression

In this question we are going to experiment with logistic regression. This exercise focuses on the inner workings of gradient descent using a cross-entropy cost function as it was learned in class.

a) Using the Pima Indians Diabetes Dataset (https://www.kaggle.com/uciml/pima-indians-diabetes-database), first apply a feature selection algorithm based on evaluating feature importance using Pearson correlation       (https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) (see scipy documentation                                   (https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.pearsonr.html)). Extract the top two     most important features based on this measure. Then, separate a random 20% of your data instances for       validation.

b) We want to train a logistic regression model to predict the target feature Outcome . It’s important that no         other external package is used (pandas, numpy are ok) for this question part . We want to find the weights for the logistic regression using a hand made gradient descent algorithm. We will use cross-entropy as the cost       function, and the logistic cross-entropy to compute the weight update during gradient descent. It is OK to reuse  as much as you need from the code you developed for Assignment 1. Differently from what we did for                 Assignment 1, we are now using a random 20% of your data instances for validation.

Your function should be able to return the updated weights and bias after every iteration of the gradient descent algorithm.

Your function should be defined as follows:

def LRGradDesc( data, target, weight_init, bias_init, learning_rate, max_iter ):

And it should print lines as indicated below (note the last line with the weights):

Iteration 0: [initial_train cost], [train accuracy], [validation accuracy]

Iteration 1: [train cost after first iteration], [train accuracy after first iteration], [validation accuracy after first iteration]

Iteration 2: [weights after second iteration], [train cost after second iteration], [train accuracy after second iteration], [validation accuracy after second iteration]

Iteration max_iter : [weights after max_iter iteration], [train cost after max_iter iteration], [train accuracy after max_iter iteration], [validation accuracy after max_iter iterations]

Final weights: [bias], [w_0], [w_1]

Note that you may want to print every 100 or every 1000 iterations if  max_iter is a fairly large number (but you shouldn’t have more iterations than the indicated in  max_iter ).

c) Discuss how the choice of learning_rate affects the fitting of the model.

d) Compare accuracy of your model with the one using Sklearn library (https://scikit-                             learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) to compute logistic regression.

e) Retrain your model using three features of your choice. Compare both models using an ROC curve (you can

use code from here (https://scikit-                                                                                                                             learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html#sphx-glr-auto-examples-ensemble- plot-feature-transformation-py) to draw the ROC curve).

2. Multi-class classification using neural networks

In this question you will experiment with a neural network in the context of text classification, where a document can belong to one out of several possible categories. The main goal for you is to try different hyperparameters

in a systematic manner so that you can propose a network configuration that is properly justified. You will            experiment with the MNIST digits (https://keras.io/api/datasets/mnist/), which can be loaded directly from Keras:

from keras.datasets import mnist

(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)

In [ ]:

from keras.datasets import mnist

from keras.preprocessing import sequence

(train_data, train_labels), (test_data, test_labels) = mnist.load_data(num_words=10000)

/usr/local/lib/python3.7/dist-packages/keras/datasets/reuters.py:143: VisibleDepreca tionWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tu ple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated.

If you meant to do this, you must specify 'dtype=object' when creating the ndarray

x_train, y_train = np.array(xs[:idx]), np.array(labels[:idx])

/usr/local/lib/python3.7/dist-packages/keras/datasets/reuters.py:144: VisibleDepreca tionWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tu ple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated.

If you meant to do this, you must specify 'dtype=object' when creating the ndarray

x_test, y_test = np.array(xs[idx:]), np.array(labels[idx:])

We would then use a Keras utility to truncate or pad the dataset to a length of 500 for each observation using the sequence.pad_sequences() function.

To learn more why we need padding read this article (https://developers.google.com/machine-

learning/guides/text-classification/step-3)

In [ ]:

Finally, later on, the first layer of our model would be an word embedding layer created using the Embedding class as follows:

from keras.layers.embeddings import Embedding

Embedding(5000, 32, input_length=500)

a) As we load the data from the built-in keras function, it splits them into two subsets; however, it is recommended to split the data into three subsets such as:

70% train, 15% val, 80% train, 10% val, 60% train, 20% val,

15% test.

10% test.

20% test.

Use the mentioned ratios to split the data and train the model using these portions. For each one of your         experiments, train the model and report the loss and accuracy of model on the training and validation set. (for

more information check this link (https://scikit-                                                                                                            learn.org/stable/modules/learning_curve.html#:~:text=2.-,Learning%20curve,error%20or%20a%20bias%20error.)

b) Experiment with different hyperparameters and report your best accuracy found. The most important hyperparameters that you need to experiment with in this question part are:

  number of layers

nodes per hidden layer

  learning rate

  number of epochs

To select the best hyper-parameter, draw the loss and accuracy curve.

3. Computational graph (no code involved)

This question aims at checking your understanding on defining arbitrary network architectures and compute any derivative involved for optimization.

Consider a neural network with N input units, N output units, and K hidden units. The activations are computed as follows:

 = (1) + (1)

 = ()

 =  + (2) + (2)

where  denotes the logistic function, applied elementwise. The cost involves a squared difference with the        target  (with a 0.5 factor) and a regularization term that accounts for the dot product with respect to an external vector  . More concretely:

 =  + 

 = ||

 =  ‖ − ‖2

 

a) Draw the computation graph relating  ,  ,  ,  ,  ,  , and  .

 

b) Derive the backpropagation equations for computing ∂/∂(1) . To make things simpler, you may use ′ to denote the derivative of the ReLU function.

4. Tuning generalization

In this question you will construct a neural network to classify a large set of low resolution images. Differently     from Q2, in this case we suggest you a neural network to start experimenting with, but we would like you to        describe the behavior of the network as you modify certain parameters. You will be reproducing some concepts mentioned during the lectures, such as when we show how generalization changes as the number of                 parameters are changed.

a) Use the CIFAR-100 dataset (available from Keras)

from keras.datasets import cifar100

(x_train_original, y_train_original), (x_test_original, y_test_original) =

cifar100.load_data(label_mode='fine')

to train a neural network with two hidden layers using the logistic activation function, with 500 and 200 hidden nodes, respectively. The output layer should be defined according to the nature of the targets.

a) Generate a plot that shows average precision for training and test sets as a function of the number of epochs. Indicate what a reasonable number of epochs should be.

b) Generate a plot that shows average precision for training and test sets as a function of the number of       weights/parameters (# hidden nodes). For this question part, you will be modifying the architecture that was given to you as a starting point.

c) Generate a plot that shows average precision for training and test sets as a function of the number of              instances in the training set. For this question part, you will be modifying your training set. For instance, you can run 10 experiments where you first use a random 10% of the training data, a second experiment where you use a random 20% of the training data, and so on until you use the entire training set. Keep the network                     hyperparameters constant during your experiments.

d) Based on all your experiments above, define a network architecture and report accuracy and average precision for all classes.

e) Can you improve test prediction performance by using an ensemble of neural networks?