[机器学习实验1]Linear Regression

来源:互联网 发布:nokia n8软件下载 编辑:程序博客网 时间:2024/05/16 06:22

线性回归分析,最简单的一个预测模型,也属于机器学习中的监督学习的范畴,这里主要对LINEAR REGRESSION I这部分的实验做个记录。
具体的理论要去看Andrew Ng大神的机器学习课程http://cs229.stanford.edu
问题如下:
这里写图片描述
对提供的数据进行线性回归并分析几个问题。题目链接http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex2/ex2.html

原理和公式在课程的笔记中有
这里写图片描述
h(x)就是我们要求的预测函数,θ是我们要进行迭代求最优解的参数,x是输入变量,一般维度比较大,比如和n个因素相关,那么就是n维的。

这里写图片描述
这里的α称为学习率learning rate。

这里写图片描述
J(θ)函数为cost function既代价函数,我们迭代的公式就是由它推出来的,推导过程很简单,一阶导即可。
这里写图片描述

下面附上matlab代码:

function LinearRegression()x = load('ex2x.dat');%年龄y = load('ex2y.dat');%身高figure % open a new figure windowplot(x, y, 'o');ylabel('Height in meters')xlabel('Age in years')m = length(y); % store the number of training examplesx = [ones(m, 1), x]; % Add a column of ones to xtheta = ones(size(x(1,:)))'; % initialize fitting parametersN=1500;%迭代次数alph = 0.07;sum = [0;0];for i=1:N%%这里这样写死因为写C写习惯了。。不习惯matlab的矩阵方式,但是用它矩阵来就很简单的两句就算出来了     %%Here is the gradient   %grad = (1/m).* x' * ((x * theta) - y);    %%Here is the actual update   %theta = theta - alpha .* grad;    for j=1:m    h= x * theta;    sum(1,1) =sum(1,1)+ (h(j,1)-y(j,1))*x(j,1)/m;    sum(2,1) =sum(2,1)+ (h(j,1)-y(j,1))*x(j,2)/m;    end    theta(1,1) = theta(1,1)-alph*sum(1,1);    theta(2,1) = theta(2,1)-alph*sum(2,1);    sum(1:2)=0;endhold on % Plot new data without clearing old plotplot(x(:,2), x*theta, '-') % remember that x is now a matrix with 2 columns                           % and the second column contains the time infolegend('Training data', 'Linear regression')predic_x1=[1,3.5];ans_3point5 = predic_x1*theta;predic_x2=[1,7];ans_7 = predic_x2*theta;thetaans_3point5ans_7end

代码运行的结果
这里写图片描述
这里写图片描述
我们可以根据我们求出的h(x)方程预测年龄是3.5和7的孩子的身高。
最后还有对代价函数的一些理解,代价函数一般是高维度(和x同维度),所以一般是不画出来的,但是这个例题中的维度是2,所以可以画出来,是碗状的,说明不存在局部最优解,只存在全局最优解,那么毫无疑问地说明LMS算法得到的最优解就是全局最优解了。

这里写图片描述

转载请注明出处:http://blog.csdn.net/gyh_420/article/details/77658058

阅读全文
1 0
原创粉丝点击