⛳
PorkerHandデータセットでXGboost備忘録
目標
忘れかけているので、とりあえず動かすことを目的としています
XGboostとは
勾配ブーストを用いた決定木(GBDT)のアルゴリズムの一種。
論文はこちら
解説は以下のQiitaもわかりやすかったです。感謝
実践
データの用意
データセットはカレントディレクトリにある前提とします。
ダウンロード方法はこちらから
import pandas as pd
import io
train = pd.read_csv('./poker-hand-training-true.csv', header=None)
test = pd.read_csv('./poker-hand-testing.csv', header=None)
前処理
sklearnの前処理用のモジュールpreprocessing
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
train_Y = train[:][10]
test_Y = test[:][10]
X_train, X_test, = train_test_split(train,train_size=0.7)
Y_train,Y_test = train_test_split(train_Y,train_size=0.7)
print(X_train.shape,Y_train.shape,X_test.shape,Y_test.shape)
X_train.drop(10,axis=1,inplace=True)
X_test.drop(10,axis=1,inplace=True)
print(X_train.shape,Y_train.shape,X_test.shape,Y_test.shape)
(17507, 11) (17507,) (7503, 11) (7503,)
(17507, 10) (17507,) (7503, 10) (7503,)
検証データ取り出し
精度向上のためにfloatにしています
import numpy as np
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
Y_train = Y_train.astype('float32')
Y_test = Y_test.astype('float32')
X_train, X_val,= train_test_split(X_train,train_size=0.7)
Y_train, Y_val = train_test_split(Y_train,train_size=0.7)
print(X_train.shape,Y_train.shape,X_val.shape,Y_val.shape)
(12254, 10) (12254,) (5253, 10) (5253,)
モデル定義
import xgboost as xgb
from sklearn.model_selection import GridSearchCV
clf = xgb.XGBClassifier()
clf_cv = GridSearchCV(clf, {'max_depth': [2,4,6], 'n_estimators': [50,100,200]}, verbose=1)
パラメータ探索
学習前に、最適なパラメータを選定します
clf_cv.fit(X_train, Y_train,verbose=1)
学習
最適パラメータで学習を回します
clf = xgb.XGBClassifier(**clf_cv.best_params_)
clf.fit(X_train, Y_train,
early_stopping_rounds=100,
eval_set=[[X_val, Y_val]],
verbose=1)
モデルの評価
from sklearn.metrics import confusion_matrix,classification_report
pred = clf.predict(X_test)
print (confusion_matrix(Y_test, pred))
print (classification_report(Y_test, pred))
[[3729 10 0 0 0 0 0 0 0 0]
[3201 6 0 0 0 0 0 0 0 0]
[ 343 1 0 0 0 0 0 0 0 0]
[ 146 0 0 0 0 0 0 0 0 0]
[ 33 0 0 0 0 0 0 0 0 0]
[ 19 0 0 0 0 0 0 0 0 0]
[ 11 0 0 0 0 0 0 0 0 0]
[ 2 0 0 0 0 0 0 0 0 0]
[ 1 0 0 0 0 0 0 0 0 0]
[ 1 0 0 0 0 0 0 0 0 0]]
precision recall f1-score support
0.0 0.50 1.00 0.66 3739
1.0 0.35 0.00 0.00 3207
2.0 0.00 0.00 0.00 344
3.0 0.00 0.00 0.00 146
4.0 0.00 0.00 0.00 33
5.0 0.00 0.00 0.00 19
6.0 0.00 0.00 0.00 11
7.0 0.00 0.00 0.00 2
8.0 0.00 0.00 0.00 1
9.0 0.00 0.00 0.00 1
accuracy 0.50 7503
macro avg 0.09 0.10 0.07 7503
weighted avg 0.40 0.50 0.33 7503
まだまだですね。とりあえずXGBoost動かすのが目的だったので、アルゴリズム選定的にも適していない可能性もあります。
Discussion