问题描述
我正在尝试使用MATLAB中的Gradient Descent算法计算全局最小值。 派生形式为: Equation
我的代码是:
%Load and split the features and label
data = load('Data.txt');
X = data(:,1:2);
y = data(:,3);
%Add a new feature
X = [ones(m,1),X];
%Define the length and initial theta value
[m,n] = size(X);
alpha = 0.01;
iteration = 400;
theta = zeros(n,1);
[theta,hist] = GradientDescent(X,y,m,alpha,theta,iteration);
J = CostFunction(X,m);
fprintf('The cost for inital value zero is: %f\n',J);
fprintf('Minimum Gradient Descent is:\n')
fprintf('%f\n',theta)
我的GradientDescent功能是:
function [theta,iteration)
hist = zeros(m,1);
for i = 1:iteration
z = X * theta;
sigmoid = Sigmoid(z);
theta = theta - sum((alpha/m) *(X' * (sigmoid - y)));
hist(i) = CostFunction(X,m);
end
成本函数为:
function [J,grad] = CostFunction(X,m)
J = 0;
z = X * theta;
hpyX = Sigmoid(z);
J = (1/m) .* ((-y' * log(hpyX)) - ((1-y)' * log(1-hpyX)));
grad = (1/m) * (X' * (hpyX - y));
end
end
和Sigmoid函数是:
function sigmoid = Sigmoid(z)
sigmoid = zeros(size(z));
sigmoid = 1 ./ (1 + exp(-z));
end
我正在输出:
The cost for initial value zero is: *NaN*
Minimum Gradient Descent is:
0.413048
0.413048
0.413048
另一方面,当我在 fminunc 中获得400次迭代的不同结果时:
option = optimset('GradObj','on','MaxIter',400);
[theta,cost] = fminunc(@(t)(CostFunction(X,t,m)),option);
fprintf('The cost function by fminunc is: %f\n',J)
fprintf('Theta is:\n')
fprintf('%f\n',theta)
输出
The cost function by fminunc is: 0.693147
Theta is:
-25.161343
0.206232
0.201472
我不明白为什么我变得与众不同?我在梯度下降函数中犯错了吗?另外,当我计算梯度下降时,我得到了成本函数的NaN值。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)