Matlab实现线性回归和逻辑回归: Linear Regression & Logistic Regression

本文为Maching Learning 栏目补充内容,为上几章中所提到单参数线性回归多参数线性回归和 逻辑回归的总结版。旨在帮助大家更好地理解回归,所以我在Matlab中分别对他们予以实现,在本文中由易到难地逐个介绍。

本讲内容:

Matlab 实现各种回归函数

=========================

基本模型

Y=θ0+θ1X1型---线性回归(直线拟合)

解决过拟合问题---Regularization

Y=1/(1+e^X)型---逻辑回归(sigmod 函数拟合)

=========================


第一部分:基本模型


在解决拟合问题的解决之前,我们首先回忆一下线性回归和逻辑回归的基本模型。

设待拟合参数 θn*1 和输入参数[ xm*n, ym*1 ] 。


对于各类拟合我们都要根据梯度下降的算法,给出两部分:

①   cost function(指出真实值y与拟合值h<hypothesis>之间的距离):给出cost function 的表达式,每次迭代保证cost function的量减小;给出梯度gradient,即cost function对每一个参数θ的求导结果。

function [ jVal,gradient ] = costFunction ( theta )

 

②   Gradient_descent(主函数):用来运行梯度下降算法,调用上面的cost function进行不断迭代,直到最大迭代次数达到给定标准或者cost function返回值不再减小。

function [optTheta,functionVal,exitFlag]=Gradient_descent( )

 

线性回归:拟合方程为hθ(x)=θ0x01x1+…+θnxn,当然也可以有xn的幂次方作为线性回归项(如),这与普通意义上的线性不同,而是类似多项式的概念。

其cost function 为:

 

逻辑回归:拟合方程为hθ(x)=1/(1+e^(θTx)),其cost function 为:

 

cost function对各θj的求导请自行求取,看第三章最后一图,或者参见后文代码。

后面,我们分别对几个模型方程进行拟合,给出代码,并用matlab中的fit函数进行验证。




第二部分:Y=θ0+θ1X1型---线性回归(直线拟合)

Matlab 线性拟合 & 非线性拟合中我们已经讲过如何用matlab自带函数fit进行直线和曲线的拟合,非常实用。而这里我们是进行ML课程的学习,因此研究如何利用前面讲到的梯度下降法(gradient descent)进行拟合。


cost function:
[cpp]  view plain  copy
  1. function [ jVal,gradient ] = costFunction2( theta )  
  2. %COSTFUNCTION2 Summary of this function goes here  
  3. %   linear regression -> y=theta0 + theta1*x  
  4. %   parameter: x:m*n  theta:n*1   y:m*1   (m=4,n=1)  
  5. %     
  6.   
  7. %Data  
  8. x=[1;2;3;4];  
  9. y=[1.1;2.2;2.7;3.8];  
  10. m=size(x,1);  
  11.   
  12. hypothesis = h_func(x,theta);  
  13. delta = hypothesis - y;  
  14. jVal=sum(delta.^2);  
  15.   
  16. gradient(1)=sum(delta)/m;  
  17. gradient(2)=sum(delta.*x)/m;  
  18.   
  19. end  

其中,h_func是hypothesis的结果:
[cpp]  view plain  copy
  1. function [res] = h_func(inputx,theta)  
  2. %H_FUNC Summary of this function goes here  
  3. %   Detailed explanation goes here  
  4.   
  5.   
  6. %cost function 2  
  7. res= theta(1)+theta(2)*inputx;function [res] = h_func(inputx,theta)  
  8. end  


Gradient_descent:
[cpp]  view plain  copy
  1. function [optTheta,functionVal,exitFlag]=Gradient_descent( )  
  2. %GRADIENT_DESCENT Summary of this function goes here  
  3. %   Detailed explanation goes here  
  4.   
  5.   options = optimset('GradObj','on','MaxIter',100);  
  6.   initialTheta = zeros(2,1);  
  7.   [optTheta,functionVal,exitFlag] = fminunc(@costFunction2,initialTheta,options);  
  8.   
  9. end  

