【问题标题】:Gradient descent Search implemented in matlab theta1 incorrect在 matlab theta1 中实现的梯度下降搜索不正确
【发布时间】:2019-03-22 13:30:44
【问题描述】:

我学习了吴恩达教授教授的机器学习课程。 This is the link

我尝试实施本课程的第一项作业。 练习 2:基于监督学习问题

的线性回归

1.使用 alpha=0.07 的学习率实现梯度下降。由于 Matlab/Octave 和 Octave 索引向量从 1 而不是 0 开始,您可能会在 Matlab/Octave 中使用 theta(1) 和 theta(2)来表示 theta0 和 theta1。

我写了一个matlab代码来解决这个问题:

clc
clear
close all

x = load('ex2x.dat');
y = load('ex2y.dat');
figure % open a new figure window
 plot(x, y, '*');
 ylabel('Height in meters')
 xlabel('Age in years')
m = length(y); % store the number of training examples
x = [ones(m, 1), x]; % Add a column of ones to x
theta = [0 0];
temp=0,temp2=0;
h=[];
alpha=0.07;n=2; %alpha=learning rate
for i=1:m
temp1=0;
for j=1:n
    h(j)=theta(j)*x(i,j);
    temp1=temp1+h(j);
end
temp=temp+(temp1-y(i));
temp2=temp2+((temp1-y(i))*(x(i,1)+x(i,2)));

end
theta(1)=theta(1)-(alpha*(1/m)*temp);
theta(2)=theta(2)-(alpha*(1/m)*temp2);

我得到了答案:

>> theta

theta =

0.0745    0.4545

Here, 0.0745 is exact answer but 2nd one is not accurate. 

实际答案

θ =

0.0745 0.3800

数据集在链接中提供。谁能帮我解决这个问题?

【问题讨论】:

    标签: matlab machine-learning linear-regression gradient-descent


    【解决方案1】:

    您会得到错误的结果,因为您编写了很容易出现错误的冗长不必要的代码,这正是我们拥有 matlab 的原因:

    clear
    
    x = load('d:/ex2x.dat');
    y = load('d:/ex2y.dat');
    figure(1), clf, plot(x, y, '*'), xlabel('Age in years'), ylabel('Height in meters')
    
    m = length(y); % store the number of training examples
    x = [ones(m, 1), x]; % Add a column of ones to x
    
    
    theta=[0,0];  alpha=0.07;
    
    residuals = x*theta' - y ; %same as:  sum(x.*theta,2)-y
    theta = theta - alpha*mean(residuals.*x);
    
    disp(theta)
    

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 2011-07-04
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2018-01-10
      相关资源
      最近更新 更多