博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python机器学习(二):线性回归算法
阅读量:6860 次
发布时间:2019-06-26

本文共 5060 字,大约阅读时间需要 16 分钟。

机器学习研究的问题分为分类问题回归问题。分类问题很好理解,而回归问题就是找到一条曲线,可以最大程度地拟合样本特征和样本输出标记之间的关系。当给算法一个输入时,这条曲线可以计算出相应可能的输出。回归算法最简单的就是线性回归。当样本特征只有一个时,称为简单线性回归;当样本特征有多个时,称为多元线性回归

img_09c23661093aebe566d5eb47705df8d4.png
线性回归

1.简单线性回归

由上图可知,简单线性回归只有一个特征x,一个标记y。假定x和y之间具有类似于线性的关系,就可以使用使用简单线性回归算法。假定我们找到了最佳拟合的直线方程

img_ea32a3521da780f2f384daf605473be5.png
最佳拟合的直线方程
则对于每一个样本点x(i),预测值如下。其中带箭头的y是预测值,称为 y head。右上角的 i 是指样本的索引。
img_e043034d0d842d41ec8e4075db66931d.png
预测值
我们希望预测值和真实值之间的差距尽量小。一般用欧氏距离来衡量。下式称为
损失函数(Loss Function)
img_2e8e0edfd16577ee12a048e4e5171252.png
损失函数
换句话说,我们的目标就是找到一组a和b,使得下式最小
img_e95b555f81a9a6b93a5f676a916aaa98.png
y(i)和x(i)是固定的

通过分析不同的问题,我们需要确定问题的损失函数。通过最优化损失函数,获得机器学习的模型。几乎所有的参数学习算法都是这样的套路

那么这个问题是一个典型的最小二乘法问题,即最小化误差的平方。推导可得以下公式

img_25d1aea6c77680e4460c98bfe599f664.png
最小二乘法

可以用python封装成这种形式

"""Created by 杨帮杰 on 10/1/18Right to use this code in any way you want withoutwarranty, support or any guarantee of it workingE-mail: yangbangjie1998@qq.comAssociation: SCAU 华南农业大学"""import numpy as npclass SimpleLinearRegression:    def __init__(self):        """初始化Simple Linear Regression 模型"""        self.a_ = None        self.b_ = None    def fit(self, x_train, y_train):        """根据训练数据集x_train,y_train训练Simple Linear Regression 模型"""        assert x_train.nidm == 1, \            "Simple Linear Regressor can only solve single feature training data."        assert len(x_train) == len(y_train), \            "the size of x_train must be equal to the size of y_train"        x_mean = np.mean(x_train)        y_mean = np.mean(y_train)        """进行向量化可以加快训练速度"""        # num = 0.0        # d = 0.0        # for x, y in zip(x_train, y_train):        #     num += (x - x_mean) * (y - y_mean)        #     d += (x - x_mean) ** 2        num = (x_train - x_mean).dot(y_train - y_mean)        d = (x_train - x_mean).dot(x_train - x_mean)        self.a_ = num/d        self.b_ = y_mean - self.a_ * x_mean        return self    def predict(self, x_predict):        """给定待预测数据集x_predict, 返回表示x_predict的结果向量"""        assert x_predict.ndim == 1, \            "Simeple Linear Regressor can only solve single feature training data."        assert self.a_ is not None and self.b_ is not None, \            "must fit before predict!"        return np.array([self._predict(x) for x in x_predict])    def _predict(self, x_single):        """给定单个待预测数据x_single, 返回x_single的预测结果值"""        return self.a_ * x_single + self.b_    def __repr__(self):        return "SimpleLinearRegression()"

衡量线性回归模型好坏有多个标准,均方误差(Mean Squared Error)、均方根误差(Root Mean Squared Error)、平均绝对误差(Mean Absolute Error)等。一般使用MSE。

img_a7b0d4f92723348421b4e40497f85ac8.png
均方误差MSE
img_10eae95b8954fdd08825e96ef06bcbee.png
均方根误差RMSE
img_5841879e1219ceeca0f1c30d8045f3ce.png
平均绝对误差MAE

而如果想像分类问题一样将评判得分限制在0和1之间,则应该使用R Square

img_7cb8a42ca0d772b3549d7ed266d7381c.png
R Square
右边一项的分子代表使用模型产生的错误,分母代表使用平均值进行预测产生的错误。分母也可以理解为一个模型,称为
Baseline Model

R Square的输出分为以下几种情况:

  • R^2 = 1,则模型不犯任何错误,完美
  • R^2 = 0,模型为基准模型,相当于没训练过
  • R^2 < 0,数据可能不存在任何线性关系

2.多元线性回归

多元线性回归,就是指样本特征值有多个。根据这多个特征值来预测样本的标记值。那么特征X和参数Θ就是一个向量。

