XGBoost:二分類問題
18243 ワード
にぶんかつもんだい
XGBoostのコマンドラインの使い方について説明します.PythonとRの使い方はhttps://github.com/dmlc/xgboost/blob/master/doc/README.md . XGBoostを用いて二分類問題を解決する方法について説明します.次のデータセットはmushroom datasetを参照してください.
概要
入力データの生成
XGBoostの入力データフォーマットはLibSVMと同じです.XGBoostで使用する入力データ形式は次のとおりです.
各行は1つのサンプルを表し、第1列の数字はカテゴリラベルを表し、サンプルが属するカテゴリを表し、「101」および「102」はフィーチャーインデックスを表し、「1.2」および「0.03」はフィーチャーに対応する値である.二分類では‘1’は正のクラスを表し,‘0’は負のクラスを表す.同時にカテゴリラベルは確率ラベルをサポートし、値取りサービスiは[0,1]であり、サンプルがあるカテゴリに属する可能性を示す.
最初のステップでは、データセットをlibSVM形式に変換し、次のスクリプトを実行します.
mapfeat.pyとmknfold.pyはそれぞれ以下の通りです
以上の2つのPythonスクリプトを実行すると、トレーニングデータセットが生成されます.txt.train'とテストデータセット:'agaricus.txt.test’
トレーニング
モデルトレーニングを完了するには、次のコマンドラインを実行します.
mushroom.confファイルは、トレーニングモデルとテストモデルを構成する際に必要な情報です.各行の構成情報フォーマットは、[attribute]=[value]:
ここでboosterはgbtree,ターゲット関数はlogistic regressionを用いる.これは古典的な勾配リフト回帰ツリーを用いて計算できることを意味する(GBRT).この方法は二分類問題をうまく処理できる.
以上のプロファイルでは、最も一般的な構成パラメータが示されています.詳細については、https://github.com/dmlc/xgboost/blob/master/doc/parameter.md.コンフィギュレーション・ファイルでアルゴリズム・パラメータを構成したくない場合は、コマンド・ラインで次のように構成できます.
これはmax_を表しますdepthパラメータは、プロファイルの3ではなく6に設定されます.コマンドラインパラメータを使用する場合はmax_を確認します.depth=6は、パラメータ間に間隔を含まないパラメータです.コンフィギュレーションとコマンドラインパラメータの両方を使用すると、コマンドラインパラメータはコンフィギュレーションファイルパラメータを上書きします.すなわち、コマンドラインパラメータを優先的に使用します.
以上の例ではtree boosterを用いて勾配リフトを計算した.linear boosterを使用して回帰計算を行う場合は、boosterパラメータをgblinearに変更できます.プロファイル内の他のパラメータは変更する必要はありません.プロファイル情報は次のとおりです.
予測
モデルを訓練した後、テストデータを予測し、次のスクリプトを実行できます.
二分類問題について予測した出力結果は[0,1]間の確率値であり,サンプルが正クラスに属する確率を表す.
モデルディスプレイ
現在は基本的な機能であり、ツリーモデルの展示のみをサポートしています.XGBoostでは、表示ツリーモデルをテキストで表示し、以下のスクリプトを実行できます.
0003.modelはdumpに出力.raw.txtとdump.nice.txtで.dump.nice.txtの結果は、フィーチャーマッピングファイルfeatmapが使用するため、より理解しやすい.txt
featmap.txtのフォーマットは Feature idは、0から特徴の個数まで、小さいものから大きいものまで配列されている. iは二分類特徴 であることを示す. qは、年齢、時間などの数値変数を表す.qデフォルト intは整数(when int is hinted,the decision boundary will be integer) を表す.
けいさんプロセスモニタリング
プログラムを実行すると、次の実行情報が出力されます.
計算中にモデル評価情報をエラー出力ストリームstderrに出力し、計算中のモデル評価情報を記録したい場合は、次のスクリプトを実行します.
ロゴtxtファイルには以下の情報が記録されている
訓練過程と試験過程の統計情報を同時にモニタリングすることもでき、以下のように構成することができる.
以上のスクリプトを実行して得られた情報は次のとおりです.
実行ルールは[name-printed-in-log]=filenameであり、filenameファイルは検出プロセスに追加され、各反復プロセスでモデルが評価されます.
XGBoostは同時に複数の統計量のモニタリングをサポートし、トレーニングプロセスで予測される平均log-likelihoodをモニタリングしたいと仮定し、プロファイルに構成情報
実行中のモデルの保存
実行中に2ステップごとにモデルを保存する場合は、パラメータset save_を設定できます.period=2..現在のフォルダには、モデル0002が表示する.model.モデル出力のパスを変更する場合は、パラメータdir=foldernameで変更できます.XGBoostはデフォルトで前回の反復の結果モデルを保持します.
既存のモデルから計算を続行
既存のモデルからトレーニングを継続する場合は、例えば0002.モデルは計算を続行し、次のコマンドラインを使用します.
XGBoostは0002をロードする.モデルは2回の反復計算を行い、出力をcontinueに明らかに保存する.model.注意しなければならないのはmushroomです.confで定義されたトレーニングデータや評価データ情報は変更できない.
マルチスレッドの使用
大きなデータセットを計算する場合は、並列計算が必要になる場合があります.コンパイラがOpenMPをサポートしている場合、XGBoostオリジナルはマルチスレッドをサポートしています.パラメータ
その他注意すべき点 デフォルトではXGBoostは、
XGBoostのコマンドラインの使い方について説明します.PythonとRの使い方はhttps://github.com/dmlc/xgboost/blob/master/doc/README.md . XGBoostを用いて二分類問題を解決する方法について説明します.次のデータセットはmushroom datasetを参照してください.
概要
入力データの生成
XGBoostの入力データフォーマットはLibSVMと同じです.XGBoostで使用する入力データ形式は次のとおりです.
1 101:1.2 102:0.03
0 1:2.1 10001:300 10002:400
...
各行は1つのサンプルを表し、第1列の数字はカテゴリラベルを表し、サンプルが属するカテゴリを表し、「101」および「102」はフィーチャーインデックスを表し、「1.2」および「0.03」はフィーチャーに対応する値である.二分類では‘1’は正のクラスを表し,‘0’は負のクラスを表す.同時にカテゴリラベルは確率ラベルをサポートし、値取りサービスiは[0,1]であり、サンプルがあるカテゴリに属する可能性を示す.
最初のステップでは、データセットをlibSVM形式に変換し、次のスクリプトを実行します.
python mapfeat.py
python mknfold.py agaricus.txt 1
mapfeat.pyとmknfold.pyはそれぞれ以下の通りです
#!/usr/bin/python
def loadfmap( fname ):
fmap = {}
nmap = {}
for l in open( fname ):
arr = l.split()
if arr[0].find('.') != -1:
idx = int( arr[0].strip('.') )
assert idx not in fmap
fmap[ idx ] = {}
ftype = arr[1].strip(':')
content = arr[2]
else:
content = arr[0]
for it in content.split(','):
if it.strip() == '':
continue
k , v = it.split('=')
fmap[ idx ][ v ] = len(nmap)
nmap[ len(nmap) ] = ftype+'='+k
return fmap, nmap
def write_nmap( fo, nmap ):
for i in range( len(nmap) ):
fo.write('%d\t%s\ti
' % (i, nmap[i]) )
# start here
fmap, nmap = loadfmap( 'agaricus-lepiota.fmap' )
fo = open( 'featmap.txt', 'w' )
write_nmap( fo, nmap )
fo.close()
fo = open( 'agaricus.txt', 'w' )
for l in open( 'agaricus-lepiota.data' ):
arr = l.split(',')
if arr[0] == 'p':
fo.write('1')
else:
assert arr[0] == 'e'
fo.write('0')
for i in range( 1,len(arr) ):
fo.write( ' %d:1' % fmap[i][arr[i].strip()] )
fo.write('
')
fo.close()
#!/usr/bin/python
import sys
import random
if len(sys.argv) < 2:
print ('Usage:<filename> <k> [nfold = 5]')
exit(0)
random.seed( 10 )
k = int( sys.argv[2] )
if len(sys.argv) > 3:
nfold = int( sys.argv[3] )
else:
nfold = 5
fi = open( sys.argv[1], 'r' )
ftr = open( sys.argv[1]+'.train', 'w' )
fte = open( sys.argv[1]+'.test', 'w' )
for l in fi:
if random.randint( 1 , nfold ) == k:
fte.write( l )
else:
ftr.write( l )
fi.close()
ftr.close()
fte.close()
以上の2つのPythonスクリプトを実行すると、トレーニングデータセットが生成されます.txt.train'とテストデータセット:'agaricus.txt.test’
トレーニング
モデルトレーニングを完了するには、次のコマンドラインを実行します.
xgboost mushroom.conf
mushroom.confファイルは、トレーニングモデルとテストモデルを構成する際に必要な情報です.各行の構成情報フォーマットは、[attribute]=[value]:
# General Parameters, see comment for each definition
# can be gbtree or gblinear
booster = gbtree
# choose logistic regression loss function for binary classification
objective = binary:logistic
# Tree Booster Parameters
# step size shrinkage
eta = 1.0
# minimum loss reduction required to make a further partition
gamma = 1.0
# minimum sum of instance weight(hessian) needed in a child
min_child_weight = 1
# maximum depth of a tree
max_depth = 3
# Task Parameters
# the number of round to do boosting
num_round = 2
# 0 means do not save any model except the final round model
save_period = 0
# The path of training data
data = "agaricus.txt.train"
# The path of validation data, used to monitor training process, here [test] sets name of the validation set
eval[test] = "agaricus.txt.test"
# The path of test data
test:data = "agaricus.txt.test"
ここでboosterはgbtree,ターゲット関数はlogistic regressionを用いる.これは古典的な勾配リフト回帰ツリーを用いて計算できることを意味する(GBRT).この方法は二分類問題をうまく処理できる.
以上のプロファイルでは、最も一般的な構成パラメータが示されています.詳細については、https://github.com/dmlc/xgboost/blob/master/doc/parameter.md.コンフィギュレーション・ファイルでアルゴリズム・パラメータを構成したくない場合は、コマンド・ラインで次のように構成できます.
xgboost mushroom.conf max_depth=6
これはmax_を表しますdepthパラメータは、プロファイルの3ではなく6に設定されます.コマンドラインパラメータを使用する場合はmax_を確認します.depth=6は、パラメータ間に間隔を含まないパラメータです.コンフィギュレーションとコマンドラインパラメータの両方を使用すると、コマンドラインパラメータはコンフィギュレーションファイルパラメータを上書きします.すなわち、コマンドラインパラメータを優先的に使用します.
以上の例ではtree boosterを用いて勾配リフトを計算した.linear boosterを使用して回帰計算を行う場合は、boosterパラメータをgblinearに変更できます.プロファイル内の他のパラメータは変更する必要はありません.プロファイル情報は次のとおりです.
# General Parameters
# choose the linear booster
booster = gblinear
...
# Change Tree Booster Parameters into Linear Booster Parameters
# L2 regularization term on weights, default 0
lambda = 0.01
# L1 regularization term on weights, default 0
f ```agaricus.txt.test.buffer``` exists, and automatically loads from binary buffer if possible, this can speedup training process when you do training many times. You can disable it by setting ```use_buffer=0```.
- Buffer file can also be used as standalone input, i.e if buffer file exists, but original agaricus.txt.test was removed, xgboost will still run
* Deviation from LibSVM input format: xgboost is compatible with LibSVM format, with the following minor differences:
- xgboost allows feature index starts from 0
- for binary classification, the label is 1 for positive, 0 for negative, instead of +1,-1
- the feature indices in each line *do not* need to be sorted
alpha = 0.01
# L2 regularization term on bias, default 0
lambda_bias = 0.01
# Regression Parameters
...
予測
モデルを訓練した後、テストデータを予測し、次のスクリプトを実行できます.
xgboost mushroom.conf task=pred model_in=0003.model
二分類問題について予測した出力結果は[0,1]間の確率値であり,サンプルが正クラスに属する確率を表す.
モデルディスプレイ
現在は基本的な機能であり、ツリーモデルの展示のみをサポートしています.XGBoostでは、表示ツリーモデルをテキストで表示し、以下のスクリプトを実行できます.
../../xgboost mushroom.conf task=dump model_in=0003.model name_dump=dump.raw.txt
../../xgboost mushroom.conf task=dump model_in=0003.model fmap=featmap.txt name_dump=dump.nice.txt
0003.modelはdumpに出力.raw.txtとdump.nice.txtで.dump.nice.txtの結果は、フィーチャーマッピングファイルfeatmapが使用するため、より理解しやすい.txt
featmap.txtのフォーマットは
featmap.txt: <featureid> <featurename> <q or i or int>
です.けいさんプロセスモニタリング
プログラムを実行すると、次の実行情報が出力されます.
tree train end, 1 roots, 12 extra nodes, 0 pruned nodes ,max_depth=3
[0] test-error:0.016139
boosting round 1, 0 sec elapsed
tree train end, 1 roots, 10 extra nodes, 0 pruned nodes ,max_depth=3
[1] test-error:0.000000
計算中にモデル評価情報をエラー出力ストリームstderrに出力し、計算中のモデル評価情報を記録したい場合は、次のスクリプトを実行します.
xgboost mushroom.conf 2>log.txt
ロゴtxtファイルには以下の情報が記録されている
[0] test-error:0.016139
[1] test-error:0.000000
訓練過程と試験過程の統計情報を同時にモニタリングすることもでき、以下のように構成することができる.
eval[test] = "agaricus.txt.test"
eval[trainname] = "agaricus.txt.train"
以上のスクリプトを実行して得られた情報は次のとおりです.
[0] test-error:0.016139 trainname-error:0.014433
[1] test-error:0.000000 trainname-error:0.001228
実行ルールは[name-printed-in-log]=filenameであり、filenameファイルは検出プロセスに追加され、各反復プロセスでモデルが評価されます.
XGBoostは同時に複数の統計量のモニタリングをサポートし、トレーニングプロセスで予測される平均log-likelihoodをモニタリングしたいと仮定し、プロファイルに構成情報
eval_metric=logloss
を追加するだけでよい.再度logファイルを実行すると、次の情報が表示されます.[0] test-error:0.016139 test-negllik:0.029795 trainname-error:0.014433 trainname-negllik:0.027023
[1] test-error:0.000000 test-negllik:0.000000 trainname-error:0.001228 trainname-negllik:0.002457
実行中のモデルの保存
実行中に2ステップごとにモデルを保存する場合は、パラメータset save_を設定できます.period=2..現在のフォルダには、モデル0002が表示する.model.モデル出力のパスを変更する場合は、パラメータdir=foldernameで変更できます.XGBoostはデフォルトで前回の反復の結果モデルを保持します.
既存のモデルから計算を続行
既存のモデルからトレーニングを継続する場合は、例えば0002.モデルは計算を続行し、次のコマンドラインを使用します.
xgboost mushroom.conf model_in=0002.model num_round=2 model_out=continue.model
XGBoostは0002をロードする.モデルは2回の反復計算を行い、出力をcontinueに明らかに保存する.model.注意しなければならないのはmushroomです.confで定義されたトレーニングデータや評価データ情報は変更できない.
マルチスレッドの使用
大きなデータセットを計算する場合は、並列計算が必要になる場合があります.コンパイラがOpenMPをサポートしている場合、XGBoostオリジナルはマルチスレッドをサポートしています.パラメータ
nthread=10
でスレッド数を10に設定します.その他注意すべき点
agaricus.txt.test.buffer
とagaricus.txt.train.buffer
はどんな書類ですか.buffer
という接尾辞を持つバイナリキャッシュファイルを生成します.次回XGBoostを再実行すると、元のファイルではなくキャッシュファイルがロードされます.