简体   繁体   English

梯度下降Matlab

[英]Gradient descent Matlab

i have a problem with gradient descent in Matlab. 我在Matlab中有梯度下降问题。 I dont know how to build the function. 我不知道如何建立功能。

Default settings: 默认设置:

  max_iter = 1000;
  learing = 1;
  degree = 1;

My logistic regression cost function: (Correct ???) 我的逻辑回归成本函数:(正确???)

function [Jval, Jgrad] = logcost(function(theta, matrix, y)
 mb = matrix * theta;
 p = sigmoid(mb);

 Jval = sum(-y' * log(p) - (1 - y')*log(1 - p)) / length(matrix);

if nargout > 1
    Jgrad = matrix' * (p - y) / length(matrix);
end

and now my gradient descent function: 现在是我的梯度下降函数:

function [theta, Jval] = graddescent(logcost, learing, theta, max_iter)

[Jval, Jgrad] = logcost(theta);
for iter = 1:max_iter 
  theta = theta - learing * Jgrad; % is this correct?
  Jval[iter] = ???

end

thx for all help :), Hans 谢谢所有的帮助:),汉斯

You can specify the code of your cost function in a regular matlab function: 您可以在常规的matlab函数中指定cost函数的代码:

function [Jval, Jgrad] = logcost(theta, matrix, y)
    mb = matrix * theta;
    p = sigmoid(mb);

    Jval = sum(-y' * log(p) - (1 - y')*log(1 - p)) / length(matrix);

    if nargout > 1
        Jgrad = matrix' * (p - y) / length(matrix);
    end
end

Then, create your gradient descent method ( Jgrad is automatically updated in each loop iteration): 然后,创建您的梯度下降方法(每次循环迭代都会自动更新Jgrad ):

function [theta, Jval] = graddescent(logcost, learing, theta, max_iter)
    for iter = 1:max_iter 
        [Jval, Jgrad] = logcost(theta);
        theta = theta - learing * Jgrad;
    end
end

and call it with a function object that can be used to evaluate your cost: 并使用可用于评估费用的函数对象进行调用:

% Initialize 'matrix' and 'y' ...
matrix = randn(2,2);
y = randn(2,1);

% Create function object.
fLogcost = @(theta)(logcost(theta, matrix, y));

% Perform gradient descent.
[ theta, Jval] = graddescent(fLogcost, 1e-3, [ 0 0 ]', 10);

You can also take a look at fminunc, built in Matlab's method for function optimization which includes an implementation of gradient descent, among other minimization techniques. 您还可以看一下fminunc,它是Matlab用于函数优化的方法所内置的,其中包括梯度下降的实现以及其他最小化技术。

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM