#机器学习模型选择与参数调优

#三种集成学习算法-GBDT/XGBoost/lightGBM

#1-1 GBDT算法:梯度决策树,加强型模型,构建多个决策树进行合并

import numpy as np

import matplotlib.pyplot as plt

from sklearn import ensemble

from sklearn import datasets

from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_squared_error

'''

#导入数据集

bost=datasets.load_boston()

x,y=bost.data,bost.target

x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=666)

#构建模型

params={"n_estimators":800,"max_depth":4,"min_samples_split":2,"learning_rate":0.01,"loss":"ls"}

clf=ensemble.GradientBoostingRegressor(**params)

clf.fit(x_train,y_train)

y_pre=clf.predict(x_test)

mse=mean_squared_error(y_test,y_pre)

print("MSE:",mse)

#绘制测试误差-每一次所输出的迭代误差

test_score=np.zeros((params["n_estimators"],),dtype=np.float64)

for i ,y_pre in enumerate(clf.staged_predict(x_test)):

test_score[i]=clf.loss_(y_test,y_pre)

plt.figure(figsize=(12,6))

plt.subplot(1,2,1)

plt.title("Deviance")

plt.plot(np.arange(params["n_estimators"])+1,clf.train_score_,"b-",label="Training set deviance")

plt.plot(np.arange(params["n_estimators"])+1,test_score,"r-",label="Test set deviance")

plt.legend(loc="upper right")

plt.xlabel("Boostng Iterations")

plt.ylabel("Deviance")

#绘制特征重要性图

feature_importance=clf.feature_importances_

feature_importance=100.0*(feature_importance/feature_importance.max())

sort_index=np.argsort(feature_importance)

pos=np.arange(sort_index.shape[0])+0.5

plt.subplot(1,2,2)

plt.barh(pos,feature_importance[sort_index],align="center")

plt.yticks(pos,bost.feature_names[sort_index])

plt.xlabel("Relative Importance")

plt.title("Veriable Importance")

plt.show()

#1-2 XGboost扩展的GBDT

import xgboost as xgb

data=np.random.rand(100000,10)

label=np.random.randint(2,size=100000)

dtrain=xgb.DMatrix(data,label=label,missing=-999.0)

data2=np.random.rand(5000,10)

label2=np.random.randint(2,size=5000)

dtest=xgb.DMatrix(data2,label=label2,missing=-999.0)

params={"bst:max_depth":2,"bst:eta":1,"silent":1,"objective":"binary:logistic"}

params["nthread"]=4

params["eval_metric"]="auc"

evallist=[(dtrain,"train"),(dtest,"eval")] #监控效果

num_round=10 #训练迭代的次数

bst=xgb.train(params,dtrain,num_round,evallist)

#设置一种早停,输出最好的效果

bst=xgb.train(params,dtrain,num_round,evallist,early_stopping_rounds=10)

#1-3 lightGBM 轻量级梯度提升机

import lightgbm as lgb

data=np.random.rand(100000,10)

label=np.random.randint(2,size=100000)

train=lgb.Dataset(data,label=label)

data2=np.random.rand(5000,10)

label2=np.random.randint(2,size=5000)

test=lgb.Dataset(data2,label=label2)

params={"num_leaves":31,"num_trees":100,"objective":"binary","metrics":"binary_error"}

num_round=10 #10论训练

bst=lgb.train(params,train,num_round,valid_sets=[test])

#交叉验证

num_round=10

params={"num_leaves":50,"num_trees":100,"objective":"binary"}

print(lgb.cv(params,train,num_round,nfold=5))

bst=lgb.train(params,train,20,valid_sets=test,early_stopping_rounds=10)

'''

#招聘数据的实际项目需要

#2-1 GBDT算法进行训练和预测

import pandas as pd

import numpy as np

df=pd.read_csv("D:\Byrbt2018\Study\Python机器学习全流程项目实战精讲\配套课件\第七讲 机器学习建模\lagou_featured.csv",encoding="gbk")

print(df.shape)

pd.options.display.max_columns=999 #设置最大的展示列数为999

print(df.head())

#首先对salary的目标回归变量进行直方图展示

import matplotlib.pyplot as plt

plt.hist(df["salary"])

plt.show()

#将表格数据转化为目标向量和训练特征矩阵

x=df.drop(["salary"],axis=1).values

y=df["salary"].values.reshape(-1,1)

print(x.shape,y.shape)

from sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=666)

print(x_train.shape,x_test.shape,y_train.shape,y_test.shape)

from sklearn.ensemble import GradientBoostingRegressor

clf=GradientBoostingRegressor(n_estimators=100,max_depth=5)

clf.fit(x_train,y_train)

from sklearn.metrics import mean_squared_error,max_error,mean_absolute_error

y_pre=clf.predict(x_test)

print(np.sqrt(mean_squared_error(y_test,y_pre)))

print(np.sqrt(mean_squared_error(y_test,y_pre)))

print(np.sqrt(mean_absolute_error(y_test,y_pre)))

print(np.sqrt(max_error(y_test,y_pre)))

