机器学习-4 线性回归 代码 matlab
2013-11-11 21:05
537 查看
下面是对全国200多个城市人口和GDP进行线性回归:
样本获取:http://pan.baidu.com/s/1qu6dq
梯度下降回归:
效果:
样本获取: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
效果:
相关文章推荐
- 频率f,角频率Ω和数字频率w的物理含义
- matlab 位操作
- MAC OX 10.8 环境下运行TLD算法(MATLAB版)
- Matlab基本函数-fix函数
- Matlab基本函数-feather函数
- matlab绘制世界地图的脚本
- MatLab2012b/MatLab2013b分类器大全(svm,knn,随机森林等)
- 徐海蛟:MatLab2012b/MatLab2013b分类器大全(svm,knn,随机森林等)
- Matlab滤波器设计(转)
- matlab绘制地理栅格数据示例
- Matlab文件不关联
- Matlab之graythresh()函数详解
- Matlab之imfilter()详解
- matlab绘制中国地图
- win7 64, matlab2012a文件关联
- matlab conv2 和filter2的区别
- Matlab中快速傅里叶变换FFT结果的物理意义(转载)
- matlab中关于FFT的使用(理解频率分辨率、补零问题)
- mod函数用法
- 小波学习之三(多孔算法与MATLAB swt剖析)