machine-learning - 八度 fminunc 不收敛
问题描述
我正在尝试fminunc
在 Octave 中使用来解决后勤问题,但它不起作用。它说我没有定义变量,但实际上我做了。如果我直接在 costFunction 中定义变量,而不是在 main 中,它不会产生任何问题,但该函数并不能真正工作。事实上exitFlag
等于 -3 并且它根本不收敛。
这是我的功能:
function [jVal, gradient] = cost(theta, X, y)
X = [1,0.14,0.09,0.58,0.39,0,0.55,0.23,0.64;1,-0.57,-0.54,-0.16,0.21,0,-0.11,-0.61,-0.35;1,0.42,0.45,-0.41,-0.6,0,-0.44,0.38,-0.29];
y = [1;0;1];
theta = [0.8;0.2;0.6;0.3;0.4;0.5;0.6;0.2;0.4];
jVal = 0;
jVal = costFunction2(X, y, theta); %this is another function that gives me jVal. I'm quite sure it is
%correct because I use it also with other algorithms and it
%works perfectly
m = length(y);
xSize = size(X, 2);
gradient = zeros(xSize, 1);
sig = X * theta;
h = 1 ./(1 + exp(-sig));
for i = 1:m
for j = 1:xSize
gradient(j) = (1/m) * sum(h(i) - y(i)) .* X(i, j);
end
end
这是我的主要内容:
theta = [0.8;0.2;0.6;0.3;0.4;0.5;0.6;0.2;0.4];
options = optimset('GradObj', 'on', 'MaxIter', 100);
[optTheta, functionVal, exitFlag] = fminunc(@cost, theta, options)
如果我编译它:
optTheta =
0.80000
0.20000
0.60000
0.30000
0.40000
0.50000
0.60000
0.20000
0.40000
functionVal = 0.15967
exitFlag = -3
我该如何解决这个问题?
解决方案
您实际上没有fminunc
正确使用。从文档中:
-- fminunc (FCN, X0)
-- fminunc (FCN, X0, OPTIONS)
FCN should accept a vector (array) defining the unknown variables,
and return the objective function value, optionally with gradient.
'fminunc' attempts to determine a vector X such that 'FCN (X)' is a
local minimum.
您传递的不是接受单个向量参数的函数的句柄。相反,您传递的(即@cost
)是一个接受三个参数的函数的句柄。
您需要将其“转换”为仅接受一个输入的函数的句柄,并在后台执行您想要的操作。最简单的方法是将成本函数“包装”到一个只接受一个参数的匿名函数中,并cost
以适当的方式调用该函数,例如
fminunc( @(t) cost(t, X, y), theta, options )
注意:这假设 X 和 y 是在您执行此“包装”业务的范围内定义的
推荐阅读
- r - 什么会导致使用 %in% 函数 R 的 ```.``` 输出?
- c# - 尝试加载脚本时浏览器中的 C# Windows 窗体应用程序错误
- keras - Python 中深度 tensorflow keras 模型的输出与 tensorflowjs 转换的显着差异
- ios - 适用于 iOS 的 Azure Devops 管道集成
- package - 从 package.config 迁移的 Visual Studio 2019 没有执行迁移的选项,也没有错误
- salt-stack - 更新除内核之外的所有已安装软件包
- libgdx - Box2d RopeJoint 错误 - 修复或替代解决方案?
- sql - 更新oracle触发器之前:new pseudorecord中未设置列的值
- reactjs - 不了解在反应项目上运行 npm start 的 bebug.log 文件
- r - 如何将多个 csv 文件完全外部连接到 R 中的单个 data.table 中?