【问题标题】:Using fminunc function使用 fminunc 函数
【发布时间】:2012-05-14 11:34:48
【问题描述】:

我正在尝试使用 fminunc 函数进行凸优化。但是,在我的情况下,我采用的是关于 logx 的梯度。让我的目标函数为 F。那么梯度将是

dF/dx = (dF/dlogx) * (1/x)
= > dF/dlogx = (dF/dx) * x

所以

logx_new = logx_old + learning_rate * x * (dF/logx)
x_new = exp(logx_new)

如何在 fminunc 中实现这一点

【问题讨论】:

    标签: matlab convex-optimization


    【解决方案1】:

    这是可能的,并在documentation中描述:

    如果 fun 的梯度也可以计算并且 GradObj 选项为 'on',设置为 options = optimset('GradObj','on') 那么函数 fun 必须在第二个输出参数中返回梯度值 g,一个向量,在 x 处。

    具有自定义渐变的 fminunc

    例如:如果f = @(x) x.^2; 那么df/dx = 2*x 你可以使用

    function [f df] = f_and_df(x)
        f = x.^2;
        if nargout>1
            df = 2*x;
        end
    end
    

    然后您可以将该函数传递给fminunc

    options = optimset('GradObj','on');
    x0 = 5;
    [x,fval] = fminunc(@f_and_df,x0,options);
    

    带有 logx 梯度的 fminunc

    对于您的 logx 梯度,这变为:

    function [f df] = f_and_df(x)
        f = ...;
        if nargout>1
            df =  x * (dF/logx);
        end
    end
    

    fminunc 保持不变。

    带有匿名函数的fminunc

    如果你愿意,你也可以使用匿名函数:

    f_and_df2 = @(x) deal(x(1).^2+x(2).^2,[2*x(1)  2*x(2)]);
    [x,fval] = fminunc(f_and_df2,[5, 4],optimset('GradObj','on'))
    

    带有 logx 梯度的 fminunc 示例

    f = (log(x))^2 的其他示例

    function [f df_dlogx] = f_and_df(x)
        f = log(x).^2;
    
        df_dx = 2*log(x)./x;
        df_dlogx = df_dx.* x;
    end
    

    然后:

    >>x0=3;
    >>[x,fval] = fminunc(@f_and_df,x0,optimset('GradObj','on'))
    x =
       0.999999990550151
    
    fval =
       8.92996430424197e-17
    

    具有自定义渐变和多个变量的 fminunc 示例

    对于多个变量,例如f(x,y),您必须将变量放入向量中,例如:

    function [f df_dx] = f_and_df(x)
        f = x(1).2 + x(2).^2;
    
        df_dx(1) = 2*x(1);
        df_dx(2) = 2*x(2);
    end
    

    这个函数对应一个抛物面。 当然,您还必须使用向量作为初始起始参数,在这种情况下,例如:x0=[-5 3]

    【讨论】:

    • 我没听懂。它是如何 df = x * (dF/logx)。另外,如果我有多个变量,可以说 x,y,z 那么我该怎么做呢?
    • 我不知道你的实际函数或梯度是什么,这就是为什么我把你在问题中写的表达式:dF/dlogx = (dF/dx) * x。在我的回答中使用df,我的意思是实际梯度df/dx,或者对于你的情况,梯度到logx:dF/dx。我会尝试在我的帖子中再举一个例子
    猜你喜欢
    • 2016-09-08
    • 2011-10-28
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多