首页 > 解决方案 > 梯度函数无法找到最佳 theta,但正规方程可以

问题描述

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

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

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

这是由梯度下降 (GD) 和正规方程 (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, y, 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(:,2), 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, y, theta, alpha, 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, y, theta);
endfor
endfunction

计算代价函数:

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

endfunction

标签: machine-learninglinear-regressionoctave

解决方案


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

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

总结一下,问题是:学习率低+迭代次数少


推荐阅读