result:
[cpp]  view plain  copy
  1. >> [optTheta,functionVal,exitFlag] = Gradient_descent()  
  2.   
  3. Local minimum found.  
  4.   
  5. Optimization completed because the size of the gradient is less than  
  6. the default value of the function tolerance.  
  7.   
  8. <stopping criteria details>  
  9.   
  10.   
  11. optTheta =  
  12.   
  13.     0.3000  
  14.     0.8600  
  15.   
  16.   
  17. functionVal =  
  18.   
  19.     0.0720  
  20.   
  21.   
  22. exitFlag =  
  23.   
  24.      1  



即得y=0.3+0.86x;
验证:
[cpp]  view plain  copy
  1. function [ parameter ] = checkcostfunc(  )  
  2. %CHECKC2 Summary of this function goes here  
  3. %   check if the cost function works well  
  4. %   check with the matlab fit function as standard  
  5.   
  6. %check cost function 2  
  7. x=[1;2;3;4];  
  8. y=[1.1;2.2;2.7;3.8];  
  9.   
  10. EXPR= {'x','1'};  
  11. p=fittype(EXPR);  
  12. parameter=fit(x,y,p);  
  13.   
  14. end  

运行结果:
[cpp]  view plain  copy
  1. >> checkcostfunc()  
  2.   
  3. ans =   
  4.   
  5.      Linear model:  
  6.      ans(x) = a*x + b  
  7.      Coefficients (with 95% confidence bounds):  
  8.        a =        0.86  (0.4949, 1.225)  
  9.        b =         0.3  (-0.6998, 1.3)  

和我们的结果一样。下面画图:
[cpp]  view plain  copy
  1. function PlotFunc( xstart,xend )  
  2. %PLOTFUNC Summary of this function goes here  
  3. %   draw original data and the fitted   
  4.   
  5.   
  6.   
  7. %===================cost function 2====linear regression  
  8. %original data  
  9. x1=[1;2;3;4];  
  10. y1=[1.1;2.2;2.7;3.8];  
  11. %plot(x1,y1,'ro-','MarkerSize',10);  
  12. plot(x1,y1,'rx','MarkerSize',10);  
  13. hold on;  
  14.   
  15. %fitted line - 拟合曲线  
  16. x_co=xstart:0.1:xend;  
  17. y_co=0.3+0.86*x_co;  
  18. %plot(x_co,y_co,'g');  
  19. plot(x_co,y_co);  
  20.   
  21. hold off;  
  22. end  




第三部分: 解决过拟合问题---Regularization

过拟合问题解决方法我们已在第三章中讲过,利用Regularization的方法就是在cost function中加入关于 θ的项,使得部分θ的值偏小,从而达到fit效果。
例如定义 costfunction J(θ): jVal=(theta(1)-5)^2+(theta(2)-5)^2;

在每次迭代中,按照gradient descent的方法更新参数θ:θ(i)-=gradient(i),其中gradient(i)是J(θ)对θi求导的函数式,在此例中就有gradient(1)=2*(theta(1)-5), gradient(2)=2*(theta(2)-5)。


函数costFunction, 定义jVal=J(θ)和对两个θ的gradient:


[cpp]  view plain  copy
  1. function [ jVal,gradient ] = costFunction( theta )  
  2. %COSTFUNCTION Summary of this function goes here  
  3. %   Detailed explanation goes here  
  4.   
  5. jVal= (theta(1)-5)^2+(theta(2)-5)^2;  
  6.   
  7. gradient = zeros(2,1);  
  8. %code to compute derivative to theta  
  9. gradient(1) = 2 * (theta(1)-5);  
  10. gradient(2) = 2 * (theta(2)-5);  
  11.   
  12. end  

Gradient_descent,进行参数优化
[cpp]  view plain  copy
  1. function [optTheta,functionVal,exitFlag]=Gradient_descent( )  
  2. %GRADIENT_DESCENT Summary of this function goes here  
  3. %   Detailed explanation goes here  
  4.   
  5.  options = optimset('GradObj','on','MaxIter',100);  
  6.  initialTheta = zeros(2,1)  
  7.  [optTheta,functionVal,exitFlag] = fminunc(@costFunction,initialTheta,options);  
  8.     
  9. end  