img_2f78c1093556260e3032fbf287060e46.png
多元线性回归

相类似地,我们需要找到一个损失函数。我们需要找到一组参数Θ,使下式尽可能小

img_8f70459b6b81f09d5edbc6d2fd22488c.png
损失函数
img_5295623fe026b18cb28c8ae6d0910148.png
预测值有n个参数

为了方便进行矩阵运算,我们写成这种形式

img_6a8d455e9d2f81eec6c2546375a1cc9d.png
X0不是特征输入!

预测值可以写成这种形式

img_7978f9c054ce549034a6348ca1fc40b2.png
预测值和参数是n维向量,X是n维矩阵
X展开是这个样子。每一行是一个样本点,每一列(除了第一列)是一种特征
img_726925cd9e768cec00c83e3b4307cf7d.png
展开

经过推导,得到这样一个公式。这成为多元线性回归的正规方程解(Normal Equation)。结果就是参数向量。

img_dd546671996d6e29cfc4255510cf4eb1.png
我也不知道怎么来的

img_527459709419fdb5637bb1e87da89394.png
Θ0就是简单线性回归中的b

如上,可以封装成这种形式

"""Created by 杨帮杰 on 10/1/18Right to use this code in any way you want withoutwarranty, support or any guarantee of it workingE-mail: yangbangjie1998@qq.comAssociation: SCAU 华南农业大学"""import numpy as npclass LinearRegression:    def __init__(self):        """初始化Linear Regression模型"""        self.coef_ = None        self.interception_ = None        self._theta = None    def fit_normal(self, X_train, y_train):        """根据训练数据集X_train, y_train训练Linear Regression模型"""        assert X_train.shape[0] == y_train.shape[0], \            "the size of X_train must be equal to the size of y_train"        X_b = np.hstack([np.ones((len(X_train), 1)), X_train])        self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)        self.interception_ = self._theta[0]        self.coef_ = self._theta[1:]        return self    def predict(self, X_predict):        """给定待预测数据集X_predict, 返回表示X_predict的结果向量"""        assert self.interception_ is not None and self.coef_ is not None, \            "must fit before predict!"        assert X_predict.shape[1] == len(self.coef_), \            "the feature number of X_predict must be equal to X_train"        X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])        return X_b.dot(self._theta)    def __repr__(self):        return "LinearRegression()"

sciki-learn中使用线性回归如下

"""Created by 杨帮杰 on 10/1/18Right to use this code in any way you want withoutwarranty, support or any guarantee of it workingE-mail: yangbangjie1998@qq.comAssociation: SCAU 华南农业大学"""from sklearn import datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression# 加载波士顿房价的数据集boston = datasets.load_boston()# 清除一些不合理的数据X = boston.datay = boston.targetX = X[y < 50.0]y = y[y < 50.0]# 分离出测试集并拟合X_train, X_test, y_train, y_test = train_test_split(X, y)lin_reg = LinearRegression()lin_reg.fit(X_train, y_train)# 打印结果print(lin_reg.coef_)print(lin_reg.intercept_)print(lin_reg.score(X_test, y_test))

输出如下

img_479057ecfa5ede8287bcf0591264d891.png
打印结果

3.总结

线性回归是许多其他回归和分类问题的基础。

它最大的优点是对数据具有很强的解释性。比如某一项的参数是正数,那么很可能这个特征和样本标记之间成正相关,反之成负相关。

优点:

  1. 思想简单,实现容易
  2. 是许多非线性模型的基础
  3. 具有很好的可解释性

缺点:

  1. 假设特征和标记之间有线性关系,现实中不一定
  2. 训练的时间复杂度比较高

References:

机器学习实战 —— Peter Harrington

转载地址:http://ioxyl.baihongyu.com/

你可能感兴趣的文章
MS DOS 命令大全
查看>>
升级10.10 Yosemite 后,cocoapods 出现错误(解决方案)
查看>>
UEditor编辑器两个版本任意文件上传漏洞分析
查看>>
Redis分布式锁服务(八)
查看>>
MySQL的引入
查看>>
C++单例模式
查看>>
bower安装报错”Cannot be run with sudo”解决办法
查看>>
android平台中编写jni模块的方法(3)
查看>>
软件工程网络15结对编程1——四则运算优化
查看>>
进程、应用程序域,线程和上下文之间的关系
查看>>
Spring源码学习之一下载和导入
查看>>
13.使用第三方类实现动画
查看>>
H5在js中向指定的元素添加样式
查看>>
本地通知,UILocalNotification
查看>>
分页---总结
查看>>
前端开发的历史和趋势(转摘阮一峰)
查看>>
Ubuntu 削减非 LTS 支持周期
查看>>
_实用的cms企业后台管理模板
查看>>
菜鸟看Redis(一)
查看>>
matplotlib.pyplot.plot()参数详解
查看>>