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 ORM框架SQLAlchemy学习笔记之安装和简单查询实例
Jun 10 Python
python文件操作之目录遍历实例分析
May 20 Python
详解Python使用tensorflow入门指南
Feb 09 Python
Python实现打砖块小游戏代码实例
May 18 Python
python用requests实现http请求代码实例
Oct 31 Python
Python 实现递归法解决迷宫问题的示例代码
Jan 12 Python
Python datetime 格式化 明天,昨天实例
Mar 02 Python
解决pycharm下pyuic工具使用的问题
Apr 08 Python
Python检测端口IP字符串是否合法
Jun 05 Python
Django Session和Cookie分别实现记住用户登录状态操作
Jul 02 Python
详解Pymongo常用查询方法总结
Jan 29 Python
Python中的套接字编程是什么?
Jun 21 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使之能同时支持GIF和JPEG
2006/10/09 PHP
使用php+xslt在windows平台上
2006/10/09 PHP
apache rewrite_module模块使用教程
2008/01/10 PHP
yii2多图上传组件的使用教程
2018/05/10 PHP
laravel在中间件内生成参数并且传递到控制器中的2种姿势
2019/10/15 PHP
WordPress伪静态规则设置代码实例
2020/12/10 PHP
javascript showModalDialog模态对话框使用说明
2009/12/31 Javascript
JQuery,Extjs,YUI,Prototype,Dojo 等JS框架的区别和应用场景简述
2010/04/15 Javascript
js中匿名函数的N种写法
2010/09/08 Javascript
jquery中ajax学习笔记一
2011/10/16 Javascript
让复选框只能选择一项的方法
2013/10/08 Javascript
按下回车键指向下一个位置的一个函数代码
2014/03/10 Javascript
js中的cookie的读写操作示例详解
2014/04/17 Javascript
Bootstrap select实现下拉框多选效果
2016/12/23 Javascript
js实现带简单弹性运动的导航条
2017/02/22 Javascript
微信小程序返回箭头跳转到指定页面实例解析
2019/10/08 Javascript
[13:38]2015国际邀请赛中国战队出征仪式
2015/05/29 DOTA
[59:36]2018DOTA2亚洲邀请赛 4.3 突围赛 Secret vs VG 第二场
2018/04/04 DOTA
[06:45]2018DOTA2亚洲邀请赛 4.5 SOLO赛 Sccc vs Maybe
2018/04/06 DOTA
推荐下python/ironpython:从入门到精通
2007/10/02 Python
寻找网站后台地址的python脚本
2014/09/01 Python
跟老齐学Python之Import 模块
2014/10/13 Python
Python读取环境变量的方法和自定义类分享
2014/11/22 Python
详解Python3中的Sequence type的使用
2015/08/01 Python
Python Pandas数据结构简单介绍
2019/07/03 Python
flask 实现上传图片并缩放作为头像的例子
2020/01/09 Python
K最近邻算法(KNN)---sklearn+python实现方式
2020/02/24 Python
Python装饰器结合递归原理解析
2020/07/02 Python
matplotlib基础绘图命令之imshow的使用
2020/08/13 Python
15个Pythonic的代码示例(值得收藏)
2020/10/29 Python
马来西亚太阳镜、眼镜和隐形眼镜网上商店:Focus Point
2018/12/13 全球购物
开放系统互连参考模型
2016/06/29 面试题
酒店总经理岗位职责
2014/03/17 职场文书
护士求职自荐信范文
2015/03/04 职场文书
建立共青团委员会的请示
2019/04/02 职场文书
css布局巧妙技巧之css三角示例的运用
2022/03/16 HTML / CSS