代写COMP9417 - Machine Learning Homework 1帮做Python程序

COMP9417 - Machine Learning

Homework 1: Regularized Optimization & Gradient Methods

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.

Points Allocation There are a total of 30 marks.

  Question 1 a): 2 marks

  Question 1 b): 4 marks

  Question 1 c): 2 marks

  Question 1 d): 2 marks

  Question 1 e): 6 marks

  Question 1 f): 6 marks

  Question 1 g): 4 marks

  Question 1 h): 2 marks

  Question 1 i): 2 marks

What to Submit

•  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 — onlyinclude these when they are explicitly asked for.

•  .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.

  You maybe deducted points for not following these instructions.

•  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.

•  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.

•  We will setup 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.

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

•  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).

•  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.

•  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.

When and Where to Submit

•  Due date:  Week 4, Friday June 14th, 2024 by 5pm.  Please note that the forum will not be actively monitored on weekends.

•  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.

  Submission must be made on Moodle, no exceptions.


Question 1. Gradient Based Optimization

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

x(k+1)  = x(k) - Qk ▽f (xk );       k = 0; 1; 2; : : : ;                                        (1)

where Qk   > 0 is known as the step size, or learning rate.  Consider the following simple example of minimizing the function g(x) = 2x3 + 1. We first note that g/ (x) = 3x2 (x3  + 1) —1/2 . We then need to choose a starting value of x, say x(0)  = 1. Let’s also take the step size to be constant, Qk  = Q = 0:1. Then we have the following iterations:

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

.

.

.

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*  = -1).  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.

(a)  Consider the following optimisation problem:

Rn(in) f (x);

where

f (x) =  ⅡAx - bⅡ2(2) +  ⅡxⅡ2(2) ;

and where A Rm ×n, b ∈ Rm  are defined as

 

and √ is a positive constant. Run gradient descent on fusing a step size of Q = 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, printout the first 5 and last 5 values of x(k), clearly indicating the value of k, in the form.

k = 0;       x(k)  = [1; 1; 1; 1]

k = 1;       x(k)  = · · ·

k = 2;       x(k)  = · · ·

.

.

.



What to submit: an equation outlining the explicit gradient update, a printout of thefirst 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.

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

 

where blanks denote zero elements.  Define the loss function:

L(β) =  Ⅱy - βⅡ2(2) + λⅡWβⅡ2(2).                                                   (2)

The following code allows you to load in the data needed for this problem:

1    import  numpy  as  np

2   import  matplotlib.pyplot  as  plt  

3    t_var  =  np .load( "t_var .npy " )   

4    y_var  =  np .load( "y_var .npy " )   

5   plt .plot(t_var,  y_var) 

6    plt .show() 

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

β(^) in L(β) = (I + 2λpWTW)-1y.

Update the following code  so that it returns a plot of β(^) and calculates L(β(^)).  Only in your code

implementation, set λ = 0.9.

1    def  create_W(p):                                                                                                                                                                          

2              ##  generate  W  which  is  a  p-2  x  p  matrix  as  defined  in  the  question                                                 

3                     W  =  np . zeros((p-2,  p))                                                                                                                                                   

4                    b  =  np .array([1,-2,1])                                                                                                                                                   

5                    for  i  in  range (p-2):                                                                                                                                                        

6                                      W[i,i:i+3]  =  b                                                                                                                                                            

7                     return  W                                                                                                                                                                                   

8    

9    def  loss(beta,  y,  W,  L):                                                                                                                                                        

10                    ##  compute  loss  for  a  given  vector  beta  for  data  y ,  matrix  W ,  regularization                       

parameter  L   (lambda)                                                                                                                                                       11                     #  your  code  here                                                                                                                                                                 

2If it is not already clear: for the first row of W : W11  = 1; W12  = -2; W13  = 1 and W1j  = 0 for any j ≥ 4. For the second row of W : W21  = 0; W22  = 1; W23  = -2; W24  = 1 and W2j  = 0 for any j ≥ 5 and so on.

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

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



12                    return  loss_val                                                                                                                                                                   

13     14    ##  your  code  here ,  e .g .  compute  betahat  and  loss ,  and  set  other  params ..                                          

15    

16   plt .plot(t_var,  y_var,  zorder=1,  color= ’red  ,  label= ’truth  )                                                                     

17   plt .plot(t_var,  beta_hat,  zorder=3,  color= ’blue  ,                                                                                              

18                                                      linewidth=2,  linestyle= ’--  ,  label= ’fit’ )                                                                                     

19   plt .legend(loc= ’best  )                                                                                                                                                            

20   plt .title(f"L (beta_hat)  =  {loss (beta_hat ,  y ,  W ,  L ) } " )                                                                                     

21    plt .show()                                                                                                                                                                                        

22    

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.

(c)  Write out each of the two terms that makeup the loss function (  Ⅱy - βⅡ2(2) and λⅡWβ2(2)) explicitly

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.

(d)  Show that we can write (2) in the following way:

 

where Lj (β) depends on the data y1 , . . . , yp only through yj . Further, show that

 

 

I         0        I

▽Lj (β) =  I -(yj  - βj ) I  + 2λWTWβ,       j = 1, . . . , p. I         0        I

I                  I

I         ..          I

l       0.        

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.

