1. Homepage
  2. Programming
  3. COMP9417 Machine Learning Homework 1: Regularized Optimization & Gradient Methods

COMP9417 Machine Learning Homework 1: Regularized Optimization & Gradient Methods

Engage in a Conversation
UNSWCOMP9417Machine LearningData MiningPythonGradient OptimizationBackpropagationRegression

COMP9417 - Machine Learning Homework 1: Regularized Optimization & Gradient Methods CourseNana.COM

Introduction In this homework we will explore gradient based optimization. Gradient based algorithms have been crucial to the development of machine learning in the last few decades. The most famous exam- ple is the backpropagation algorithm used in deep learning, which is in fact just a particular application of a simple algorithm known as (stochastic) gradient descent. We will first implement gradient descent from scratch on a deterministic problem (no data), and then extend our implementation to solve a real world regression problem. CourseNana.COM

Points Allocation There are a total of 30 marks. CourseNana.COM

  • A single PDF file which contains solutions to each question. For each question, provide your solution in the form of text and requested plots. For some questions you will be requested to provide screen shots of code used to generate your answer — only include these when they are explicitly asked for. CourseNana.COM

  • .py file(s) containing all code you used for the project, which should be provided in a separate .zip file. This code must match the code provided in the report. CourseNana.COM

  • You may be deducted points for not following these instructions. CourseNana.COM

  • You may be deducted points for poorly presented/formatted work. Please be neat and make your solutions clear. Start each question on a new page if necessary. CourseNana.COM

    1 CourseNana.COM

  • You cannot submit a Jupyter notebook; this will receive a mark of zero. This does not stop you from developing your code in a notebook and then copying it into a .py file though, or using a tool such as nbconvert or similar. CourseNana.COM

  • We will set up a Moodle forum for questions about this homework. Please read the existing questions before posting new questions. Please do some basic research online before posting questions. Please only post clarification questions. Any questions deemed to be fishing for answers will be ignored and/or deleted. CourseNana.COM

  • Please check Moodle announcements for updates to this spec. It is your responsibility to check for announcements about the spec. CourseNana.COM

  • Please complete your homework on your own, do not discuss your solution with other people in the course. General discussion of the problems is fine, but you must write out your own solution and acknowledge if you discussed any of the problems in your submission (including their name(s) and zID). CourseNana.COM

  • As usual, we monitor all online forums such as Chegg, StackExchange, etc. Posting homework ques- tions on these site is equivalent to plagiarism and will result in a case of academic misconduct. CourseNana.COM

  • You may not use SymPy or any other symbolic programming toolkits to answer the derivation ques- tions. This will result in an automatic grade of zero for the relevant question. You must do the derivations manually. CourseNana.COM

    When and Where to Submit CourseNana.COM

  • Due date: Week 4, Monday March 4th, 2024 by 5pm. Please note that the forum will not be actively monitored on weekends. CourseNana.COM

  • Late submissions will incur a penalty of 5% per day from the maximum achievable grade. For ex- ample, if you achieve a grade of 80/100 but you submitted 3 days late, then your final grade will be 80 3 × 5 = 65. Submissions that are more than 5 days late will receive a mark of zero. CourseNana.COM

  • Submission must be made on Moodle, no exceptions. CourseNana.COM

Question 1. Gradient Based Optimization CourseNana.COM

The general framework for a gradient method for finding a minimizer of a function f : Rn R is defined by CourseNana.COM

x(k+1) =x(k) αkf(xk), k=0,1,2,..., (1) > 0 is known as the step size, or learning rate. Consider the following simple example of CourseNana.COM

where α
minimizing the function g(x) = 2
choose a starting value of x, say x(0) = 1. Let’s also take the step size to be constant, αk = α = 0.1. Then we have the following iterations: CourseNana.COM

x3 + 1. We first note that g(x) = 3x2(x3 + 1)1/2. We then need to CourseNana.COM

x(1) = x(0) 0.1 × 3(x(0))2((x(0))3 + 1)1/2 = 0.7878679656440357 x(2) = x(1) 0.1 × 3(x(1))2((x(1))3 + 1)1/2 = 0.6352617090300827 x(3) = 0.5272505146487477 CourseNana.COM

. CourseNana.COM