print(clf.score(x_test,y_test))

plt.plot(y_pre)

plt.plot(y_test)

plt.legend(["y_pre","y_test"])

plt.show()

#对目标回归变量进行对数化处理,消除有偏数据的影响

from sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test=train_test_split(x,np.log(y),random_state=666)

print(x_train.shape,x_test.shape,y_train.shape,y_test.shape)

from sklearn.ensemble import GradientBoostingRegressor

clf=GradientBoostingRegressor(n_estimators=100,max_depth=5)

clf.fit(x_train,y_train)

from sklearn.metrics import mean_squared_error,max_error,mean_absolute_error

y_pre=clf.predict(x_test)

print(np.sqrt(mean_squared_error(np.exp(y_test),np.exp(y_pre))))

print(np.sqrt(mean_absolute_error(np.exp(y_test),np.exp(y_pre))))

print(np.sqrt(max_error(np.exp(y_test),np.exp(y_pre))))

print(clf.score(x_test,y_test))

print()

plt.plot(np.exp(y_pre))

plt.plot(np.exp(y_test))

plt.legend(["y_pre","y_test"])

plt.show()

#2-2 XGBoost模型训练和预测

from sklearn.model_selection import KFold #五划分的交叉验证的方式模块

import xgboost as xgb

from sklearn.metrics import mean_squared_error

import time

kf=KFold(n_splits=5,random_state=123,shuffle=True)

def evalereor(pre,train):

labels=train.getlabel()

return "mse",mean_squared_error(np.exp(pre),np.exp(labels))

y=np.log(y)

valid_pre=np.zeros((330,5))

time_start=time.time()

for i,(train_ind,valid_ind) in enumerate(kf.split(x)):

print("FOLD",i+1,"out of",5)

x_train,y_train=x[train_ind],y[train_ind]

x_valid,y_valid=x[valid_ind],y[valid_ind]

xgb_params={"eta":0.01,"max_depth":6,"subsample":0.9,"colsample_bytree":0.9,"objective":"reg:linear","seed":99,"eval_metgric":"rmse","silent":True}

d_train=xgb.DMatrix(x_train,y_train)

d_valid=xgb.DMatrix(x_valid,y_valid)

watchlist=[(d_train,"train"),(d_valid,"valid")] #监控效果

model=xgb.train(

xgb_params,

d_train,

2000,

watchlist,

verbose_eval=100,

#feval=evalereor,

early_stopping_rounds=1000

)

# valid_pre[:,i]=np.exp(model.predict(d_valid))

print("cv training time{} second".format(time.time()-time_start))

#网格搜索的方式

import xgboost as xgb

xg_train=xgb.DMatrix(x,y)

params={"eta": 0.01, "max_depth": 6, "subsample": 0.9, "colsample_bytree": 0.9, "objective": "reg:linear",

"seed": 99, "eval_metgric": "rmse", "silent": True}

cv=xgb.cv(params,xg_train,1000,nfold=5,early_stopping_rounds=800,verbose_eval=100)

print(cv)

#2-3 lightGBM算法模型

import time

import lightgbm as lgb

from sklearn.model_selection import KFold

from sklearn.metrics import mean_squared_error

from lightgbm import LGBMRegressor

x=df.drop(["salary"],axis=1).values

y=df["salary"].values

y=np.log(y)

def evalerror(pre,train):

labels=train.getlabel()

return "mse",mean_squared_error(np.exp(pre),np.exp(labels))

params={

"learning_rate":0.01,

"boosting_type":"gbdt",

"objective": "regression",

"metric":"mse",

"sub_feature":0.7,

"num_leaves":17,

"colsample_bytree":0.7,

"feature_fraction":0.7,

"min_data":100,

"min_hessian":1,

"verbose":-1

}

print("begin cv 5-fold training...")

scores=[]

time_start=time.time()

kf=KFold(n_splits=5,shuffle=True,random_state=27)

for i,(train_ind,valid_ind) in enumerate(kf.split(x)):

print("FOLD",i+1,"out of",5)

x_train,y_train=x[train_ind],y[train_ind]

x_valid,y_valid=x[valid_ind],y[valid_ind]

d_train=lgb.Dataset(x_train,y_train)

d_valid=lgb.Dataset(x_valid,y_valid)

model=lgb.train(

params,

d_train,

num_boost_round=2000,

valid_sets=d_valid,

verbose_eval=200,

#feval=evalerror(),

early_stopping_rounds=1000)

#valid_pre[:,i]=np.exp(model.predict(d_valid))

print("cv training time{} second".format(time.time()-time_start))

