您的位置:首页 > 其它

机器学习练习之线性回归

2014-01-17 17:59 225 查看
       还是要打牢基础吧,再做做机器学习最基本的方法和技术。这个练习是线性回归,来自Andrew Ng的 机器学习课程http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex2/ex2.html

    线性回归是有监督的学习方法,给定一些训练数据,我们要找到数据中存在的规律,线性回归就是假定存在一条直线能够拟合训练数据,这样再给新的数据时,就可以用训练好的回归模型来对新数据作出预测。线性回归实质上式对输入样本的特征进行线性组合的结果,就是对输入的线性表达。

假设给定训练数据

,训练数据输入用X表示,输出用Y表示。

        用平方损失函数计算回归模型与真实值的误差:

    


     模型h就是线性模型,参数为theta。要求出最优的theta能使损失最小,就是使预测值尽量接近真实值。可以采用梯度下降算法来找出这样的theta。对于这个最小二乘问题,它也存在方程解的,方程解为



    这里采用batch梯度下降,每一次迭代都要扫描整个样本集,计算总代价对于theta的偏导即梯度,然后更新梯度,循环到预先设定的最大迭代次数或者误差小于一定范围就停止算法。关键要理解的是怎么算梯度,梯度的更新计算公式如下:



    上面的公式是矩阵向量的表达方式,也可以根据一个个样本来求解出梯度,但是用matlab实现时用这样的计算方式效率比对一个个样本算出梯度然后累加起来要快得多。

这个练习是预测男生身高与年龄的关系,输入x是年龄,输出是身高,要找到一个线性模型,尽量拟合训练数据,然后对于新数据作出预测。

程序如下:

%% Exercise: Linear regression
% From http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex2/ex2.html % 数据是不同男生的身高和体重,用线性回归模型对数据进行拟合
% 用到的算法是梯度下降
%%
x = load('ex2x.dat'); % x是男生年龄,是一个列向量
y = load('ex2y.dat'); % y是男生身高,也是一个列向量

figure % 打开新的绘画窗口
plot(x, y, 'o');
ylabel('Height in meters');
xlabel('Age in years');

m = length(y);  % m存储样本数目
x = [ones(m, 1), x]; % 给x添加第一列全为1,这样x的每一行有2个数,表示每个男生的特征,第二列才是男生年龄

theta = zeros(2, 1); % theta为权重参数,一个2维列向量,初始化为0
alpha = 0.07; %步长
MAX_ITR = 1500; %最多迭代次数
ERROR = 1e-10;
%Jtheta = 0; % 代价函数

%% 直接用最小二乘方法求解
%theta = inv(x'*x)*x'*y
%%

%% Batch gradient decent
for i=1:MAX_ITR
% Jtheta = 0.5/m*sum(x*theta-y).^2); 计算代价
grad = 1/m*x'*(x*theta-y); %计算梯度
prev_theta = theta;
theta = theta - alpha*grad;
if abs(prev_theta-theta)<ERROR
break
end
fprintf('%d\n',i);
end
theta
[1 3.5]*theta
[1 7]*theta

hold on % Plot new data without clearing old plot
plot(x(:,2), x*theta, '-'); % remember that x is now a matrix with 2 columns
% and the second column contains the time info
legend('Training data', 'Linear regression');
%%
%% Understand J(theta)
% 为了更好理解batch梯度下降所做的事情,这里画出J(theta)也就是损失与theta之间的关系
J_vals = zeros(100, 100); % initialize Jvals to 100x100 matrix of 0's
theta0_vals = linspace(-3, 3, 100); %从-3到3,中间均匀采集100个点
theta1_vals = linspace(-1, 1, 100);
for i = 1:length(theta0_vals)
for j = 1:length(theta1_vals)
t = [theta0_vals(i); theta1_vals(j)];
J_vals(i,j) = 0.5/m*sum((x*t-y).^2);
end
end

% Plot the surface plot
% Because of the way meshgrids work in the surf command, we need to
% transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';
figure;
surf(theta0_vals, theta1_vals, J_vals);
xlabel('\theta_0'); ylabel('\theta_1');

figure;
% Plot the cost function with 15 contours spaced logarithmically
% between 0.01 and 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2,2,15))
xlabel('\theta_0'); ylabel('\theta_1');
实验结果如下:





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