9.22 XGBoost

oml.xgbクラスは、分類仕様、回帰仕様、ランク付けモデルおよび生存モデルのすべてについて、データベース内のスケーラブルな勾配ツリー・ブースティング・アルゴリズムをサポートしています。これによって、オープン・ソースの勾配ブースティング・フレームワークを利用できるようになります。これは、質的エンコーディングおよびOMLインフラストラクチャからの欠損値の置換を準備し、データベース内XGBoostをコールし、最上位クラスのデータベース・モデル・オブジェクトとしてモデルを構築および維持し、予測のためのモデルの使用をサポートします。

oml.xgbをスタンドアロンの予測子として使用することも、広告クリックスルー率の予測、ハザード・リスクの予測、Webテキスト分類といった幅広い問題に対処するために、実際の生産パイプラインに組み込むこともできます。

oml.xgbアルゴリズムでは、汎用パラメータ、ブースタ・パラメータおよびタスク・パラメータの3種類のパラメータを使用します。パラメータはモデル設定から設定します。このアルゴリズムでは、オープン・ソースXGBoostプロジェクトの設定のほとんどがサポートされています。サポートされている設定の詳細は、「XGBoost parameters」を参照してください。

oml.xgbを介して、OML4Pyでは様々な分類仕様、回帰仕様、ランク付けモデルおよび生存モデルがサポートされています。分類の機械学習手法では2項モデルと多クラス・モデルがサポートされており、回帰の機械学習手法では回帰、ランキング、カウントおよび生存がサポートされています。

また、oml.xgbでは、パーティション化されたモデルがサポートされており、データ準備が内部化されています。

XG Boost機能相互作用制約を使用すると、ユーザーはどの変数を相互作用できるか、できないかを指定できます。主要な相互作用に焦点を当て、ノイズを排除することで、予測パフォーマンスの向上に役立ちます。これによって、より一般化された予測になる可能性があります。XG Boost機能相互作用制約の詳細は、Oracle Machine Learning for SQLコンセプト・ガイドを参照してください。

XGBoostモデルの設定

次の表に、XGBoostモデルに適用される設定を示します。

表9-19 XGBoostモデルの設定

設定名 設定値 説明
xgboost_booster

次のいずれかの文字列:

  • dart
  • gblinear
  • gbtree

使用するブースタ:

  • dart
  • gblinear
  • gbtree

dartおよびgbtreeではツリー・ベースのモデルが使用され、gblinearでは線形ファンクションが使用されます。

デフォルト値はgbtreeです。

xgboost_num_round

負でない整数。

ブースティングの丸め数。

デフォルト値は10です。

xgboost_interaction_constraints

ノート:

Oracle Database 23aiでのみ使用できます。

[[x0,x1,x2],[x0,x4],[x5,x6]] (たとえば、xnは特徴名または列)

この設定では、モデル内で許可される相互作用を指定します。ネストされたリストの形式で制約を指定します。内側の各リストは、相互に作用できる特徴(列名)のグループです。相互作用で単一の列が渡された場合、入力は無視されます。

ここでは、特徴x0、x1およびx2は相互に作用できますが、他の特徴と相互に作用することはできません。同様に、x0とx4は相互に作用できるが、他の特徴と相互に作用することはできないというようになります。この設定は、2次元特徴に適用されます。サポートされていない型の列や存在しない特徴名を渡すと、エラーが発生します。

xgboost_decrease_constraints

ノート:

Oracle Database 23aiでのみ使用できます。

[x0,x1],[x4,x5]

この設定では、減少制約に従う必要がある特徴(列名)を指定します。特徴名はカンマで区切ります。たとえば、値'x4,x5'を設定すると、特徴x4およびx5に対して減少制約が設定されます。この設定は、数値列および2次元特徴に適用されます。サポートされていない型の列や存在しない特徴名を渡すと、エラーが発生します。

xgboost_increase_constraints

ノート:

Oracle Database 23aiでのみ使用できます。

[x0,x1],[x0,x3]

この設定では、増加制約に従う必要がある特徴(列名)を指定します。特徴名はカンマで区切ります。たとえば、値'x0,x3'を設定すると、特徴x0およびx3に対して増加制約が設定されます。この設定は、2次元特徴に適用されます。サポートされていない型の列や存在しない特徴名を渡すと、エラーが発生します。

