我正在尝试实现梯度下降算法,以根据Andrew Ng课程中的图像,将一条直线拟合到有噪声的数据上。
首先,我声明了我想拟合的有噪声的直线:
xrange =(-10:0.1:10); % data lenghtydata = 2*(xrange)+5; % data with gradient 2, intercept 5plot(xrange,ydata); grid on;noise = (2*randn(1,length(xrange))); % generating noise target = ydata + noise; % adding noise to datafigure; scatter(xrange,target); grid on; hold on; % plot a sctter
然后我初始化了两个参数和目标函数的历史记录如下:
tita0 = 0 %intercept (randomised)tita1 = 0 %gradient (randomised)% Initialize Objective Function HistoryJ_history = zeros(num_iters, 1);% Number of training examplesm = (length(xrange));
接着我编写了梯度下降算法:
for iter = 1:num_iters h = tita0 + tita1.*xrange; % building the estimated %c = (1/(2*length(xrange)))*sum((h-target).^2) temp0 = tita0 - alpha*((1/m)*sum((h-target))); temp1 = tita1 - alpha*((1/m)*sum((h-target))).*xrange; tita0 = temp0; tita1 = temp1; J_history(iter) = (1/(2*m))*sum((h-target).^2); % Calculating cost from data to estimateend
最后是绘图部分。我使用MATLAB内置的polyfit函数来测试我的拟合精度。
% print theta to screenfprintf('Theta found by gradient descent: %f %f\n',tita0, tita1(end));fprintf('Minimum of objective function is %f \n',J_history(num_iters));%Plot the linear fithold on; % keep previous plot visibledesgplot(xrange, tita0+xrange*tita1(end), '-'); title(sprintf('Cost is %g',J_history(num_iters))); % plotting line on scatter% Validate with polyfit fncpoly_theta = polyfit(xrange,ydata,1);plot(xrange, poly_theta(1)*xrange+poly_theta(2), 'y--');legend('Training data', 'Linear regression','Linear regression with polyfit')hold off
结果:
如图所示,我的线性回归效果很差。似乎两个参数(y截距和斜率)都没有收敛到最优解。
对于我的实现中可能存在的问题,任何建议都将不胜感激。我似乎无法理解我的解决方案与上述方程相比在哪里发生了偏离。谢谢!
回答:
您对theta_1的实现是错误的。Andrew Ng的方程还需要对x进行求和。您对theta_0和theta_1的实现是这样的:
temp0 = tita0 - alpha*((1/m)*sum((h-target)));temp1 = tita1 - alpha*((1/m)*sum((h-target))).*xrange;
请注意,sum((h-target))出现在两个公式中。您需要先乘以x,然后再进行求和。我不是MatLab程序员,所以无法修复您的代码。
在您的错误实现中,您实际上是在以相同的方向推动截距和斜率的预测值,因为您的变化总是与sum((h-target))成比例。这不是梯度下降的工作方式。