and this continues until we terminate the algorithm (as a quick exercise for your own benefit, code this up and compare it to the true minimum of the function which is x= 11). This idea works for functions that have vector valued inputs, which is often the case in machine learning. For example, when we minimize a loss function we do so with respect to a weight vector, β. When we take the step- size to be constant at each iteration, this algorithm is known as gradient descent. For the entirety of this question, do not use any existing implementations of gradient methods, doing so will result in an automatic mark of zero for the entire question. CourseNana.COM

(a) Consider the following optimisation problem: CourseNana.COM

min f(x), xRn CourseNana.COM

where CourseNana.COM

f (x) = 21 Ax b2 + γ2 x2 , and where A Rm×n, b Rm are defined as CourseNana.COM

.
1Does the algorithm converge to the true minimizer? Why/Why not? CourseNana.COM

Page 3 CourseNana.COM

3 2 0 1A = 1 3 0 2 , CourseNana.COM

0 4 2 7 CourseNana.COM

3b = 1 , CourseNana.COM

4 CourseNana.COM

and γ is a positive constant. Run gradient descent on f using a step size of α = 0.01 and γ = 2 and starting point of x(0) = (1, 1, 1, 1). You will need to terminate the algorithm when the following condition is met: ∥∇f(x(k))2 < 0.001. In your answer, clearly write down the version of the gradient steps (1) for this problem. Also, print out the first 5 and last 5 values of x(k), clearly indicating the value of k, in the form: CourseNana.COM

k = 0, k=1, k=2, CourseNana.COM

x(k) = [1,1,1,1] x(k) =···
x(k) =··· CourseNana.COM

What to submit: an equation outlining the explicit gradient update, a print out of the first 5 (k = 5 inclusive) and last 5 rows of your iterations. Use the round function to round your numbers to 4 decimal places. Include a screen shot of any code used for this section and a copy of your python code in solutions.py. CourseNana.COM

Consider now a slightly different problem: let y, β Rp and λ > 0. Further, we define the matrix W R(p2)×p as CourseNana.COM

1 2 1 CourseNana.COM

121 CourseNana.COM

...W = .. .. .. , CourseNana.COM

1 2 1 1 2 1 CourseNana.COM

where blanks denote zero elements.2 Define the loss function:
L(β) = 1 y β2 + λ2. (2) CourseNana.COM

2p
The following code allows you to load in the data needed for this problem3: CourseNana.COM

import numpy as np
import matplotlib.pyplot as plt
t_var = np.load("t_var.npy")
y_var = np.load("y_var.npy")
plt.plot(t_var, y_var)
plt.show()

1 2 3 4 5 6 7 CourseNana.COM

Note, the t variable is purely for plotting purposes, it should not appear in any of your calculations. (b) Show that CourseNana.COM

βˆ = arg min L(β) = (I + 2λpW T W )1y. β CourseNana.COM

Update the following code4 so that it returns a plot of βˆ and calculates L(βˆ). Only in your code implementation, set λ = 0.9. CourseNana.COM

def create_W(p):
## generate W which is a p-2 x p matrix as defined in the question
 W = np.zeros((p-2, p))
b = np.array([1,-2,1])
for i in range(p-2):
    W[i,i:i+3] = b
return W
def loss(beta, y, W, L):
## compute loss for a given vector beta for data y, matrix W, regularization
parameter L (lambda)
# your code here

3a copy of this code is provided in code student.py 4a copy of this code is provided in code student.py CourseNana.COM

return loss_val
## your code here, e.g. compute betahat and loss, and set other params..
plt.plot(t_var, y_var, zorder=1, color=’red’, label=’truth’)
plt.plot(t_var, beta_hat, zorder=3, color=’blue’,
            linewidth=2, linestyle=’--’, label=’fit’)
plt.legend(loc=’best’)
plt.title(f"L(beta_hat) = {loss(beta_hat, y, W, L)}")

plt.show() CourseNana.COM

12 13 14 15 16 17 18 19 20 21 22 CourseNana.COM

(c) Writeouteachofthetwotermsthatmakeupthelossfunction( 1 yβ2 andλ2)explicitly 2p 2 2 CourseNana.COM

using summations. Use this representation to explain the role played by each of the two terms. Be as specific as possible. What to submit: your answer, and any working either typed or handwritten. CourseNana.COM

(d) Show that we can write (2) in the following way:
1 Xp CourseNana.COM