objective

ノート:

Oracle Database 23aiでのみ使用できます。

分類モデルの場合、次のいずれかの文字列になります。

  • binary:hinge
  • binary:logistic
  • multi:softmax
  • multi:softprob

回帰モデルの場合、次のいずれかの文字列になります。

  • binary:logitraw
  • count:poisson
  • rank:map
  • rank:ndcg
  • rank:pairwise
  • reg:gamma
  • reg:logistic
  • reg:tweedie
  • survival:aft
  • survival:cox
  • reg:squarederror
  • reg:squaredlogerror

分類モデルの設定:

  • binary:hinge: 2項分類のヒンジ損失。この設定では、確率を生成するのではなく、0または1で予測が行われます。
  • binary:logistic: 2項分類のロジスティック回帰。出力は確率です。
  • multi:softmax: softmaxの目的を使用して多クラスの分類を実行します。また、num_class(number_of_classes)を設定する必要もあります。
  • multi:softprob: : softmaxと同じですが、出力は、ndata * nclassマトリックスにさらに形状変換できるndata * nclassのベクターです。結果には、各クラスに属する各データ・ポイントの予測確率が含まれます。

分類のデフォルト値objectivemulti:softprobです。

回帰モデルの設定:

  • binary:logitraw: バイナリ分類のロジスティック回帰。出力はロジスティック変換前のスコアです。
  • count:poisson: カウント・データのPoisson回帰。出力はPoisson分布の平均です。最適化を保護するために、デフォルトでは、Poisson回帰のmax_delta_step値は0.7に設定されます。
  • rank:map: LambdaMARTを使用して、平均精度(MAP)が最大化されるリスト単位のランキングを実行します。
  • rank:ndcg: LambdaMARTを使用して、正規化された割引累積利益(NDCG)が最大化されるリスト単位のランキングを実行します。
  • rank:pairwise: 組の損失を最小限に抑えてランキングを実行します。
  • reg:gamma: ログリンクを使用したガンマ回帰。出力はガンマ分布の平均です。この設定は、保険金請求の重大度のモデリングなど、ガンマ分布になる可能性のある結果に役立つ場合があります。
  • reg:logistic: ロジスティック回帰。
  • reg:tweedie: 対数リンクありのTweedie回帰。この設定は、保険における全損のモデリングなど、Tweedie分散される可能性のある結果に役立つ場合があります。
  • survival:aft: 打切り生存時間データに対してAccelerated Failure Time (AFT)モデルを適用します。このオプションを選択すると、eval_metricではデフォルト値としてaft-nloglikが使用されます。
  • survival:cox: 右側打切りの生存時間データのCox回帰(負の値は右側打切りとみなされます)。予測は、ハザード率スケールで(つまり、比例ハザード関数h(t) = h0(t) * HRHR = exp(marginal_prediction)として)返されます。
  • reg:squarederror: 二乗損失のある回帰。
  • reg:squaredlogerror: 二乗ログ損失のある回帰。すべての入力ラベルは-1より大きくする必要があります。

回帰のデフォルトのobjective値は、reg:squarederrorです。

xgboost_aft_loss_distribution

ノート:

Oracle Database 23aiでのみ使用できます。

[normal, logistic, extreme]

AFTモデルのZ項の分布を指定します。これは、survival:aft目的およびaft-nloglik評価メトリックで使用される確率密度ファンクションを指定します。デフォルト値はnormalです。

xgboost_aft_loss_distribution_scale

ノート:

Oracle Database 23aiでのみ使用できます。

正数

AFTモデルのZ項のサイズをスケーリングするスケーリング係数σを指定します。デフォルト値は1です。

xgboost_aft_right_bound_column_name

ノート:

Oracle Database 23aiでのみ使用できます。

column_name

AFTモデルのラベルの右境界を含む列を指定します。非AFTモデルについてこのパラメータを選択することはできません。

ノート:

Oracle Machine Learningは、この設定についてBOOLEAN値をサポートしていません。

ブースタ設定の詳細は、「XGBoost parameters」を参照してください

例9-21 oml.xgbクラスの使用

この例では、XGBモデルを作成し、oml.xgbクラスのメソッドの一部を使用します。

