[机器学习实验1]Linear Regression

线性回归分析,最简单的一个预测模型,也属于机器学习中的监督学习的范畴,这里主要对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 window
plot(x, y, 'o');
ylabel('Height in meters')
xlabel('Age in years')
m = length(y); % store the number of training examples
x = [ones(m, 1), x]; % Add a column of ones to x
theta = ones(size(x(1,:)))'; % initialize fitting parameters
N=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;
end
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')
predic_x1=[1,3.5];
ans_3point5 = predic_x1*theta;
predic_x2=[1,7];
ans_7 = predic_x2*theta;
theta
ans_3point5
ans_7
end

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

这里写图片描述

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值