机器学习-4 线性回归 代码 matlab

来源:互联网 发布:jni java c 相互调用 编辑:程序博客网 时间:2024/05/17 17:58

下面是对全国200多个城市人口和GDP进行线性回归:

  • 样本获取:http://pan.baidu.com/s/1qu6dq
  • 梯度下降回归
    %% linear regression from sunjerdege with matlabclear all;%% read GDP data% c1: city;c2:population;c3:GDP[city x y] = textread('城市人口_GDP数据.txt','%s%f%f');[num tmp] = size(x);x = x/1000;y = y/1000;% 先看看整体是否有线性的趋势figurehold onplot(x, y, 'b.');title('2011全国城市人口与GDP散点图');xlabel('人口(万)');ylabel('GDP(亿)');% 用matlab内置函数拟合p = polyfit(x, y, 1);   % 计算回归系数p_y = polyval(p, x);     % 根据回归系数计算拟合的yplot(x, p_y, 'r');legend('','matlab内置拟合',1);hold off%% 自己拟合一下% hypothesis function: H = th1 + th2 * x;% cost function: J = 1/(2*num)  * sum((H - y).^2);% 画一下代价函数的图size = 50;th0 = linspace(-1000, 1000, size);      % 在-1000和1000之间生成50个数th1 = linspace(-1000, 1000, size);J = zeros(length(th0), length(th1));    % 生成J代价矩阵X = [ones(num, 1), x(:,1)];             % 方便计算,th0对应的X为1(y = th0*1 + th1*x1)for i = 1 : length(th0)    for j = 1 : length(th1)        theta = [th0(i); th1(j)];         J(i,j) = 1/(2 * num) * sum((X * theta - y).^2);    % 代价函数     endendfiguresurf(th0, th1, J);title('曲面图')figurecontour(th0,th1, J, 70);title('等高线图');%% 梯度下降寻找最优点iter_cnt = 2500;        % 迭代次数alpha = 0.01;           % 寻找的速度theta = zeros(2,1);     % 初始化阈值iter_J = [];            % 迭代中的代价for iter = 1:iter_cnt    % 更新阈值    theta = theta - alpha * ( 1 / num * sum( ((X * theta - y)' * X), 1) )';    % 求代价函数    iter_J(iter) = 1/(2 * num) * sum((X * theta - y).^2);end%% 显示figurehold onplot(x,y,'b.');plot(x, X*theta, 'r')legend('散点图','回归结果',1);title('回归结果');hold offfigurehold oncontour(th0,th1, J, 70);plot(theta(1), theta(2), 'r*','MarkerSize', 5, 'LineWidth', 5);legend('等高图','寻找到的最优');title('等高图-最优点');hold off
  • 效果:






原创粉丝点击