fminunc 函数的用法

无约束最优化 fminunc

官方文档

求无约束多变量函数的最小值

语法

x = fminunc(fun,x0)  % 最基本的用法,给定起始点求出局部最优解
x = fminunc(fun,x0,options) % 添加参数 options,指定一些如‘最优化方式’,‘迭代次数’等信息
x = fminunc(problem) % 用于求解问题矩阵
[x,fval] = fminunc(___) % 略
[x,fval,exitflag,output] = fminunc(___) % 略
[x,fval,exitflag,output,grad,hessian] = fminunc(___)  % 略

以求解logistic regression问题下的代价函数为例。

在运用梯度下降时,操作如下

[left{ egin{align} J( heta) &= -frac{1}{m}sum_{i=1}^{m}(y^{(i)}log(h_ heta(x)) + (1-y^{(i)})log(1-h_ heta(x))) + frac{lambda}{2m}sum_{j=1}^{n} heta_j^2 \ heta_j &= heta_j - alpha * frac{part{J( heta)}}{part{ heta_j}} end{align} ight. ]

运用fminunc函数不需要自定义梯度下降的求法,但需要为fminunc提供

  • 函数句柄

    % 实现定义 costFunction
    % function [J,grad] = costFunction(theta,X,y,lambda)
    %
    %
    % 创建句柄,自变量定为 t
    fun = @(t) costFunction(t,X,y,lambda);
    
  • 初始theta值

    % 对于简单的Logistic Regression,只需要将theta矩阵全部置0即可
    % 需要提前将X添加 x0 属性
    %
    %
    Init_theta = zeros(size(X,2),1);
    
  • 操作参数

    % options 中 'GradObj' 指定 fminunc 的求解最优化方式为 '梯度下降' , 'MaxIter' 指定迭代次数为400
    options = optimset('GradObj', 'on', 'MaxIter', 400);
    

运用fminuc

[theta, J, exit_flag] = ...
	fminunc(@(t)(costFunction(t, x, y, lambda)), initial_theta, options);
---- suffer now and live the rest of your life as a champion ----
原文地址:https://www.cnblogs.com/popodynasty/p/13689117.html