What to submit: a closed form expression along with your working, a single plot and a screen shot of your code along with a copy of your code in your .py file. CourseNana.COM

L(β) = p
where Lj(β) depends on the data y1,...,yp only through yj. Further, show that CourseNana.COM

Note that the first vector is the p-dimensional vector with zero everywhere except for the j-th index. Take a look at the supplementary material if you are confused by the notation. What to submit: your answer, and any working either typed or handwritten. CourseNana.COM

(e) Inthisquestion,youwillimplement(batch)GDfromscratchtosolvethe(2).Useaninitialestimate β(0) = 1p (the p-dimensional vector of ones), and λ = 0.001 and run the algorithm for 1000 epochs (an epoch is one pass over the entire data, so a single GD step). Repeat this for the following step sizes: CourseNana.COM

α ∈ {0.001, 0.005, 0.01, 0.05, 0.1, 0.3, 0.6, 1.2, 2} To monitor the performance of the algorithm, we will plot the value CourseNana.COM

(k) = L(β(k)) L(βˆ), CourseNana.COM

where βˆ is the true (closed form) solution derived earlier. Present your results in a single 3 × 3 grid plot, with each subplot showing the progression of (k) when running GD with a specific step-size. State which step-size you think is best in terms of speed of convergence. What to submit: a single plot. Include a screen shot of any code used for this section and a copy of your python code in solutions.py. CourseNana.COM

