您的位置:首页 > 编程语言 > MATLAB

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

2013-11-11 21:05 537 查看
下面是对全国200多个城市人口和GDP进行线性回归:

样本获取:http://pan.baidu.com/s/1qu6dq
梯度下降回归:

%% linear regression from sunjerdege with matlab
clear 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;

% 先看看整体是否有线性的趋势
figure
hold on
plot(x, y, 'b.');
title('2011全国城市人口与GDP散点图');
xlabel('人口(万)');
ylabel('GDP(亿)');

% 用matlab内置函数拟合
p = polyfit(x, y, 1);   % 计算回归系数
p_y = polyval(p, x);     % 根据回归系数计算拟合的y
plot(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);    % 代价函数
end
end
figure
surf(th0, th1, J);
title('曲面图')
figure
contour(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

%% 显示
figure
hold on
plot(x,y,'b.');
plot(x, X*theta, 'r')
legend('散点图','回归结果',1);
title('回归结果');
hold off

figure
hold on
contour(th0,th1, J, 70);
plot(theta(1), theta(2), 'r*','MarkerSize', 5, 'LineWidth', 5);
legend('等高图','寻找到的最优');
title('等高图-最优点');
hold off


效果:









内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: