我在 MATLAB 中有以下代码:
% Set options for fminunc
options = optimset('GradObj', 'on', 'MaxIter', 400);
% Run fminunc to obtain the optimal theta
% This function will return theta and the cost
[theta, cost] = ...
fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);
我的老师这样解释了最小化函数:
为了指定我们正在最小化的实际函数,我们使用“速记”
用于指定函数,例如@(t)(costFunction(t, X, y))
。这
创建一个带有参数的函数t
,这会调用你的costFunction
。这
允许我们包装costFunction
与使用fminunc
.
我实在无法理解什么@(t)(costFunction(t, X, y)
方法。两者是什么t
我们在做什么?那是什么样的表情呢?
在 Matlab 中,这称为匿名函数.
采取以下行:
f = @(t)( 10*t );
在这里,我们定义一个函数f
,需要一个参数t
,并返回10*t
。它可以用于
f(5) % returns 50
在你的情况下,你正在使用fminunc
它接受一个函数作为其第一个参数,并用一个参数来最小化 over。这可以被称为使用
X = 1; y = 1; % Defining variables which aren't passed into the costFunction
% but which must exist for the next line to pass them as anything!
f = @(t)(costFunction(t, X, y)); % Explicitly define costFunction as a function of t alone
[theta, cost] = fminunc(f, 0, options);
这可以通过不定义来缩短f
首先,只是打电话
[theta, cost] = fminunc(@(t)(costFunction(t, X, y)), 0, options);
进一步阅读
- 正如评论中提到的,这里有一个链接一般参数化函数 https://uk.mathworks.com/help/matlab/math/parameterizing-functions.html.
- 具体来说,这里有一个有关的文档链接匿名函数 https://uk.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)