Calculating the gradient at Gradient Ascent Algorithm
6 views (last 30 days)
Show older comments
Hi, The code below is suppose to perform gradient ascent after implementation of the missing parts. There are several things I dont' know how to do, the first one being how to "Calculate the gradient at StartPt" which is suppose to be done in the for loop. I would very much appriciate help from you guys.
Thank you very much.
function GradientAscentEg
% plot the landscape
ezmesh(@ComplexLandscape,[-3 7],[-3 7])
% Enter maximum number of iterations of the algorithm, learning rate and
% mutation range
NumSteps=50;
LRate=0.1;
MaxMutate=1;
% TO DO: choose a random starting point with x and y in the range, (-2, 2)
GradAscent(StartPt,NumSteps,LRate);
% HillClimb(StartPt,NumSteps,MaxMutate);
function GradAscent(StartPt,NumSteps,LRate)
PauseFlag=1;
hold on;
for i = 1:NumSteps
% TO DO: Calculate the 'height' at StartPt using SimpleLandscape
% TO DO: Plot a point on the landscape in 3D
% use plot3(x,y,z,,'r*','MarkerSize',10)
% to get a marker you can see well
% TO DO: Calculate the gradient at StartPt
% TO DO: Calculate the new point and update StartPoint
% Make sure StartPt is within the specified bounds
StartPt = max([StartPt;-2 -2]);
StartPt = min([StartPt;2 2]);
% Pause to view output
if(PauseFlag)
x=input('Press return to continue\nor 0 and return to stop pausing\n');
if(x==0) PauseFlag=0; end;
end
end
hold off
0 Comments
Answers (1)
Walter Roberson
on 7 Nov 2016
What is it that you are trying to take the gradient of? Is it the function handle @ComplexLandscape ? Is it @SimpleLandscape ? What are their input variables?
If you are trying to take the the numeric gradient of a function near the starting point, then you need to evaluate the function at 9 points total, all combinations of x0, x0-dx, x0+dx, y0, y0-dy, y0+dy . Then you can use gradient()
2 Comments
Walter Roberson
on 7 Nov 2016
Then it sounds like you just have to call SimpleLandscapeGrad and pass in the initial point.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!