#Load the iris data from sklearn and combine the target and predictors into a single DataFrame, which matches the form of a database table.  
Use the oml.create function to load this Pandas DataFrame into the databae, which creates a persistent table and returns a proxy object that you assign to z.#

import oml
from sklearn import datasets
import pandas as pd

iris = datasets.load_iris()
x = pd.DataFrame(iris.data, columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width'])
y = pd.DataFrame(list(map(lambda x: {0: 'setosa', 1: 'versicolor', 2:'virginica'}[x], iris.target)), columns = ['Species'])

#For on-premises database follow the below command to connect to the database#
oml.connect("<username>","<password>", dsn="<dsn>")
z = oml.create(pd.concat([x, y], axis=1), table = 'IRIS')

#Create training data and test data.#

dat = oml.sync(table = "IRIS").split()
train_x = dat[0].drop('Species')
train_y = dat[0]['Species']
test_dat = dat[1]

#Classification Example:#

#Create an XGBoost model object.#

setting = {'xgboost_max_depth': '3',
...            'xgboost_eta': '1',
...            'xgboost_num_round': '10'}

xgb_mod = oml.xgb('classification', **setting)

#Fit the XGBoost model to the training data.#

xgb_mod.fit(train_x, train_y)  
#Use the model to make predictions on the test data and return the prediction probabilities for each category in Species.#
xgb_mod.predict(test_dat.drop('Species'), supplemental_cols = test_dat[:, ['Sepal_Length', 'Sepal_Width', 'Species']], proba = True).sort_values(by = ['Sepal_Length', 'Sepal_Width']) 
     Sepal_Length  Sepal_Width     Species       TOP_1  TOP_1_VAL
 0            4.4          3.0      setosa      setosa   0.993619
 1            4.4          3.2      setosa      setosa   0.993619
 2            4.5          2.3      setosa      setosa   0.942128
 3            4.8          3.4      setosa      setosa   0.993619
...           ...          ...         ...         ...        ...
 42           6.7          3.3   virginica   virginica   0.996170
 43           6.9          3.1  versicolor  versicolor   0.925217
 44           6.9          3.1   virginica   virginica   0.996170
 45           7.0          3.2  versicolor  versicolor   0.990586

#Create training data and test data.#

dat = oml.sync(table = "IRIS").split()

train_x = dat[0].drop('Sepal_Length')
train_y = dat[0]['Sepal_Length']
test_dat = dat[1]

#Create an XGBoost model object.#

setting = {'xgboost_booster': 'gblinear'}
xgb_mod = oml.xgb('regression', **setting)

#Fit the XGBoost Model according to the training data and parameter settings.#

xgb_mod.fit(train_x, train_y)  
xgb_mod.predict(test_dat.drop('Species'), supplemental_cols = test_dat[:, ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Species']]) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
#Create an XGBoost model object.#

setting = {'xgboost_objective': 'rank:pairwise',
...            'xgboost_max_depth': '3',
...            'xgboost_eta': '0.1',
...            'xgboost_gamma': '1.0',
...            'xgboost_num_round': '4'}

xgb_mod = oml.xgb('regression', **setting)

#Fit the XGBoost Model according to the training data and parameter settings.#

xgb_mod.fit(train_x, train_y)
#Use the model to make predictions on the test data, returning the Sepal_Length, Sepal_Width, Petal_Length, and Species columns in the result.#

xgb_mod.predict(test_dat.drop('Species'), supplemental_cols = test_dat[:, ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Species']]) 
 

この例のリスト

#Load the iris data from sklearn and combine the target and predictors into a single DataFrame, which matches the form of a database table.  
Use the oml.create function to load this Pandas DataFrame into the databae, which creates a persistent table and returns a proxy object that you assign to z.#

>>> import oml
>>> from sklearn import datasets
>>> import pandas as pd

>>> iris = datasets.load_iris()
>>> x = pd.DataFrame(iris.data, columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width'])
>>> y = pd.DataFrame(list(map(lambda x: {0: 'setosa', 1: 'versicolor', 2:'virginica'}[x], iris.target)), columns = ['Species'])

>>> #For on-premises database follow the below command to connect to the database#
>>> oml.connect("<username>","<password>", dsn="<dsn>")
>>> z = oml.create(pd.concat([x, y], axis=1), table = 'IRIS')

#Create training data and test data.#

>>> dat = oml.sync(table = "IRIS").split()
>>> train_x = dat[0].drop('Species')
>>> train_y = dat[0]['Species']
>>> test_dat = dat[1]

#Classification Example:#

#Create an XGBoost model object.#

>>> setting = {'xgboost_max_depth': '3',
...            'xgboost_eta': '1',
...            'xgboost_num_round': '10'}

>>> xgb_mod = oml.xgb('classification', **setting)

#Fit the XGBoost model to the training data.#

>>> xgb_mod.fit(train_x, train_y)  

Algorithm Name: XGBOOST
Mining Function: CLASSIFICATION
Target: Species

Settings: 
                    setting name            setting value
0                      ALGO_NAME             ALGO_XGBOOST
1          CLAS_WEIGHTS_BALANCED                      OFF
2                   ODMS_DETAILS              ODMS_ENABLE
3   ODMS_MISSING_VALUE_TREATMENT  ODMS_MISSING_VALUE_AUTO
4                  ODMS_SAMPLING    ODMS_SAMPLING_DISABLE
5                      PREP_AUTO                       ON
6                        booster                   gbtree
7                            eta                        1
8                      max_depth                        3
9                    ntree_limit                        0
10                     num_round                       10
11                     objective           multi:softprob

Global Statistics: 
  attribute name attribute value
0       NUM_ROWS             104
1       mlogloss        0.024858

Attributes: 
Petal_Length
Petal_Width
Sepal_Length
Sepal_Width

Partition: NO

ATTRIBUTE IMPORTANCE: 

  PNAME ATTRIBUTE_NAME ATTRIBUTE_SUBNAME ATTRIBUTE_VALUE      GAIN     COVER  \
0  None   Petal_Length              None            None  0.743941  0.560554   
1  None    Petal_Width              None            None  0.162191  0.245400   
2  None   Sepal_Length              None            None  0.003738  0.044741   
3  None    Sepal_Width              None            None  0.090129  0.149306   

   FREQUENCY  
0   0.447761  
1   0.268657  
2   0.119403  
3   0.164179  

#Use the model to make predictions on the test data and return the prediction probabilities for each category in Species.#

>>> xgb_mod.predict(test_dat.drop('Species'), supplemental_cols = test_dat[:, ['Sepal_Length', 'Sepal_Width', 'Species']], proba = True).sort_values(by = ['Sepal_Length', 'Sepal_Width']) 
     Sepal_Length  Sepal_Width     Species       TOP_1  TOP_1_VAL
 0            4.4          3.0      setosa      setosa   0.993619
 1            4.4          3.2      setosa      setosa   0.993619
 2            4.5          2.3      setosa      setosa   0.942128
 3            4.8          3.4      setosa      setosa   0.993619
...           ...          ...         ...         ...        ...
 42           6.7          3.3   virginica   virginica   0.996170
 43           6.9          3.1  versicolor  versicolor   0.925217
 44           6.9          3.1   virginica   virginica   0.996170
 45           7.0          3.2  versicolor  versicolor   0.990586


#Regression Example:#

#Create training data and test data.#

>>> dat = oml.sync(table = "IRIS").split()

>>> train_x = dat[0].drop('Sepal_Length')
>>> train_y = dat[0]['Sepal_Length']
>>> test_dat = dat[1]

#Create an XGBoost model object.#

>>> setting = {'xgboost_booster': 'gblinear'}
>>> xgb_mod = oml.xgb('regression', **setting)

#Fit the XGBoost Model according to the training data and parameter settings.#

>>> xgb_mod.fit(train_x, train_y)  

Algorithm Name: XGBOOST
Mining Function: REGRESSION
Target: Sepal_Length

Settings: 
                   setting name            setting value
0                     ALGO_NAME             ALGO_XGBOOST
1                  ODMS_DETAILS              ODMS_ENABLE
2  ODMS_MISSING_VALUE_TREATMENT  ODMS_MISSING_VALUE_AUTO
3                 ODMS_SAMPLING    ODMS_SAMPLING_DISABLE
4                     PREP_AUTO                       ON
5                       booster                 gblinear
6                   ntree_limit                        0
7                     num_round                       10

Computed Settings: 
              setting name setting value
0  ODMS_EXPLOSION_MIN_SUPP             1

Global Statistics: 
  attribute name attribute value
0       NUM_ROWS             104
1           rmse        0.364149

Attributes: 
Petal_Length
Petal_Width
Sepal_Width
Species

Partition: NO

ATTRIBUTE IMPORTANCE: 

  PNAME ATTRIBUTE_NAME ATTRIBUTE_SUBNAME ATTRIBUTE_VALUE    WEIGHT  CLASS
0  None   Petal_Length              None            None  0.335183      0
1  None    Petal_Width              None            None  0.368738      0
2  None    Sepal_Width              None            None  0.249208      0
3  None        Species              None      versicolor -0.197582      0
4  None        Species              None       virginica -0.170522      0

>>> xgb_mod.predict(test_dat.drop('Species'), supplemental_cols = test_dat[:, ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Species']]) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
     Sepal_Length  Sepal_Width  Petal_Length     Species  PREDICTION
 0            4.9          3.0           1.4      setosa    4.797075
 1            4.9          3.1           1.5      setosa    4.818641
 2            4.8          3.4           1.6      setosa    4.963796
 3            5.8          4.0           1.2      setosa    4.979247
...           ...          ...           ...         ...         ...
 42           6.7          3.3           5.7   virginica    6.990700
 43           6.7          3.0           5.2   virginica    6.674599
 44           6.5          3.0           5.2   virginica    6.563977
 45           5.9          3.0           5.1   virginica    6.456711
 

#Ranking Example:#

#Create an XGBoost model object.#

>>> setting = {'xgboost_objective': 'rank:pairwise',
...            'xgboost_max_depth': '3',
...            'xgboost_eta': '0.1',
...            'xgboost_gamma': '1.0',
...            'xgboost_num_round': '4'}

>>> xgb_mod = oml.xgb('regression', **setting)

#Fit the XGBoost Model according to the training data and parameter settings.#

>>> xgb_mod.fit(train_x, train_y) 
Algorithm Name: XGBOOST
Mining Function: REGRESSION
Target: Sepal_Length

Settings: 
                    setting name            setting value
0                      ALGO_NAME             ALGO_XGBOOST
1                   ODMS_DETAILS              ODMS_ENABLE
2   ODMS_MISSING_VALUE_TREATMENT  ODMS_MISSING_VALUE_AUTO
3                  ODMS_SAMPLING    ODMS_SAMPLING_DISABLE
4                      PREP_AUTO                       ON
5                        booster                   gbtree
6                            eta                      0.1
7                          gamma                      1.0
8                      max_depth                        3
9                    ntree_limit                        0
10                     num_round                        4
11                     objective            rank:pairwise

Computed Settings: 
              setting name setting value
0  ODMS_EXPLOSION_MIN_SUPP             1

Global Statistics: 
  attribute name  attribute value
0       NUM_ROWS              104
1            map                1

Attributes: 
Petal_Length
Petal_Width
Sepal_Width
Species

Partition: NO

ATTRIBUTE IMPORTANCE: 

  PNAME ATTRIBUTE_NAME ATTRIBUTE_SUBNAME ATTRIBUTE_VALUE      GAIN     COVER  \
0  None   Petal_Length              None            None  0.873855  0.677624   
1  None    Petal_Width              None            None  0.083504  0.184802   
2  None    Sepal_Width              None            None  0.042641  0.137574   

   FREQUENCY  
0   0.500000  
1   0.285714  
2   0.214286  

#Use the model to make predictions on the test data, returning the Sepal_Length, Sepal_Width, Petal_Length, and Species columns in the result.#

>>> xgb_mod.predict(test_dat.drop('Species'), supplemental_cols = test_dat[:, ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Species']]) 
     Sepal_Length  Sepal_Width  Petal_Length     Species  PREDICTION
 0            4.9          3.0           1.4      setosa    0.243485
 1            4.9          3.1           1.5      setosa    0.243485
 2            4.8          3.4           1.6      setosa    0.243485
 3            5.8          4.0           1.2      setosa    0.310980
...           ...          ...           ...         ...         ...
 42           6.7          3.3           5.7   virginica    0.771761
 43           6.7          3.0           5.2   virginica    0.728637
 44           6.5          3.0           5.2   virginica    0.728637
 45           5.9          3.0           5.1   virginica    0.674835