(e)  In this question, you will implement (batch) GD from scratch to minimize the loss function (2). Use an initial estimate β(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:

Q ∈ {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

 (k)  = L(β(k)) - L(β(ˆ)),

whereβ(ˆ) is the true (closed form) solution derived earlier (but with λ = 0.001 now for consistency). 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.


(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 4pupdates of β . Repeat this for the following step sizes:

Q ∈ {0.001, 0.005, 0.01, 0.05, 0.1, 0.3, 0.6, 1.2, 2}

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?

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.

 

 

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(β1 , β2 . . . , βp ). We initialize β(0), and then solve fork = 1, 2, 3, . . . ,

β1(k)  = arg β(m)nL(β1 , β2(k-1), β3(k-1), . . . , βp(k-1))

 = arg 

.

.

.

βp(k)  = arg β(m)nL(β1(k), β2(k), β3(k), . . . , βp ).

Note that each of the minimizations is over a single (1-dimensional) coordinate of β, and also that as as soon as we update βj(k), we use the new value when solving the update for βj()1  and so on. 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).

(g)  Derive closed-form expressions for β(^)1 , β(^)2 , . . . , β(^)p where for j = 1, 2, . . . , p:

β(^)j  = arg β(m)nL(β1, . . . , βj-1, βj , βj+1, . . . , βp ).

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

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.

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

•  Use λ = 0.001 for the coordinate scheme, and step-size Q = 1 for your gradient descent scheme.

•  Initialize both algorithms with β = 1p, the p-dimensional vector of ones.

•  For the coordinate scheme, be sure to update the βj ’sin order (i.e. 1,2,3,...)


•  For your coordinate scheme, terminate the algorithm after 1000 updates (each time you update a single coordinate, that counts as an update.)

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

  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.

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

(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.

 

 

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

β (k+1)  = β (k) - Qk ▽L(β(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 that the loss function takes the form.

 

i.e. the loss is an average of n functions that we have labelled Li, and each Li depends on the data only through (xi , yi ). It then follows that the gradient is also an average of the form.

 

We can now define some popular variants of gradient descent .

(i)  Gradient Descent (GD) (also referred to as batch gradient descent): here we use the full gradient, as in we take the average over all n terms, so our update rule is:


 


k = 0, 1, 2, . . . .


(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

β (k+1)  = β (k) - Qk Lik (β(k)),       k = 0, 1, 2, . . . . Here, we are approximating the full gradient ▽L(β) using ▽Lik (β).

(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


 


k = 0, 1, 2, . . . ,


so we are still approximating the full gradient but using more than a single element as is done in SGD.


热门主题

课程名

mktg2509 csci 2600 38170 lng302 csse3010 phas3226 77938 arch1162 engn4536/engn6536 acx5903 comp151101 phl245 cse12 comp9312 stat3016/6016 phas0038 comp2140 6qqmb312 xjco3011 rest0005 ematm0051 5qqmn219 lubs5062m eee8155 cege0100 eap033 artd1109 mat246 etc3430 ecmm462 mis102 inft6800 ddes9903 comp6521 comp9517 comp3331/9331 comp4337 comp6008 comp9414 bu.231.790.81 man00150m csb352h math1041 eengm4100 isys1002 08 6057cem mktg3504 mthm036 mtrx1701 mth3241 eeee3086 cmp-7038b cmp-7000a ints4010 econ2151 infs5710 fins5516 fin3309 fins5510 gsoe9340 math2007 math2036 soee5010 mark3088 infs3605 elec9714 comp2271 ma214 comp2211 infs3604 600426 sit254 acct3091 bbt405 msin0116 com107/com113 mark5826 sit120 comp9021 eco2101 eeen40700 cs253 ece3114 ecmm447 chns3000 math377 itd102 comp9444 comp(2041|9044) econ0060 econ7230 mgt001371 ecs-323 cs6250 mgdi60012 mdia2012 comm221001 comm5000 ma1008 engl642 econ241 com333 math367 mis201 nbs-7041x meek16104 econ2003 comm1190 mbas902 comp-1027 dpst1091 comp7315 eppd1033 m06 ee3025 msci231 bb113/bbs1063 fc709 comp3425 comp9417 econ42915 cb9101 math1102e chme0017 fc307 mkt60104 5522usst litr1-uc6201.200 ee1102 cosc2803 math39512 omp9727 int2067/int5051 bsb151 mgt253 fc021 babs2202 mis2002s phya21 18-213 cege0012 mdia1002 math38032 mech5125 07 cisc102 mgx3110 cs240 11175 fin3020s eco3420 ictten622 comp9727 cpt111 de114102d mgm320h5s bafi1019 math21112 efim20036 mn-3503 fins5568 110.807 bcpm000028 info6030 bma0092 bcpm0054 math20212 ce335 cs365 cenv6141 ftec5580 math2010 ec3450 comm1170 ecmt1010 csci-ua.0480-003 econ12-200 ib3960 ectb60h3f cs247—assignment tk3163 ics3u ib3j80 comp20008 comp9334 eppd1063 acct2343 cct109 isys1055/3412 math350-real math2014 eec180 stat141b econ2101 msinm014/msing014/msing014b fit2004 comp643 bu1002 cm2030
联系我们
EMail: 99515681@qq.com
QQ: 99515681
留学生作业帮-留学生的知心伴侣!
工作时间:08:00-21:00
python代写
微信客服:codinghelp
站长地图