初入机器学习,根据吴恩达的机器学习课程学习,根据1978-2012年农村收入与支出数据进行线性回归相关知识的练习。hello.txt数据是从网上得到。
matlab代码
%% linear regression from sunjerdege with matlab
clear;
%% read GDP data
% c1: city;c2:population;c3:GDP
[ x,y] = textread('hello.txt','%f%f');
[num tem] = size(x);
x = x/1000;
y = y/1000;
% 先看看整体是否有线性的趋势
figure
hold on
plot(x, y, 'b.');
title('1978-2012全国农村居民收入与支出散点图');
xlabel('人均收入(千元)');
ylabel('人均支出(千元)');
% 用matlab内置函数拟合
p = polyfit(x, y, 1); % 计算回归系数
p_y = polyval(p, x); % 根据回归系数计算拟合的y
plot(x, p_y, 'r');
legend('matlab内置拟合','回归结果','NorthEast');
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('散点图','回归结果','NorthEast');
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
心得:线性回归只适应于小部分数据分布大致线性,对应多数数据而已,运用非线性回归得到的函数更科学;
运用MATLAB内置回归函数方便解决线性回归问题,自己拟合并运用梯度算法计算最优解,帮助理解相关知识。
本文通过吴恩达的机器学习课程,使用1978-2012年的农村收入与支出数据,实践了线性回归算法。利用MATLAB内置函数进行数据拟合,并自行实现梯度下降法来寻找最优解。

被折叠的 条评论
为什么被折叠?