(f) We will now implement SGD from scratch to solve (2). Use an initial estimate β(0) = 1p (the vector of ones) and λ = 0.001 and run the algorithm for 4 epochs (this means a total of 4p updates of β. Repeat this for the following step sizes: CourseNana.COM

α ∈ {0.001, 0.005, 0.01, 0.05, 0.1, 0.3, 0.6, 1.2, 2} CourseNana.COM

Present an analogous single 3 × 3 grid plot as in the previous question. Instead of choosing an index randomly at each step of SGD, we will cycle through the observations in the order they are stored in y to ensure consistent results. Report the best step-size choice. In some cases you might observe that the value of (k) jumps up and down, and this is not something you would have seen using batch GD. Why do you think this might be happening? CourseNana.COM

What to submit: a single plot and some commentary. Include a screen shot of any code used for this section and a copy of your python code in solutions.py. CourseNana.COM

An alternative Coordinate Based scheme: In GD, SGD and mini-batch GD, we always update the entire p-dimensional vector β at each iteration. An alternative approach is to update each of the p parameters individually. To make this idea more clear, we write the loss function of interest L(β) as L(β12 ...,βp). We initialize β(0), and then solve for k = 1,2,3,..., CourseNana.COM

β(k) =argminL(β ,β(k1)(k1),...,β(k1)) 1123p CourseNana.COM

β1 CourseNana.COM

β(k) =argminL(β(k),β ,β(k1),...,β(k1)) 2123p CourseNana.COM

β2 . CourseNana.COM

βp
Note that each of the minimizations is over a single (1-dimensional) coordinate of β, and also that CourseNana.COM

as as soon as we update β(k), we use the new value when solving the update for β(k) and so on. j j+1 CourseNana.COM

The idea is then to cycle through these coordinate level updates until convergence. In the next two parts we will implement this algorithm from scratch for the problem we have been working on (2). CourseNana.COM

  1. (g)  Derive closed-form expressions for βˆ1, βˆ2, . . . , βˆp where for j = 1, 2, . . . , p: βˆj = argminL(β1,...,βj1jj+1,...,βp). CourseNana.COM

    βj CourseNana.COM

    What to submit: a closed form expression along with your working. CourseNana.COM

    Hint: Be careful, this is not as straight-forward as it might seem at first. It is recommended to choose a value for p, e.g. p = 8 and first write out the expression in terms of summations. Then take derivatives to get the closed form expressions. CourseNana.COM

  2. (h)  Implement both gradient descent and the coordinate scheme in code (from scratch) and apply it to the provided data. In your implementation: CourseNana.COM

    • Useλ=0.001forthecoordinatescheme,andstep-sizeα=1foryourgradientdescentscheme. • Initialize both algorithms with β = 1p, the p-dimensional vector of ones.
    • For the coordinate scheme, be sure to update the
    βj ’s in order (i.e. 1,2,3,...) CourseNana.COM

    Page 6 CourseNana.COM

β(k) = argminL(β(k)(k)(k),...,β ). p123p CourseNana.COM

CourseNana.COM

  • Foryourcoordinatescheme,terminatethealgorithmafter1000updates(eachtimeyouupdate a single coordinate, that counts as an update.) CourseNana.COM

  • For your GD scheme, terminate the algoirthm after 1000 epochs. CourseNana.COM

  • Create a single plot of k vs (k) = L(β(k)) L(βˆ), where βˆ is the closed form expression derived earlier. Your plot should have both the coordinate scheme (blue) and GD (green) displayed and should start from k = 0. Your plot should have a legend. CourseNana.COM

    What to submit: a single plot and a screen shot of your code along with a copy of your code in your .py file. CourseNana.COM

    (i) Based on your answer to the previous part, when would you prefer GD? When would you prefer the coordinate scheme? What to submit: Some commentary. CourseNana.COM

    Supplementary: Background on Gradient Descent As noted in the lectures, there are a few variants of gradient descent that we will briefly outline here. Recall that in gradient descent our update rule is CourseNana.COM

    β(k+1) =β(k) αkL(β(k)), k=0,1,2,...,
    where L(β) is the loss function that we are trying to minimize. In machine learning, it is often the case CourseNana.COM

    that the loss function takes the form CourseNana.COM

    1 Xn CourseNana.COM

    1 Xn CourseNana.COM

Li(β),
i.e. the loss is an average of n functions that we have lablled Li, and each Li depends on the data only CourseNana.COM

L(β) = n
through (xi , yi ). It then follows that the gradient is also an average of the form CourseNana.COM

Li(β). We can now define some popular variants of gradient descent . CourseNana.COM

L(β) = n
(i) Gradient Descent (GD) (also referred to as batch gradient descent): here we use the full gradient, CourseNana.COM

as in we take the average over all n terms, so our update rule is: αn CourseNana.COM

β(k+1) = β(k) nk XLi(β(k)), k = 0,1,2,.... i=1 CourseNana.COM

  1. (ii)  Stochastic Gradient Descent (SGD): instead of considering all n terms, at the k-th step we choose an index ik randomly from {1, . . . , n}, and update CourseNana.COM

    β(k+1) =β(k) αkLik(β(k)), k=0,1,2,.... Here, we are approximating the full gradient L(β) using Lik (β). CourseNana.COM

  2. (iii)  Mini-Batch Gradient Descent: GD (using all terms) and SGD (using a single term) represents the two possible extremes. In mini-batch GD we choose batches of size 1 < B < n randomly at each step, call their indices {ik1 , ik2 , . . . , ikB }, and then we update CourseNana.COM

Get in Touch with Our Experts

WeChat WeChat
Whatsapp WhatsApp
UNSW代写,COMP9417代写,Machine Learning代写,Data Mining代写,Python代写,Gradient Optimization代写,Backpropagation代写,Regression代写,UNSW代编,COMP9417代编,Machine Learning代编,Data Mining代编,Python代编,Gradient Optimization代编,Backpropagation代编,Regression代编,UNSW代考,COMP9417代考,Machine Learning代考,Data Mining代考,Python代考,Gradient Optimization代考,Backpropagation代考,Regression代考,UNSWhelp,COMP9417help,Machine Learninghelp,Data Mininghelp,Pythonhelp,Gradient Optimizationhelp,Backpropagationhelp,Regressionhelp,UNSW作业代写,COMP9417作业代写,Machine Learning作业代写,Data Mining作业代写,Python作业代写,Gradient Optimization作业代写,Backpropagation作业代写,Regression作业代写,UNSW编程代写,COMP9417编程代写,Machine Learning编程代写,Data Mining编程代写,Python编程代写,Gradient Optimization编程代写,Backpropagation编程代写,Regression编程代写,UNSWprogramming help,COMP9417programming help,Machine Learningprogramming help,Data Miningprogramming help,Pythonprogramming help,Gradient Optimizationprogramming help,Backpropagationprogramming help,Regressionprogramming help,UNSWassignment help,COMP9417assignment help,Machine Learningassignment help,Data Miningassignment help,Pythonassignment help,Gradient Optimizationassignment help,Backpropagationassignment help,Regressionassignment help,UNSWsolution,COMP9417solution,Machine Learningsolution,Data Miningsolution,Pythonsolution,Gradient Optimizationsolution,Backpropagationsolution,Regressionsolution,