梯度函数无法找到最佳 theta 但正规方程可以

问题描述

我尝试使用一些样本数据实现我自己的线性回归模型在八度音程,但 theta 似乎不正确并且与正常提供的不匹配给出正确的 theta 值的方程。 但是在 Andrew Ng 的机器学习课程中的数据上运行我的模型(使用不同的 alpha 和迭代)为假设提供了适当的 theta。我已经调整了 alpha 和迭代,以便成本函数降低。 This is the image of cost function against iterations.如您所见,成本下降并趋于平稳,但成本还不够低。有人可以帮助我理解为什么会发生这种情况以及我可以做些什么来解决它吗?

这是数据(第一列是 x 值,第二列是 y 值):

20,48
40,55.1
60,56.3
80,61.2
100,68

Here is the graph of the data and the equations plotted by gradient descent(GD) and by the normal equation(NE).

主脚本代码

clear,close all,clc;

%loading the data
data = load("data1.txt");

X = data(:,1);
y = data(:,2);

%Plotting the data
figure
plot(X,y,'xr','markersize',7);
xlabel("Mass in kg");
ylabel("Length in cm");

X = [ones(length(y),1),X];
theta = ones(2,1);


alpha = 0.000001; num_iter = 4000;
%running gradientDescent
[opt_theta,J_history] = gradientDescent(X,theta,alpha,num_iter);

%running normal equation
opt_theta_norm = pinv(X' * X) * X' * y;

%Plotting the hypothesis for GD and NE
hold on
plot(X(:,2),X * opt_theta);
plot(X(:,X * opt_theta_norm,'g-.',"markersize",10);
legend("Data","GD","NE");
hold off

%Plotting values of prevIoUs J with each iteration
figure
plot(1:numel(J_history),J_history);
xlabel("iterations"); ylabel("J");

寻找梯度下降的函数

function [theta,J_history] = gradientDescent (X,num_iter)

m = length(y);
J_history = zeros(num_iter,1);
for iter = 1:num_iter
  theta = theta - (alpha / m) * (X' * (X * theta - y));
  J_history(iter) = computeCost(X,theta);
endfor
endfunction

计算成本的函数

function J = computeCost (X,theta)
  
J = 0;
m = length(y);
errors = X * theta - y;
J = sum(errors .^ 2) / (2 * m);

endfunction

解决方法

试试 alpha = 0.0001num_iter = 400000。这将解决您的问题!

现在,您的代码的问题是学习率太低,这会减慢收敛速度。此外,您没有给它足够的时间来收敛,将训练迭代次数限制为 4000 次,这在学习率的情况下非常少。

总而言之,问题在于:学习率较低 + 迭代次数较少