python回归模型调优要运行多久_python机器学习模型参数调优相关推荐

  1. [机器学习] XGBoost参数调优完全指南(附Python代码)

    1. 简介 如果你的预测模型表现得有些不尽如人意,那就用XGBoost吧.XGBoost算法现在已经成为很多数据工程师的重要武器.它是一种十分精致的算法,可以处理各种不规则的数据. 构造一个使用XGB ...

  2. 【超参数寻优】遗传算法(GA) 超参数寻优的python实现

    [超参数寻优]遗传算法(GA) 超参数寻优的python实现 一.遗传算法简介 1.遗传算法由来 2.遗传算法名词概念 3.遗传算法中对染色体的操作 3.1.选择 3.2.交叉 3.3.变异 二.遗传 ...

  3. 机器学习——超参数调优

    超参数是在开始学习过程之前设置值的参数,而不是通过训练得到的参数数据.超参数可以分为两种类型:定义模型及结构本身的参数,目标函数与与优化算法所需的参数,前者用于训练和预测阶段,后者用于训练阶段. 在实 ...

  4. 调参方法论:如何提高机器学习模型的性能?

    在机器学习的实践中,除了知道有哪些算法和背后原理之外,我们还需要知道如何针对具体应用挑选一个合适的算法以及如何监控,并根据实验反馈改进机器学习系统. 在机器学习系统的日常开发中,实践者需要决定是否收集 ...

  5. python语句print(chr(65))的运行结果_Python语句print(hello 'world')的执行结果是

    [填空题]Python的标准随机数生成器模块是 [简答题]Why does critical thinking matter? [简答题]采集瓶子的外形进行创意设计 用点.线.面进行装饰填充 A4纸手 ...

  6. 机器学习 对模型进行惩罚_使用Streamlit对机器学习模型进行原型制作

    机器学习 对模型进行惩罚 GitHub Repo: ml-streamlit-demo GitHub存储库: ml-streamlit-demo Bringing a Machine Learning ...

  7. python鸡兔同笼编程运行结果_Python少儿编程:鸡兔同笼

    Python少儿编程:解决鸡兔同笼问题 一笼鸡和兔子,我们数了一下,咳咳,鸡和兔子的头一共有35个,但是鸡和兔子的脚一共有94只. 好的,那么吃货们我们来好好算一算,到底能做几只德州扒鸡和双流兔头呢? ...

  8. python鸡兔同笼编程运行结果_Python解决鸡兔同笼问题的方法

    本文实例讲述了Python解决鸡兔同笼问题的方法,分享给大家供大家参考.具体分析如下: 问题描述 一个笼子里面关了鸡和兔子(鸡有 2 只脚,兔子有 4 只脚,没有例外).已经知道了笼 子里面脚的总数 ...

  9. python计算圆周率100万位要多久_python圆周率计算小程序(非常慢)

    源码: 1 from math import fabs #导入数学模块 2 3 from time import perf_counter #导入时间模块 4 5 from numba import ...

  10. python进行回归分析与检验_Python机器学习模型-线性回归模型相关检验

    假设检验: 模型显著性检验--F检验(利用statsmodels中建立模型的summary/summary2方法) 偏回归系数显著性检验--t检验(利用statsmodels中建立模型的summary ...

最新文章

  1. 专访阿里云MVP王俊杰:开发者的超能力是用技术让世界更美好
  2. Java中List高效去重
  3. Hadoop集群部署模型纵览1
  4. linux java setting,setting java_home and path environmental variables in linux [duplicate]
  5. 2013中国微信公众平台用户研究报告
  6. 实验板FPGA型号在哪里看_项目分享| 自制FPGA最小系统板(PCB可直接打板)
  7. iOS 一种很方便的构造TarBar
  8. 机器学习数学知识第一期复习指南
  9. java myqq ui_GitHub - 744184755/myqq: Java版SWing“高”仿QQ即时通聊天系统
  10. BeautifulSoup抓取门户网站上的链接
  11. 李智慧-我的全栈之路导师之一
  12. 关于centos7重启报错:[sdb] Assuming drive cache: write through [sda] Assuming drive 解决如下
  13. [EndNote]EndNote在Word中的工具条消失了怎么办?-知乎转载
  14. 如何将SNS光纤交换机(OEM博科FC交换机)恢复为出厂设置
  15. Reso | php面试题(基础概念)
  16. 计算机学院新生教育讲话,吴兴隆在数计学院2017级新生开学典礼上的讲话
  17. C语言求毕达哥拉斯亲密数
  18. 把英文翻译成中文php,中文翻译成英文,英文翻译成中文(调用的有道翻译的api)示例源码...
  19. Java中Person类型赋值_Java设计:定义一个Person类和它的子类Employee。Person类有姓名、地址、电话号码和电子邮箱,...
  20. 给准备第一次参加西雅图峰会的MVP们:签证篇(B1签证)

热门文章

  1. 计算机二级不看教材只刷题可以吗,中级会计可以只看轻松过关不看教材吗
  2. cpu顶盖怎么看步进_硬核科普丨什么是CPU步进?B0步进和U0步进具体差别有哪些...
  3. WPS Office宏病毒实现shell反弹
  4. Discuz模板的制作方法
  5. c语言----斐波那契数列
  6. 上海联影医疗公司软件开发工程师面试经历
  7. echarts中国地图根据数据对省份渲染不同的颜色
  8. 自相关函数与互相关函数
  9. Blender快捷键大全
  10. R语言绘图基础篇-线图