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()

python机器学习库xgboost的使用 

使用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))

python机器学习库xgboost的使用

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,xgboost,python机器学习库xgboost

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

评论“python机器学习库xgboost的使用”

暂无“python机器学习库xgboost的使用”评论...

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。