跳至主要內容

    XGBoost:表格資料的重要基準模型

    從二階資訊、葉權重與切分增益,到一次保留測試集的實跑

    sunny 桑尼· · 34 MIN READ · 153 次瀏覽

    XGBoost:表格資料的重要基準模型
    本文目錄

    學會Boosting之後,XGBoost就不必再從縮寫背起。它仍然逐輪加入樹、修正目前預測,但把損失、葉分數與樹複雜度放進一個可計算的目標,也加入有效率的工程實作。

    它值得列入表格資料的基準比較,不代表每份表格都一定由它勝出。這篇先拆開葉權重與切分增益,再實跑一個合成迴歸範例,清楚保留訓練、驗證與測試三份資料。

    每棵樹輸出分數,多棵樹把分數加起來

    圖1|來源用假想遊戲興趣示意:輸入依age等條件走向葉,每個葉有+2或−1等數值。這些分數不是調查結果,也不是直接可解讀的百分比。來源:DMLC/XGBoost developers,Introduction to Boosted Trees,Apache License 2.0,原圖未改。

    XGBoost的樹可以把每個輸入送到一個葉,取出該葉的數值。多棵樹加總後,再依任務解讀:迴歸可以直接是數值,二元logistic分類則把原始分數經轉換得到機率型輸出。

    圖2|來源兩樹示意有2+0.9=2.9與−1−0.9=−1.9;這裡畫的是分數相加,不是兩棵樹的硬類別多數決。來源同圖1,原圖未改。

    訓練時,固定目前已學好的部分,再找下一棵樹。這和Random Forest各樹相對獨立訓練後聚合的流程不同。

    目標不只看擬合,還要考慮樹的複雜度

    先寫一個常見的概念目標:

    總目標 = 資料損失 + 各樹的複雜度懲罰
    
    Ω(一棵樹) = γT + ½λΣⱼwⱼ²
    T:葉數
    wⱼ:第j葉的分數
    γ、λ ≥ 0
    

    這是為了推導而使用的L2葉權重版本;實際工具也有L1等其他限制。γ讓新增葉需要付出代價,λ限制葉分數幅度。它們和最大深度、每葉條件等參數一起影響模型,不是只要加正則化就完成泛化檢查。

    圖3|來源左上是待擬合資料,其他圖示意切分太多、位置不合適與較平衡的階梯。它沒有報告獨立測試成效,紅色也不是所有資料都應套用的最佳結構。來源同圖1,原圖未改。

    二階資訊:不只知道往哪裡走

    對目前每筆預測Fᵢ,計算損失的一階導數gᵢ與二階導數hᵢ。新樹對該筆輸出的修正記為f(xᵢ),對光滑損失做二階近似:

    gᵢ = ∂L(yᵢ,Fᵢ)/∂Fᵢ
    hᵢ = ∂²L(yᵢ,Fᵢ)/∂Fᵢ²
    
    本輪相關部分 ≈ Σᵢ[gᵢf(xᵢ) + ½hᵢf(xᵢ)²] + Ω(f)
    

    g提供方向,h描述局部曲率。不是要對整棵樹的離散拓撲直接求一般梯度,而是用這些統計量評估葉分數與候選結構。

    例如單筆½平方誤差,gᵢ=Fᵢ−yᵢ、hᵢ=1;二元log loss以原始分數作變數時,gᵢ=pᵢ−yᵢ、hᵢ=pᵢ(1−pᵢ)。不同損失的尺度與條件不能隨意混用;自訂目標也需要符合工具與最佳化的要求,不是所有任意函數都能保證這個近似好用。

    把同一葉的g、h加總,就能算葉分數

    落在第j葉的樣本集合為Iⱼ,定義:

    Gⱼ = Σᵢ∈Iⱼ gᵢ
    Hⱼ = Σᵢ∈Iⱼ hᵢ
    

    同一葉的樣本都得到相同修正wⱼ,因此該葉的二次式為:

    Gⱼwⱼ + ½(Hⱼ+λ)wⱼ²
    

    在Hⱼ+λ>0的條件下,對wⱼ微分令其為0:

    wⱼ* = −Gⱼ / (Hⱼ+λ)
    

    若一葉整體預測太低,平方誤差的G往往為負,得到正修正;若整體太高,G為正,得到負修正。λ增加則對修正幅度施加更強限制。

    圖4|採原圖的樣本索引/g、h清單,以及上方分組路由與部分葉統計;右側區域重新置中。原完整圖底式漏½、第二葉H下標不一致,本篇裁去那些下方區域,精確公式以正文為準。這棵示意樹切age<15,和圖1–2的age<20不同,並非同一棵樹的連續訓練快照。來源同圖1,依Apache 2.0作上述裁切編排。

    把最佳葉分數代回去,固定結構時的近似目標為:

    Obj* = −½Σⱼ Gⱼ²/(Hⱼ+λ) + γT
    

    這裡省略了不影響本輪比較的常數。它不是測試誤差,也不是可以直接跨任意損失尺度比較的品質分數。

    一次切分值不值得:手算Gain

    把一葉分成左、右兩葉,考慮增加一個葉的代價,可定義淨增益:

    Net Gain = ½[G左²/(H左+λ) + G右²/(H右+λ)
                 − (G左+G右)²/(H左+H右+λ)] − γ
    

    這個定義已經扣除γ;不能再拿它和γ比較而重扣一次。忽略其他限制時,淨增益為正,才表示這個候選比不切有利;實作仍會考慮深度、子葉條件與搜尋方式。

    用三筆自訂梯度統計作教學:g=[−2,−1,3]、h=[1,1,1]。候選把前兩筆分左、最後一筆分右,取λ=1、γ=0.1。

    區域GH最佳w
    不切的父葉030
    左葉−321
    右葉31−1.5
    Net Gain = ½[9/3 + 9/2 − 0/4] − 0.1 = 3.65
    父葉Obj* = 0.1
    分兩葉Obj* = −3.55
    改善 = 0.1 − (−3.55) = 3.65
    

    這是固定候選的局部二階目標比較,不代表找到全資料、整棵樹或最後模型的全域最佳解。若另用learning_rate=0.3縮小新樹,實際加入的左、右修正為0.3與−0.45;不能把縮小後的數值仍稱作剛才未縮小二次式的精確最小點。

    圖5|來源示意沿一個特徵排序,移動候選切點,更新G左與G右;並非枚舉所有樹結構。實際切分也需H及正則化等資訊,不能只看哪邊G較大。來源同圖1,原圖未改。

    這就是精確掃候選切點的基本想法。現代工具還有hist等建樹方式,把數值分箱以減少搜尋成本;它的候選集合與近似方式也要納入理解,不是每個設定都逐一檢查每個原始值。

    常見參數,放回它正在控制的位置

    參數主要作用與判斷

    n_estimators/boosting rounds
    允許加多少輪;early stopping可用驗證指標決定較合適階段
    learning_rate
    縮小每輪貢獻,應和輪數一起看
    max_depth
    限制單棵樹的深度與交互表達能力
    min_child_weight
    限制子節點所需的Hessian和;一般不能直接當最少筆數
    gamma/min_split_loss
    要求切分帶來足夠的改善;留意使用的Gain是否已扣代價
    reg_lambda/reg_alpha
    分別對葉分數施加L2/L1限制,本文推導只展開L2版本
    subsample/colsample_bytree
    樣本/每樹特徵的抽樣,影響變異、偏差與成本
    tree_method
    建樹策略;本文實跑固定hist,不宣稱所有策略結果相同

    沒有一組通用最佳參數。先保留簡單基準,再在適合部署情境的切分上比較;特徵洩漏、資料時間錯位與目標定義錯誤,不能靠更細的參數搜尋修好。

    用Python重算葉權重與淨增益

    以下是標準函式庫即可核對的固定三筆梯度例,沒有擬合完整模型:

    gradients = [-2.0, -1.0, 3.0]
    hessians = [1.0, 1.0, 1.0]
    lam, gamma = 1.0, 0.1
    G_left, H_left = sum(gradients[:2]), sum(hessians[:2])
    G_right, H_right = sum(gradients[2:]), sum(hessians[2:])
    G_parent, H_parent = sum(gradients), sum(hessians)
    w_left = -G_left / (H_left + lam)
    w_right = -G_right / (H_right + lam)
    parent_obj = -0.5 * G_parent ** 2 / (H_parent + lam) + gamma
    split_obj = -0.5 * (G_left ** 2 / (H_left + lam)
                        + G_right ** 2 / (H_right + lam)) + 2 * gamma
    print("leaf weights:", w_left, w_right)
    print("parent/split objectives:", round(parent_obj, 6), round(split_obj, 6))
    print("net gain:", round(parent_obj - split_obj, 6))
    

    會得到1、−1.5與淨增益3.65,和前表一致。原圖有教學式子的簡化或瑕疵時,能自己重算,比只對照截圖更可靠。

    實跑一次:驗證集負責early stopping,測試集留到最後

    以下使用WSL Linux、Python 3.10.12、NumPy 1.26.3、scikit-learn 1.5.1、XGBoost 2.1.0實測。這是本文的重現版本,不宣稱是最新套件;在Python 3.10環境安裝:

    python -m pip install "numpy==1.26.3" "scikit-learn==1.5.1" "xgboost==2.1.0"
    

    make_friedman1產生1,000筆、10個數值特徵的合成非線性迴歸資料,noise=1。先保留200筆測試,再把其餘資料切成600筆訓練、200筆驗證。參數事前固定,沒有用測試結果反覆調整。

    import numpy as np
    import xgboost as xgb
    from sklearn.datasets import make_friedman1
    from sklearn.dummy import DummyRegressor
    from sklearn.metrics import mean_squared_error
    from sklearn.model_selection import train_test_split
    
    X, y = make_friedman1(n_samples=1000, n_features=10, noise=1.0, random_state=42)
    X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    X_train, X_valid, y_train, y_valid = train_test_split(
        X_dev, y_dev, test_size=0.25, random_state=42)
    model = xgb.XGBRegressor(
        objective="reg:squarederror", n_estimators=1000, max_depth=3,
        learning_rate=0.05, subsample=0.8, colsample_bytree=0.8,
        reg_lambda=1.0, tree_method="hist", eval_metric="rmse",
        early_stopping_rounds=20, random_state=42, n_jobs=1)
    model.fit(X_train, y_train, eval_set=[(X_valid, y_valid)], verbose=False)
    baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
    rmse = lambda actual, predicted: float(np.sqrt(mean_squared_error(actual, predicted)))
    print("xgboost:", xgb.__version__)
    print("train/valid/test:", len(y_train), len(y_valid), len(y_test))
    print("best round (1-based):", model.best_iteration + 1)
    print("stored rounds:", model.get_booster().num_boosted_rounds())
    print("validation RMSE:", round(rmse(y_valid, model.predict(X_valid)), 6))
    print("test RMSE:", round(rmse(y_test, model.predict(X_test)), 6))
    print("constant baseline test RMSE:", round(rmse(y_test, baseline.predict(X_test)), 6))
    

    本環境實際結果:

    項目本次實測

    訓練/驗證/測試筆數
    600/200/200
    驗證選中的最佳輪次(從1起算)
    348
    訓練後保存的總輪數
    368
    驗證RMSE
    1.487436
    最終測試RMSE
    1.382690
    固定平均值基準的測試RMSE
    4.707488

    最佳輪次之後,還需連續20輪沒有更好的驗證指標才停止,因此保存總輪數與最佳輪次不同。在這個實測版本的sklearn介面,predict會自動使用best_iteration對應的範圍;不要把原生Booster與其他介面的預測行為一概視為相同。

    驗證集已經用來選擇停止點,不是最後一次獨立驗收。測試比驗證的RMSE低,也不表示模型跨資料變好了;兩批樣本本來不同。這個合成例只和固定均值基準比較,沒有證明XGBoost優於其他樹模型、神經網路或所有線性方法。

    如果要進一步搜尋參數,請按公平比較與交叉驗證安排開發資料;涉及時間或群組時,先讓切分符合部署情境。early stopping依據的資料已參與選擇,不能把它改名test就當作未使用。

    從能跑到值得用,還差哪些判斷

    XGBoost把梯度統計、局部結構搜尋與系統效率結合起來,但表格是否有訊號、目標是否清楚、錯誤成本是否合理,仍然由任務決定。對類別欄位、缺失、新類別與稀疏資料的支援,也要按具體版本及資料表示檢查,不把「樹模型」當成不用前處理的通行證。

    先能解釋某次切分為何值得,再能用保留資料證明它對任務有幫助,才是這一篇希望建立的基準。下一篇會比較LightGBM與CatBoost在效率與類別特徵上的不同選擇。

    來源與圖片授權

    本站新增三筆梯度推導核算,以及XGBoost 2.1.0在合成資料的600/200/200實跑。五張來源圖的原始完整訓練實驗未由本站重跑。

    • XGBoost developers:Introduction to Boosted Trees,作逐輪加樹、二階近似與葉分數推導依據。正文保留½與γ的完整定義,不沿用原頁已扣γ後再次比較γ的不一致敘述。
    • sklearn estimator interface:early stopping與預測範圍概念;程式與結果以本文實際2.1.0環境核對。
    • 五張圖實檔來自DMLC web-data的xgboost/model目錄,其實際圖檔repository以Apache License 2.0公開,未見本目錄另有圖片授權例外或NOTICE。圖片署名DMLC/XGBoost developers;圖4的裁切/編排已在圖說披露,其餘原圖未改。未暗示作者對本站內容背書。

    以下保留隨圖再發布的完整Apache License 2.0副本;與圖4修改說明共同提供。

    Apache License
                               Version 2.0, January 2004
                            http://www.apache.org/licenses/
    
       TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    
       1. Definitions.
    
          "License" shall mean the terms and conditions for use, reproduction,
          and distribution as defined by Sections 1 through 9 of this document.
    
          "Licensor" shall mean the copyright owner or entity authorized by
          the copyright owner that is granting the License.
    
          "Legal Entity" shall mean the union of the acting entity and all
          other entities that control, are controlled by, or are under common
          control with that entity. For the purposes of this definition,
          "control" means (i) the power, direct or indirect, to cause the
          direction or management of such entity, whether by contract or
          otherwise, or (ii) ownership of fifty percent (50%) or more of the
          outstanding shares, or (iii) beneficial ownership of such entity.
    
          "You" (or "Your") shall mean an individual or Legal Entity
          exercising permissions granted by this License.
    
          "Source" form shall mean the preferred form for making modifications,
          including but not limited to software source code, documentation
          source, and configuration files.
    
          "Object" form shall mean any form resulting from mechanical
          transformation or translation of a Source form, including but
          not limited to compiled object code, generated documentation,
          and conversions to other media types.
    
          "Work" shall mean the work of authorship, whether in Source or
          Object form, made available under the License, as indicated by a
          copyright notice that is included in or attached to the work
          (an example is provided in the Appendix below).
    
          "Derivative Works" shall mean any work, whether in Source or Object
          form, that is based on (or derived from) the Work and for which the
          editorial revisions, annotations, elaborations, or other modifications
          represent, as a whole, an original work of authorship. For the purposes
          of this License, Derivative Works shall not include works that remain
          separable from, or merely link (or bind by name) to the interfaces of,
          the Work and Derivative Works thereof.
    
          "Contribution" shall mean any work of authorship, including
          the original version of the Work and any modifications or additions
          to that Work or Derivative Works thereof, that is intentionally
          submitted to Licensor for inclusion in the Work by the copyright owner
          or by an individual or Legal Entity authorized to submit on behalf of
          the copyright owner. For the purposes of this definition, "submitted"
          means any form of electronic, verbal, or written communication sent
          to the Licensor or its representatives, including but not limited to
          communication on electronic mailing lists, source code control systems,
          and issue tracking systems that are managed by, or on behalf of, the
          Licensor for the purpose of discussing and improving the Work, but
          excluding communication that is conspicuously marked or otherwise
          designated in writing by the copyright owner as "Not a Contribution."
    
          "Contributor" shall mean Licensor and any individual or Legal Entity
          on behalf of whom a Contribution has been received by Licensor and
          subsequently incorporated within the Work.
    
       2. Grant of Copyright License. Subject to the terms and conditions of
          this License, each Contributor hereby grants to You a perpetual,
          worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          copyright license to reproduce, prepare Derivative Works of,
          publicly display, publicly perform, sublicense, and distribute the
          Work and such Derivative Works in Source or Object form.
    
       3. Grant of Patent License. Subject to the terms and conditions of
          this License, each Contributor hereby grants to You a perpetual,
          worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          (except as stated in this section) patent license to make, have made,
          use, offer to sell, sell, import, and otherwise transfer the Work,
          where such license applies only to those patent claims licensable
          by such Contributor that are necessarily infringed by their
          Contribution(s) alone or by combination of their Contribution(s)
          with the Work to which such Contribution(s) was submitted. If You
          institute patent litigation against any entity (including a
          cross-claim or counterclaim in a lawsuit) alleging that the Work
          or a Contribution incorporated within the Work constitutes direct
          or contributory patent infringement, then any patent licenses
          granted to You under this License for that Work shall terminate
          as of the date such litigation is filed.
    
       4. Redistribution. You may reproduce and distribute copies of the
          Work or Derivative Works thereof in any medium, with or without
          modifications, and in Source or Object form, provided that You
          meet the following conditions:
    
          (a) You must give any other recipients of the Work or
              Derivative Works a copy of this License; and
    
          (b) You must cause any modified files to carry prominent notices
              stating that You changed the files; and
    
          (c) You must retain, in the Source form of any Derivative Works
              that You distribute, all copyright, patent, trademark, and
              attribution notices from the Source form of the Work,
              excluding those notices that do not pertain to any part of
              the Derivative Works; and
    
          (d) If the Work includes a "NOTICE" text file as part of its
              distribution, then any Derivative Works that You distribute must
              include a readable copy of the attribution notices contained
              within such NOTICE file, excluding those notices that do not
              pertain to any part of the Derivative Works, in at least one
              of the following places: within a NOTICE text file distributed
              as part of the Derivative Works; within the Source form or
              documentation, if provided along with the Derivative Works; or,
              within a display generated by the Derivative Works, if and
              wherever such third-party notices normally appear. The contents
              of the NOTICE file are for informational purposes only and
              do not modify the License. You may add Your own attribution
              notices within Derivative Works that You distribute, alongside
              or as an addendum to the NOTICE text from the Work, provided
              that such additional attribution notices cannot be construed
              as modifying the License.
    
          You may add Your own copyright statement to Your modifications and
          may provide additional or different license terms and conditions
          for use, reproduction, or distribution of Your modifications, or
          for any such Derivative Works as a whole, provided Your use,
          reproduction, and distribution of the Work otherwise complies with
          the conditions stated in this License.
    
       5. Submission of Contributions. Unless You explicitly state otherwise,
          any Contribution intentionally submitted for inclusion in the Work
          by You to the Licensor shall be under the terms and conditions of
          this License, without any additional terms or conditions.
          Notwithstanding the above, nothing herein shall supersede or modify
          the terms of any separate license agreement you may have executed
          with Licensor regarding such Contributions.
    
       6. Trademarks. This License does not grant permission to use the trade
          names, trademarks, service marks, or product names of the Licensor,
          except as required for reasonable and customary use in describing the
          origin of the Work and reproducing the content of the NOTICE file.
    
       7. Disclaimer of Warranty. Unless required by applicable law or
          agreed to in writing, Licensor provides the Work (and each
          Contributor provides its Contributions) on an "AS IS" BASIS,
          WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          implied, including, without limitation, any warranties or conditions
          of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          PARTICULAR PURPOSE. You are solely responsible for determining the
          appropriateness of using or redistributing the Work and assume any
          risks associated with Your exercise of permissions under this License.
    
       8. Limitation of Liability. In no event and under no legal theory,
          whether in tort (including negligence), contract, or otherwise,
          unless required by applicable law (such as deliberate and grossly
          negligent acts) or agreed to in writing, shall any Contributor be
          liable to You for damages, including any direct, indirect, special,
          incidental, or consequential damages of any character arising as a
          result of this License or out of the use or inability to use the
          Work (including but not limited to damages for loss of goodwill,
          work stoppage, computer failure or malfunction, or any and all
          other commercial damages or losses), even if such Contributor
          has been advised of the possibility of such damages.
    
       9. Accepting Warranty or Additional Liability. While redistributing
          the Work or Derivative Works thereof, You may choose to offer,
          and charge a fee for, acceptance of support, warranty, indemnity,
          or other liability obligations and/or rights consistent with this
          License. However, in accepting such obligations, You may act only
          on Your own behalf and on Your sole responsibility, not on behalf
          of any other Contributor, and only if You agree to indemnify,
          defend, and hold each Contributor harmless for any liability
          incurred by, or claims asserted against, such Contributor by reason
          of your accepting any such warranty or additional liability.
    
       END OF TERMS AND CONDITIONS
    
       APPENDIX: How to apply the Apache License to your work.
    
          To apply the Apache License to your work, attach the following
          boilerplate notice, with the fields enclosed by brackets "{}"
          replaced with your own identifying information. (Don't include
          the brackets!)  The text should be enclosed in the appropriate
          comment syntax for the file format. We also recommend that a
          file or class name and description of purpose be included on the
          same "printed page" as the copyright notice for easier
          identification within third-party archives.
    
       Copyright {yyyy} {name of copyright owner}
    
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at
    
           http://www.apache.org/licenses/LICENSE-2.0
    
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
    

    封面將圖2完整等比縮放加白邊。手機圖2依序為tree1、tree2、原第一個分數和、原第二個分數和,移除兩樹間分隔線;手機圖3依原圖列優先順序排四圖;手機圖4將本篇已披露裁切版的左清單與右路由上下排列。皆保留原資料/數值與標籤,依Apache 2.0作上述編排,未暗示另行作者背書。

    留言0

    登入後就能留言。

    登入
    sunny 桑尼
    sunny 桑尼

    AI 資料科學 · 產品經理 · 蒙奇 D 桑尼

    專注於 AI 工具應用與資料科學教育,致力於讓每個人都能用 AI 提升工作效率。曾任職於科技業,現為全職教育創作者。

    讀更多文章 →想自己動手試?領免費 Starter Kit →