侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python机器学习库xgboost的使用

Python  /  管理员 发布于 7年前   318

1.数据读取

利用原生xgboost库读取libsvm数据

 import xgboost as xgb data = xgb.DMatrix(libsvm文件)

使用sklearn读取libsvm数据

 from sklearn.datasets import load_svmlight_file X_train,y_train = load_svmlight_file(libsvm文件)

使用pandas读取完数据后在转化为标准形式

2.模型训练过程

1.未调参基线模型

使用xgboost原生库进行训练

import xgboost as xgbfrom sklearn.metrics import accuracy_scoredtrain = xgb.DMatrix(f_train, label = l_train)dtest = xgb.DMatrix(f_test, label = l_test)param = {'max_depth':2, 'eta':1, 'silent':0, 'objective':'binary:logistic' }num_round = 2bst = xgb.train(param, dtrain, num_round)train_preds = bst.predict(dtrain)train_predictions = [round(value) for value in train_preds] #进行四舍五入的操作--变成0.1(算是设定阈值的符号函数)train_accuracy = accuracy_score(l_train, train_predictions) #使用sklearn进行比较正确率print ("Train Accuary: %.2f%%" % (train_accuracy * 100.0))from xgboost import plot_importance #显示特征重要性plot_importance(bst)#打印重要程度结果。pyplot.show()

使用XGBClassifier进行训练

# 未设定早停止, 未进行矩阵变换from xgboost import XGBClassifierfrom sklearn.datasets import load_svmlight_file #用于直接读取svmlight文件形式, 否则就需要使用xgboost.DMatrix(文件名)来读取这种格式的文件from sklearn.metrics import accuracy_scorefrom matplotlib import pyplotnum_round = 100bst1 =XGBClassifier(max_depth=2, learning_rate=1, n_estimators=num_round, #弱分类树太少的话取不到更多的特征重要性          silent=True, objective='binary:logistic')bst1.fit(f_train, l_train)train_preds = bst1.predict(f_train)train_accuracy = accuracy_score(l_train, train_preds)print ("Train Accuary: %.2f%%" % (train_accuracy * 100.0))preds = bst1.predict(f_test)test_accuracy = accuracy_score(l_test, preds)print("Test Accuracy: %.2f%%" % (test_accuracy * 100.0))from xgboost import plot_importance #显示特征重要性plot_importance(bst1)#打印重要程度结果。pyplot.show()

2.两种交叉验证方式

使用cross_val_score进行交叉验证

#利用model_selection进行交叉训练from xgboost import XGBClassifierfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.model_selection import cross_val_scorefrom sklearn.metrics import accuracy_scorefrom matplotlib import pyplotparam = {'max_depth':2, 'eta':1, 'silent':0, 'objective':'binary:logistic' }num_round = 100bst2 =XGBClassifier(max_depth=2, learning_rate=0.1,n_estimators=num_round, silent=True, objective='binary:logistic')bst2.fit(f_train, l_train)kfold = StratifiedKFold(n_splits=10, random_state=7)results = cross_val_score(bst2, f_train, l_train, cv=kfold)#对数据进行十折交叉验证--9份训练,一份测试print(results)print("CV Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))from xgboost import plot_importance #显示特征重要性plot_importance(bst2)#打印重要程度结果。pyplot.show()

 

使用GridSearchCV进行网格搜索

#使用sklearn中提供的网格搜索进行测试--找出最好参数,并作为默认训练参数from xgboost import XGBClassifierfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import accuracy_scorefrom matplotlib import pyplotparams = {'max_depth':2, 'eta':0.1, 'silent':0, 'objective':'binary:logistic' }bst =XGBClassifier(max_depth=2, learning_rate=0.1, silent=True, objective='binary:logistic')param_test = { 'n_estimators': range(1, 51, 1)}clf = GridSearchCV(estimator = bst, param_grid = param_test, scoring='accuracy', cv=5)# 5折交叉验证clf.fit(f_train, l_train) #默认使用最优的参数preds = clf.predict(f_test)test_accuracy = accuracy_score(l_test, preds)print("Test Accuracy of gridsearchcv: %.2f%%" % (test_accuracy * 100.0))clf.cv_results_, clf.best_params_, clf.best_score_ 

3.早停止调参Cearly_stopping_rounds(查看的是损失是否变化)

#进行提早停止的单独实例import xgboost as xgbfrom xgboost import XGBClassifierfrom sklearn.metrics import accuracy_scorefrom matplotlib import pyplotparam = {'max_depth':2, 'eta':1, 'silent':0, 'objective':'binary:logistic' }num_round = 100bst =XGBClassifier(max_depth=2, learning_rate=0.1, n_estimators=num_round, silent=True, objective='binary:logistic')eval_set =[(f_test, l_test)]bst.fit(f_train, l_train, early_stopping_rounds=10, eval_metric="error",eval_set=eval_set, verbose=True) #early_stopping_rounds--当多少次的效果差不多时停止  eval_set--用于显示损失率的数据 verbose--显示错误率的变化过程# make predictionpreds = bst.predict(f_test)test_accuracy = accuracy_score(l_test, preds)print("Test Accuracy: %.2f%%" % (test_accuracy * 100.0))

4.多数据观察训练损失

#多参数顺import xgboost as xgbfrom xgboost import XGBClassifierfrom sklearn.metrics import accuracy_scorefrom matplotlib import pyplotnum_round = 100bst =XGBClassifier(max_depth=2, learning_rate=0.1, n_estimators=num_round, silent=True, objective='binary:logistic')eval_set = [(f_train, l_train), (f_test, l_test)]bst.fit(f_train, l_train, eval_metric=["error", "logloss"], eval_set=eval_set, verbose=True)# make predictionpreds = bst.predict(f_test)test_accuracy = accuracy_score(l_test, preds)print("Test Accuracy: %.2f%%" % (test_accuracy * 100.0))

5.模型保存与读取

#模型保存bst.save_model('demo.model')#模型读取与预测modelfile = 'demo.model'# 1bst = xgb.Booster({'nthread':8}, model_file = modelfile)# 2f_test1 = xgb.DMatrix(f_test) #尽量使用xgboost的自己的数据矩阵ypred1 = bst.predict(f_test1)train_predictions = [round(value) for value in ypred1]test_accuracy1 = accuracy_score(l_test, train_predictions)print("Test Accuracy: %.2f%%" % (test_accuracy1 * 100.0))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    python爬取本站电子书信息并入库的实现代码
    下一条:
    使用Go语言简单模拟Python的生成器
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客