Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Q 1 ) Gradient Descent. Expected to fill in the missing lines of code to get the algorithm to work as expected. The script takes
Q Gradient Descent.
Expected to fill in the missing lines of code to get the algorithm to work as expected. The script takes no additional parameters.
There are four places where you need to add lines of code. lines of code should go inbetween the lines with the comment:
##### To be Updated #####
and
#########################
NOTE:
You should NOT modify any other lines of the script.
Deliverables:
A A screenshot of the D plot obtained when you execute the python script after adding lines of code.
B Console output obtained obtained when you execute the python script after adding lines of code.
C The equations of the Loss function and gradient of loss function on which the gradient descent was performed.
D State whether the algorithm converged to the global minima, a local minima or if it failed to converge in our case
Python Code:import numpy as np
import matplotlib.pyplot as plt
import random
studentid xx
studentid joini for i in studentid if iisdigit
random.seedstudentid
# set the number of iterations and learning rate
iters random.randint
learningrate
# Evaluate the function at x
def Cx:
##### To be Updated #####
# NOTE: return value of this function will
# ALSO change for Q of the assignment
#########################
return xT@nparray@xnparrayreshapeT@x
# Evaluate the gradient of function at x
def dCx:
##### To be Updated #####
# Compute and return the gradient
return
#########################
def plotgradchangeXYZ c gradxs gradxs gradys:
fig pltfigure
titlestr "Gradient Descent:"lrstrlearningrate
plttitletitlestr
ax fig.addsubplotprojectiond
axplotsurfaceX Y Z cmappltcmYlGnBuralpha
for i in rangelengradxs:
axplotgradxsigradxsi gradysi markerfacecolorr markeredgecolorr markero markersize
axtextgradxsgradxsgradys
strroundgradxs
strroundgradxs
strroundgradys
pltshow
def GDstartxyz c dc iters, eta:
px start.astypefloat
py cpxastypefloat
printGD Start Point:",pxpy
printNum steps:",iters
gradxs gradxs gradys pxpxpy
for iter in rangeiters:
##### To be Updated #####
# Update px using gradient descent
px
# Update py
py
#########################
gradxsappendpx
gradxsappendpx
gradysappendpy
printConverged Point:",pxpy
plotgradchangexyz c gradxsgradxs gradys
lo
hi
x roundrandomuniformlo
x roundrandomuniformlo
x nplinspacelo hi
y nplinspacelo hi
X Y npmeshgridx y
Z npzeroslikeX
for i in rangeXshape:
for j in rangeXshape:
Zij CnparrayXijYijreshape
# start Gradient Descent
GDnparrayxxreshapeXYZ C dC iters, learningrate
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started