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函数式编程
Jun 09 Python
Python创建日历实例
Aug 21 Python
Python中List.index()方法的使用教程
May 20 Python
python黑魔法之编码转换
Jan 25 Python
python生成圆形图片的方法
Mar 25 Python
Python使用pickle模块报错EOFError Ran out of input的解决方法
Aug 16 Python
Python中作用域的深入讲解
Dec 10 Python
Python3爬虫学习之应对网站反爬虫机制的方法分析
Dec 12 Python
Python中函数的返回值示例浅析
Aug 28 Python
浅谈PyQt5中异步刷新UI和Python多线程总结
Dec 13 Python
如何利用pygame实现简单的五子棋游戏
Dec 29 Python
如何通过python实现IOU计算代码实例
Nov 02 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
简单的过滤字符串中的HTML标记
2006/12/25 PHP
PHP实现的CURL非阻塞调用类
2018/07/26 PHP
js实现的仿新浪微博完美的时间组件升级版
2011/12/20 Javascript
js导出格式化的excel 实例方法
2013/07/17 Javascript
jQuery中ajax的post()方法用法实例
2014/12/26 Javascript
jQuery实现3D文字特效的方法
2015/03/10 Javascript
JavaScript中定义函数的三种方法
2015/03/12 Javascript
JavaScript闭包实例详解
2016/06/03 Javascript
vue.js与后台数据交互的实例讲解
2018/08/08 Javascript
一个因@click.stop引发的bug的解决
2019/01/08 Javascript
layui对工具条进行选择性的显示方法
2019/09/19 Javascript
vue中 数字相加为字串转化为数值的例子
2019/11/07 Javascript
vue页面跳转实现页面缓存操作
2020/07/22 Javascript
Vue页面手动刷新,实现导航栏激活项还原到初始状态
2020/08/06 Javascript
Python 深入理解yield
2008/09/06 Python
Python接收Gmail新邮件并发送到gtalk的方法
2015/03/10 Python
python实现搜索指定目录下文件及文件内搜索指定关键词的方法
2015/06/28 Python
分析并输出Python代码依赖的库的实现代码
2015/08/09 Python
Python编程中字符串和列表的基本知识讲解
2015/10/14 Python
在Python的一段程序中如何使用多次事件循环详解
2017/09/07 Python
Python装饰器知识点补充
2018/05/28 Python
解决pandas中读取中文名称的csv文件报错的问题
2018/07/04 Python
Python3爬虫学习入门教程
2018/12/11 Python
Django model update的多种用法介绍
2020/03/28 Python
Python使用requests xpath 并开启多线程爬取西刺代理ip实例
2020/03/06 Python
python能自学吗
2020/06/18 Python
python实现测试工具(二)——简单的ui测试工具
2020/10/19 Python
2013的个人自我评价
2013/12/26 职场文书
预备党员思想汇报
2014/01/08 职场文书
爱护公共设施倡议书
2014/08/29 职场文书
交通工程专业推荐信
2014/09/06 职场文书
领导班子整改方案和个人整改措施
2014/10/25 职场文书
2015学校六五普法工作总结
2015/04/22 职场文书
2015年度个人教学工作总结
2015/05/20 职场文书
地道战观后感500字
2015/06/04 职场文书
2016年教师节感言
2015/12/09 职场文书