matlab - 如何在梯度下降法中获得正确的步长?
问题描述
我必须在 Matlab 中实现梯度下降法以获得最小点,但我无法猜测最佳步长并且我的代码不起作用。你能解释一下这个函数的步长吗?函数为:f(x,y) = - ((x* y* ((1-2 x y)/ (2 y+2 x)))^2); 起点:[1;1]
function [xopt,fopt,niter,gnorm,dx] = grad_descent
if nargin==0
% define starting point
x0 = [1 1]';
else
error('Incorrect number of input arguments.')
end
%tolerance
tol = 1e-6;
% maximum number of allowed iterations
maxiter = 100 ;
dxmin = 1e-6;
% step size
alpha = 0.33;
gnorm = inf; x = x0; niter = 0; dx = inf;
% define the objective function:
f = @(x1, x2) - ((x1* x2* ((1-2*x1*x2)/ (2*x2+2*x1)))^2);
% plot objective function for visualization:
figure(1); clf; ezcontour(f,[-5 5 -5 5]); axis equal; hold on
% redefine objective function syntax for use with optimization:
f2 = @(x) f(x(1),x(2));
% gradient descent algorithm:
while and(gnorm>=tol, and(niter <= maxiter, dx >= dxmin))
% calculate gradient:
g = grad(x);
gnorm = norm(g);
% take step:
xnew = x - alpha*g;
% plot current point
plot([x(1) xnew(1)],[x(2) xnew(2)],'ko-')
refresh
% update termination metrics
niter = niter + 1;
dx = norm(xnew-x);
x = xnew;
end
xopt = x;
sprintf("The point of minimum (x; y) : %f %f \n Function value in this point: %f", xopt, f2(xopt))
niter = niter - 1;
% define the gradient of the objective (derrivative function)
function g = grad(x)
g = [-( (x(1)*x(2)^3*(4*x(1)^3*x(2) + 8*x(1)^2*x(2)^2 -2*x(1)^2-6*x(1)*x(2) +1) )/ (2*(x(1)+x(2))^3) )
-( (x(1)^3*x(2)*(4*x(1)*x(2)^3 + 8*x(1)^2*x(2)^2 -2*x(2)^2-6*x(1)*x(2) +1) )/ (2*(x(1)+x(2))^3) )];
解决方案
推荐阅读
- ios - 如何正确将字符串转换为日期?
- django - 如何组合日期字段和时间字段以存储在 Django api 发布请求中的日期时间字段中?
- c++ - 在 C++ 中使重载的成员访问运算符返回一个临时值
- javascript - 折叠 rowGroup 闪亮
- jquery - 具有不同内容的 Jquery 对话框
- android - 为 Android 运行 dx 或 d8 工具时出错
- powerbi - Power BI - 显示前一个工作日的数据 - 不包括周末
- php - 如何在数据表复选框中更新多个使用 php/ajax?
- java - 使用 JSoup 调用 JSP 函数
- asp.net-core - 如何改进工厂方法以便能够以正确的方式注册依赖项