matlab主窗口中调用,得到优化厚的参数(θ1,θ2)=(5,5)
[cpp]  view plain  copy
  1.  [optTheta,functionVal,exitFlag] = Gradient_descent()  
  2.   
  3. initialTheta =  
  4.   
  5.      0  
  6.      0  
  7.   
  8.   
  9. Local minimum found.  
  10.   
  11. Optimization completed because the size of the gradient is less than  
  12. the default value of the function tolerance.  
  13.   
  14. <stopping criteria details>  
  15.   
  16.   
  17. optTheta =  
  18.   
  19.      5  
  20.      5  
  21.   
  22.   
  23. functionVal =  
  24.   
  25.      0  
  26.   
  27.   
  28. exitFlag =  
  29.   
  30.      1  


第四部分:Y=1/(1+e^X)型---逻辑回归(sigmod 函数拟合)

hypothesis function:
[cpp]  view plain  copy
  1. function [res] = h_func(inputx,theta)  
  2.   
  3. %cost function 3  
  4. tmp=theta(1)+theta(2)*inputx;%m*1  
  5. res=1./(1+exp(-tmp));%m*1  
  6.   
  7. end  

cost function:
[cpp]  view plain  copy
  1. function [ jVal,gradient ] = costFunction3( theta )  
  2. %COSTFUNCTION3 Summary of this function goes here  
  3. %   Logistic Regression  
  4.   
  5. x=[-3;      -2;     -1;     0;      1;      2;     3];  
  6. y=[0.01;    0.05;   0.3;    0.45;   0.8;    1.1;    0.99];  
  7. m=size(x,1);  
  8.   
  9. %hypothesis  data  
  10. hypothesis = h_func(x,theta);  
  11.   
  12. %jVal-cost function  &  gradient updating  
  13. jVal=-sum(log(hypothesis+0.01).*y + (1-y).*log(1-hypothesis+0.01))/m;  
  14. gradient(1)=sum(hypothesis-y)/m;   %reflect to theta1  
  15. gradient(2)=sum((hypothesis-y).*x)/m;    %reflect to theta 2  
  16.   
  17. end  

Gradient_descent:
[cpp]  view plain  copy
  1. function [optTheta,functionVal,exitFlag]=Gradient_descent( )  
  2.   
  3.  options = optimset('GradObj','on','MaxIter',100);  
  4.  initialTheta = [0;0];  
  5.  [optTheta,functionVal,exitFlag] = fminunc(@costFunction3,initialTheta,options);  
  6.   
  7. end  

运行结果:
[cpp]  view plain  copy
  1.  [optTheta,functionVal,exitFlag] = Gradient_descent()  
  2.   
  3. Local minimum found.  
  4.   
  5. Optimization completed because the size of the gradient is less than  
  6. the default value of the function tolerance.  
  7.   
  8. <stopping criteria details>  
  9.   
  10.   
  11. optTheta =  
  12.   
  13.     0.3526  
  14.     1.7573  
  15.   
  16.   
  17. functionVal =  
  18.   
  19.     0.2498  
  20.   
  21.   
  22. exitFlag =  
  23.   
  24.      1  

画图验证:

[cpp]  view plain  copy
  1. function PlotFunc( xstart,xend )  
  2. %PLOTFUNC Summary of this function goes here  
  3. %   draw original data and the fitted   
  4.   
  5. %===================cost function 3=====logistic regression  
  6.   
  7. %original data  
  8. x=[-3;      -2;     -1;     0;      1;      2;     3];  
  9. y=[0.01;    0.05;   0.3;    0.45;   0.8;    1.1;    0.99];  
  10. plot(x,y,'rx','MarkerSize',10);  
  11. hold on  
  12.   
  13. %fitted line  
  14. x_co=xstart:0.1:xend;  
  15. theta = [0.3526,1.7573];  
  16. y_co=h_func(x_co,theta);  
  17. plot(x_co,y_co);  
  18. hold off  
  19.   
  20. end  



有朋友问,这里就补充一下logistic regression中gradient的推导:
则有
由于cost function
可得
所以gradient = -J'(theta) = (z-y)x



关于Machine Learning更多的学习资料将继续更新,敬请关注本博客和新浪微博Sophia_qing

==============================

