python机器学习库xgboost的使用
更新时间:2020年4月22日 23:19 点击:1398
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 xgb from sklearn.metrics import accuracy_score dtrain = 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 = 2 bst = 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 XGBClassifier from sklearn.datasets import load_svmlight_file #用于直接读取svmlight文件形式, 否则就需要使用xgboost.DMatrix(文件名)来读取这种格式的文件 from sklearn.metrics import accuracy_score from matplotlib import pyplot num_round = 100 bst1 =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 XGBClassifier from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import cross_val_score from sklearn.metrics import accuracy_score from matplotlib import pyplot param = {'max_depth':2, 'eta':1, 'silent':0, 'objective':'binary:logistic' } num_round = 100 bst2 =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 XGBClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import accuracy_score from matplotlib import pyplot params = {'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.早停止调参–early_stopping_rounds(查看的是损失是否变化)
#进行提早停止的单独实例 import xgboost as xgb from xgboost import XGBClassifier from sklearn.metrics import accuracy_score from matplotlib import pyplot param = {'max_depth':2, 'eta':1, 'silent':0, 'objective':'binary:logistic' } num_round = 100 bst =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 prediction preds = bst.predict(f_test) test_accuracy = accuracy_score(l_test, preds) print("Test Accuracy: %.2f%%" % (test_accuracy * 100.0))
4.多数据观察训练损失
#多参数顺 import xgboost as xgb from xgboost import XGBClassifier from sklearn.metrics import accuracy_score from matplotlib import pyplot num_round = 100 bst =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 prediction preds = 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' # 1 bst = xgb.Booster({'nthread':8}, model_file = modelfile) # 2 f_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-opencv-画外接矩形框的实例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
Python astype(np.float)函数使用方法解析
这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08- 2022虎年新年即将来临,小编为大家带来了一个利用Python编写的虎年烟花特效,堪称全网最绚烂,文中的示例代码简洁易懂,感兴趣的同学可以动手试一试...2022-02-14
- 在本篇文章里小编给大家分享的是一篇关于python中numpy.empty()函数实例讲解内容,对此有兴趣的朋友们可以学习下。...2021-02-06
python-for x in range的用法(注意要点、细节)
这篇文章主要介绍了python-for x in range的用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-05-10- 这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
- 这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
- 这篇文章主要介绍了python如何实现b站直播自动发送弹幕,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...2021-02-20
python Matplotlib基础--如何添加文本和标注
这篇文章主要介绍了python Matplotlib基础--如何添加文本和标注,帮助大家更好的利用Matplotlib绘制图表,感兴趣的朋友可以了解下...2021-01-26- 这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
- 今天小编就为大家分享一篇python 计算方位角实例(根据两点的坐标计算),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
- 这篇文章主要为大家详细介绍了python实现双色球随机选号,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-05-02
- 在本篇文章里小编给大家整理的是一篇关于python中使用np.delete()的实例方法,对此有兴趣的朋友们可以学习参考下。...2021-02-01
- 这篇文章主要介绍了使用Python的pencolor函数实现渐变色功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-09
- 这篇文章主要介绍了python自动化办公操作PPT的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-05
Python getsizeof()和getsize()区分详解
这篇文章主要介绍了Python getsizeof()和getsize()区分详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-20- 这篇文章主要为大家详细介绍了python实现学生通讯录管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-25
- 这篇文章主要介绍了PyTorch一小时掌握之迁移学习篇,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-08
- 这篇文章主要介绍了解决python 两个时间戳相减出现结果错误的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-12
- 这篇文章主要介绍了Python绘制的爱心树与表白代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-04-06