Python使用sklearn实现的各种回归算法示例


Posted in Python onJuly 04, 2019

本文实例讲述了Python使用sklearn实现的各种回归算法。分享给大家供大家参考,具体如下:

使用sklearn做各种回归

基本回归:线性、决策树、SVM、KNN

集成方法:随机森林、Adaboost、GradientBoosting、Bagging、ExtraTrees

1. 数据准备

为了实验用,我自己写了一个二元函数,y=0.5*np.sin(x1)+ 0.5*np.cos(x2)+0.1*x1+3。其中x1的取值范围是0~50,x2的取值范围是-10~10,x1和x2的训练集一共有500个,测试集有100个。其中,在训练集的上加了一个-0.5~0.5的噪声。生成函数的代码如下:

def f(x1, x2):
  y = 0.5 * np.sin(x1) + 0.5 * np.cos(x2) + 0.1 * x1 + 3
  return y
def load_data():
  x1_train = np.linspace(0,50,500)
  x2_train = np.linspace(-10,10,500)
  data_train = np.array([[x1,x2,f(x1,x2) + (np.random.random(1)-0.5)] for x1,x2 in zip(x1_train, x2_train)])
  x1_test = np.linspace(0,50,100)+ 0.5 * np.random.random(100)
  x2_test = np.linspace(-10,10,100) + 0.02 * np.random.random(100)
  data_test = np.array([[x1,x2,f(x1,x2)] for x1,x2 in zip(x1_test, x2_test)])
  return data_train, data_test

其中训练集(y上加有-0.5~0.5的随机噪声)和测试集(没有噪声)的图像如下:

Python使用sklearn实现的各种回归算法示例

2. scikit-learn的简单使用

scikit-learn非常简单,只需实例化一个算法对象,然后调用fit()函数就可以了,fit之后,就可以使用predict()函数来预测了,然后可以使用score()函数来评估预测值和真实值的差异,函数返回一个得分。

完整程式化代码为:

import numpy as np
import matplotlib.pyplot as plt
###########1.数据生成部分##########
def f(x1, x2):
  y = 0.5 * np.sin(x1) + 0.5 * np.cos(x2) + 3 + 0.1 * x1
  return y
def load_data():
  x1_train = np.linspace(0,50,500)
  x2_train = np.linspace(-10,10,500)
  data_train = np.array([[x1,x2,f(x1,x2) + (np.random.random(1)-0.5)] for x1,x2 in zip(x1_train, x2_train)])
  x1_test = np.linspace(0,50,100)+ 0.5 * np.random.random(100)
  x2_test = np.linspace(-10,10,100) + 0.02 * np.random.random(100)
  data_test = np.array([[x1,x2,f(x1,x2)] for x1,x2 in zip(x1_test, x2_test)])
  return data_train, data_test
train, test = load_data()
x_train, y_train = train[:,:2], train[:,2] #数据前两列是x1,x2 第三列是y,这里的y有随机噪声
x_test ,y_test = test[:,:2], test[:,2] # 同上,不过这里的y没有噪声
###########2.回归部分##########
def try_different_method(model):
  model.fit(x_train,y_train)
  score = model.score(x_test, y_test)
  result = model.predict(x_test)
  plt.figure()
  plt.plot(np.arange(len(result)), y_test,'go-',label='true value')
  plt.plot(np.arange(len(result)),result,'ro-',label='predict value')
  plt.title('score: %f'%score)
  plt.legend()
  plt.show()
###########3.具体方法选择##########
####3.1决策树回归####
from sklearn import tree
model_DecisionTreeRegressor = tree.DecisionTreeRegressor()
####3.2线性回归####
from sklearn import linear_model
model_LinearRegression = linear_model.LinearRegression()
####3.3SVM回归####
from sklearn import svm
model_SVR = svm.SVR()
####3.4KNN回归####
from sklearn import neighbors
model_KNeighborsRegressor = neighbors.KNeighborsRegressor()
####3.5随机森林回归####
from sklearn import ensemble
model_RandomForestRegressor = ensemble.RandomForestRegressor(n_estimators=20)#这里使用20个决策树
####3.6Adaboost回归####
from sklearn import ensemble
model_AdaBoostRegressor = ensemble.AdaBoostRegressor(n_estimators=50)#这里使用50个决策树
####3.7GBRT回归####
from sklearn import ensemble
model_GradientBoostingRegressor = ensemble.GradientBoostingRegressor(n_estimators=100)#这里使用100个决策树
####3.8Bagging回归####
from sklearn.ensemble import BaggingRegressor
model_BaggingRegressor = BaggingRegressor()
####3.9ExtraTree极端随机树回归####
from sklearn.tree import ExtraTreeRegressor
model_ExtraTreeRegressor = ExtraTreeRegressor()
###########4.具体方法调用部分##########
try_different_method(model_DecisionTreeRegressor)

