【问题标题】:Gradient descent Matlab梯度下降 Matlab
【发布时间】:2014-04-11 16:23:33
【问题描述】:

我在 Matlab 中遇到梯度下降问题。 我不知道如何构建函数。

默认设置:

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

我的逻辑回归成本函数:(正确???)

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

现在是我的梯度下降函数:

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

感谢所有帮助 :),汉斯

【问题讨论】:

    标签: matlab gradient


    【解决方案1】:

    您可以在常规 matlab 函数中指定成本函数的代码:

    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
    

    然后,创建您的梯度下降方法(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
    

    并使用可用于评估成本的 函数 对象调用它:

    % 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);
    

    您还可以查看fminunc, built in Matlab's method for function optimization,其中包括梯度下降的实现以及其他最小化技术。

    问候。

    【讨论】:

      猜你喜欢
      • 2014-07-22
      • 2014-03-14
      • 1970-01-01
      • 2011-07-04
      • 2013-10-29
      • 1970-01-01
      • 2016-06-13
      • 2017-02-18
      • 2014-03-21
      相关资源
      最近更新 更多