from: http://blog.csdn.net/abcjennifer/article/details/7732417
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 线性回归是一种统计学方法,可用于预测数值型变量之间的关系,如房价和房屋尺寸之间的关系。在这个场景下,我们考虑通过线性回归来建立一种模型,在已知的房屋尺寸的基础上,预测相应的房价。 假设我们有一个包含有房价和房屋尺寸的数据集,我们可以使用数据探索的工具,如散点图,来初步探索两个变量之间的关系。然后,我们可以使用线性回归模型来拟合这些数据点,并且预测新的房屋尺寸的房价。 接下来,我们将绘制一个图形来展示我们的线性回归模型如何拟合数据点和预测房价。在这张图中,我们将在横轴上表示房屋尺寸,纵轴上表示房价,并绘制出我们的线性回归模型所拟合的直线。这张图将使我们更容易地理解房价和房屋尺寸之间的关系,并且可以用于后续的数据分析以及预测。 在绘制完这张图后,我们可以检查线性回归模型的拟合精度。如果线性回归模型在数据集中存在显著的偏差,就需要重新考虑预测模型,或者增加更多的特征变量,这样可以使预测的结果更准确。此外,在应用线性回归模型之前,我们还应该注意一些其他的影响因素,如噪声或异常值,这样可以避免模型的偏差以及其他的预测错误。 ### 回答2: 线性回归是一种常用的机器学习算法,可以用于预测房价等连续值的问题。具体地说,线性回归就是通过找到一条直线(或者超平面,在高维空间中)来尽可能地拟合已知数据,然后利用这条直线进行预测。 在房价预测的问题中,我们可以使用线性回归算法来构建一个模型。首先,我们需要收集一些房价相关的数据,例如房屋面积、地理位置、年龄等等。然后,我们可以使用这些数据来训练线性回归模型,找到一个最优的线性函数,使得它最好地拟合已有的数据。 训练模型之后,我们就可以利用这个模型来进行预测。比如,我们输入某个房屋的面积、位置等信息,就可以利用模型预测这个房屋的价格了。 为了更加直观地理解线性回归算法,我们可以绘制出数据点和拟合直线的图像。在这个图像中,我们可以看到每一个数据点的位置,以及拟合直线的位置,这样可以更加方便地理解线性回归算法的表现。 总之,线性回归是一种非常实用的机器学习算法,它可以帮助我们解决很多连续值预测的问题,例如房价预测等。同时,在理解线性回归算法的时候,我们可以通过绘制图像来更好地理解模型的表现。 ### 回答3: 线性回归是一种广泛用于预测连续数值的统计学方法,常用于房价预测。我们可以通过已知的房屋面积、房龄等特征,拟合出一个数学函数,进而计算出未知房屋的价格。下面我将简单介绍如何使用Python中的scikit-learn库进行线性回归分析,以及如何绘制预测结果的图像。 首先,我们需要加载数据并探索数据的基本特征。数据可以从Kaggle等网站下载得到。以Boston House Price数据集为例,我们可以通过Pandas库读入数据并查看前几行数据的情况: ``` import pandas as pd df = pd.read_csv(&#39;train.csv&#39;) print(df.head()) ``` 接下来,我们需要针对数据的特征选择适当的模型进行拟合。这里我们选取最简单的线性回归模型。通过scikit-learn库中的LinearRegression模块,可以方便地进行模型训练。 ``` from sklearn.linear_model import LinearRegression X = df[[&#39;RM&#39;, &#39;LSTAT&#39;, &#39;PTRATIO&#39;]] # 我们选择房间数量、低收入人群比例以及学生与教师之比三个特征来预测房价 y = df[&#39;MEDV&#39;] lr = LinearRegression() lr.fit(X, y) # 模型拟合 ``` 至此,我们已经拟合出了一个模型,可以使用测试数据集进行预测并计算模型的评估指标,例如均方误差(Mean Squared Error,MSE)等。同时,我们还可以通过matplotlib库绘制出预测结果的图像: ``` import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set(style=&#39;whitegrid&#39;, context=&#39;notebook&#39;) pred_y = lr.predict(X) plt.scatter(y, pred_y) plt.plot([0, 50], [0, 50], &#39;--k&#39;) plt.xlabel(&#39;True value&#39;) plt.ylabel(&#39;Predicted value&#39;) ``` 在图像中,横坐标代表真实房价,纵坐标代表预测房价。可以看到,预测结果与真实情况的差异较小,说明模型的拟合效果较好。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值