3.结果展示

决策树回归结果:
Python使用sklearn实现的各种回归算法示例

线性回归结果:
Python使用sklearn实现的各种回归算法示例

SVM回归结果:
Python使用sklearn实现的各种回归算法示例

KNN回归结果:
Python使用sklearn实现的各种回归算法示例

随机森林回归结果:
Python使用sklearn实现的各种回归算法示例

Adaboost回归结果:
Python使用sklearn实现的各种回归算法示例

GBRT回归结果:
Python使用sklearn实现的各种回归算法示例

Bagging回归结果:
Python使用sklearn实现的各种回归算法示例

极端随机树回归结果:
Python使用sklearn实现的各种回归算法示例

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python实现登录接口的示例代码
Jul 21 Python
python不换行之end=与逗号的意思及用途
Nov 21 Python
Python中elasticsearch插入和更新数据的实现方法
Apr 01 Python
pandas多级分组实现排序的方法
Apr 20 Python
python matlibplot绘制3D图形
Jul 02 Python
查看python下OpenCV版本的方法
Aug 03 Python
python scp 批量同步文件的实现方法
Jan 03 Python
解决django 新增加用户信息出现错误的问题
Jul 28 Python
python os.path.isfile 的使用误区详解
Nov 29 Python
利用Python实现Excel的文件间的数据匹配功能
Jun 16 Python
基于Python 的语音重采样函数解析
Jul 06 Python
详解python定时简单爬取网页新闻存入数据库并发送邮件
Nov 27 Python
python SQLAlchemy的Mapping与Declarative详解
Jul 04 #Python
pandas分区间,算频率的实例
Jul 04 #Python
Django中信号signals的简单使用方法
Jul 04 #Python
python3读取图片并灰度化图片的四种方法(OpenCV、PIL.Image、TensorFlow方法)总结
Jul 04 #Python
pybind11和numpy进行交互的方法
Jul 04 #Python
pandas计算最大连续间隔的方法
Jul 04 #Python
python SQLAlchemy 中的Engine详解
Jul 04 #Python
You might like
php数组中删除元素的实现代码
2012/06/22 PHP
单点登录 Ucenter示例分析
2013/10/29 PHP
CodeIgniter框架验证码类库文件与用法示例
2017/03/18 PHP
PHP实现在windows下配置sendmail并通过mail()函数发送邮件的方法
2017/06/20 PHP
PHP在同一域名下两个不同的项目做独立登录机制详解
2017/09/22 PHP
laravel 5.4 + vue + vux + element的环境搭配过程介绍
2018/04/26 PHP
由prototype_1.3.1进入javascript殿堂-类的初探
2006/11/06 Javascript
jquery简单体验
2007/01/10 Javascript
Javascript 表单之间的数据传递代码
2008/12/04 Javascript
向大师们学习Javascript(视频与PPT)
2009/12/27 Javascript
元素的内联事件处理函数的特殊作用域在各浏览器中存在差异
2011/01/12 Javascript
jquery提取元素里的纯文本不包含span等里的内容
2013/09/30 Javascript
js用typeof方法判断undefined类型
2014/07/15 Javascript
js实现下拉框选择要显示图片的方法
2015/02/16 Javascript
jQuery实现鼠标划过修改样式的方法
2015/04/14 Javascript
举例详解JavaScript中Promise的使用
2015/06/24 Javascript
跟我学习JScript的Bug与内存管理
2015/11/18 Javascript
JS模态窗口返回值兼容问题的完美解决方法
2016/05/28 Javascript
轻松5句话解决JavaScript的作用域
2016/07/15 Javascript
vue-router 权限控制的示例代码
2017/09/21 Javascript
JS实现字符串中去除指定子字符串方法分析
2018/05/17 Javascript
vue-cli3配置与跨域处理方法
2019/08/17 Javascript
vue之a-table中实现清空选中的数据
2019/11/07 Javascript
初学Python函数的笔记整理
2015/04/07 Python
Python中用Decorator来简化元编程的教程
2015/04/13 Python
Python检测QQ在线状态的方法
2015/05/09 Python
python读取目录下最新的文件夹方法
2018/12/24 Python
python实现高斯(Gauss)迭代法的例子
2019/11/20 Python
Python操作MongoDb数据库流程详解
2020/03/05 Python
记录一下scrapy中settings的一些配置小结
2020/09/28 Python
人事科岗位职责范本
2014/03/02 职场文书
中国梦读书活动总结
2014/07/10 职场文书
办公室文员工作自我鉴定
2014/09/19 职场文书
学习走群众路线心得体会
2014/11/05 职场文书
《弟子规》读后感:知廉耻、明是非、懂荣辱、辨善恶
2019/12/03 职场文书
一篇文章弄懂Python中的内建函数
2021/08/07 Python