An error occurred when implementing gradient descent

3 vues (au cours des 30 derniers jours)
Nikky schulz
Nikky schulz le 6 Mar 2022
Modifié(e) : Nikky schulz le 21 Mar 2022
Given equation:
What can I modify in my code to plot the desired contour and plot the graph in this way:

Réponse acceptée

Torsten
Torsten le 6 Mar 2022
Modifié(e) : Torsten le 6 Mar 2022
What can I modify in my code to plot the desired contour and plot the graph in this way
Change the line
f = -200*(y-x^2)^2+ (1-x^2)^2;
to
f = 200*(y-x^2)^2+ (1-x^2)^2;
I suggest using
f = @(x)200*(x(2)-x(1)^2)^2+ (1-x(1)^2)^2;
g = @(x)[200*2*(x(2)-x(1)^2)*(-2*x(1))+2*(1-x(1)^2)*(-2*x(1)),200*2*(x(2)-x(1)^2)];
%f = 200*(y-x^2)^2+ (1-x^2)^2;
%g = gradient(f, [x, y]);
lr = 0.001;
eps = 1e-8;
iteration_limit = 1e4;
p = [0.3 0.5];
for i=1:iteration_limit
pGrad = g(p(end,:));
%pGrad = [subs(g(1),[x y],p(end,:)) subs(g(2),[x y],p(end,:))];
pTMP = p(end,:) - lr*pGrad;
%p = [p;double(pTMP)];
p = [p;pTMP];
%if sum( (p(end,:)-p(end-1,:)).^2 ) < eps
if sqrt(sum( (p(end,:)-p(end-1,:)).^2 ) )< eps
break
end
end
instead of the symbolic variant.
  4 commentaires
Nikky schulz
Nikky schulz le 7 Mar 2022
Modifié(e) : Nikky schulz le 7 Mar 2022
Can you show me how it's done? I edited this chunk of code and it showed an error again. Once again, thanks so much for helping me.
Edited code:
v = -10:.1:10;
[X, Y] = meshgrid(v,v);
contour(v,v,subs(f,[x(1) x(2)],{X,Y}))
hold on
quiver(v,v,, [x(1) x(2)], {X,Y}),g(2), [x(1) x(2)], {X,Y}))
plot(p(:,1),p(:,2))
hold off
subtitle(['Path Trajectory started from ',mat2str(round(p(1,:),3)),' with \eta=',num2str(lr)])
if i<iteration_limit
title(['converged to ',mat2str(round(p(end,:),3)),' after ',mat2str(i),' steps'])
else
title(['stopped at ',mat2str(round(p(end,:),3)),' without converging'])
end
Error Message:
Torsten
Torsten le 7 Mar 2022
f = @(x,y)200*(y-x.^2).^2+ (1-x.^2).^2;
g1 = @(x,y) 200*2*(y-x.^2).*(-2*x)+2*(1-x.^2).*(-2*x);
g2 = @(x,y) 200*2*(y-x.^2);
g = @(x,y)[g1(x,y),g2(x,y)];
lr = 0.001;
eps = 1e-8;
iteration_limit = 1e4;
p = [0.3 0.5];
for i=1:iteration_limit
pGrad = g(p(end,1),p(end,2));
pTMP = p(end,:) - lr*pGrad;
p = [p;pTMP];
if sqrt(sum( (p(end,:)-p(end-1,:)).^2 ) )< eps
break
end
end
v = -2:.01:2;
[X, Y] = meshgrid(v,v);
contour(v,v,f(X,Y))
hold on
quiver(v,v,g1(X,Y),g2(X,Y))
plot(p(:,1),p(:,2))
hold off
subtitle(['Path Trajectory started from ',mat2str(round(p(1,:),3)),' with \eta=',num2str(lr)])
if i<iteration_limit
title(['converged to ',mat2str(round(p(end,:),3)),' after ',mat2str(i),' steps'])
else
title(['stopped at ',mat2str(round(p(end,:),3)),' without converging'])
end

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by