机器学习-线性回归

由于在blog里面编辑公式比较麻烦,我就现在word里面把文档编辑好,然后截的图。

数据下载 点这



源代码如下:

%function liner_regression()
    clc;
    clear;

    load('shuju.mat');
    %datashuju = shuju;
    data_x = shuju(:,1);
    data_y = shuju(:,2);
    syms theta0 theta1;
    %h = theta0 + theta1 * data_x;
    [r,c] = size(data_x);
    J = 0;
    for i = 1 : r
        J = J + (theta0 + theta1 * data_x(i) - data_y(i))^2;
    end
    J = J / (2 * r);
    theta = [theta0; theta1];
    
    diffJtheta0 = diff(J,theta0);
    diffJtheta1 = diff(J,theta1);
    diffJ = [diffJtheta0;diffJtheta1];
    
    theta_0 = [rand(1);rand(1)];
    theta_1 = theta_0;
    
    diffJtheta00 = diff(diffJtheta0,theta0);
    diffJtheta01 = diff(diffJtheta0,theta1);
    diffJtheta10 = diff(diffJtheta1,theta0);
    diffJtheta11 = diff(diffJtheta1,theta1);
    A = [diffJtheta00,diffJtheta01;diffJtheta10,diffJtheta11];
    bestalpha = diffJ'* diffJ /(diffJ' * A * diffJ);
    
    plot(data_x,data_y,'x');
    axis([0 6 0 12]);
    xlabel('x');
    ylabel('y');
    hold on
    refline(theta_0(2),theta_0(1));
    
    
    cnt1 = 0;
    
    
    while (norm(subs(diffJ,theta,theta_0)) > epsilon)
       tmp = subs(diffJ,theta,theta_0);
       % use the best step lenth
       %theta_0 = theta_0 - subs(bestalpha,theta,theta_0) * tmp;
       
       %use the given step lenth
       theta_0 = theta_0 - 0.05 * tmp;
       
       if(mod(cnt1 , 100) == 0)
            refline(theta_0(2),theta_0(1));
       end
       
       cnt1 = cnt1 + 1;
       %norm(subs(diffJ,theta,theta_0))
    end
    cnt1
    
    
    cnt2 = 0
    theta_0 = theta_1;
    figure(2);
    plot(data_x,data_y,'x');
    axis([0 6 0 12]);
    xlabel('x');
    ylabel('y');
    hold on
    refline(theta_0(2),theta_0(1));
    while (norm(subs(diffJ,theta,theta_0)) > epsilon)
       tmp = subs(diffJ,theta,theta_0);
       % use the best step lenth
       theta_0 = theta_0 - subs(bestalpha,theta,theta_0) * tmp;
       
       %use the given step lenth
      % theta_0 = theta_0 - 0.05 * tmp;
       
       %if(mod(cnt , 100) == 0)
            refline(theta_0(2),theta_0(1));
       %end
       
       cnt2 = cnt2 + 1;
       %norm(subs(diffJ,theta,theta_0))
    end
    cnt2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值