Machine Learning 📂 Supervised Learning · 17 of 19 152 min read

Boosting & XGBoost

A deep-dive tutorial on ensemble boosting — from the intuition behind AdaBoost to the math, regularisation, and Python implementation of XGBoost — with visual diagrams, real-world stories, and annotated code examples.

🌐
SectionSection第 01 节

The Story That Explains Boostingवह कहानी जो Boosting समझाती है一个解释 Boosting 的故事

The Student Who Learned From Every Mistakeवह Student जिसने हर गलती से सीखा从每个错误中学习的学生
A student sits three maths exams. After the first exam, the teacher marks only the questions the student got wrong. The next lesson focuses only on those hard ones. After the second exam, the same thing: find the new weak spots and practise them. By the third exam, the student is very strong. Not because of talent, but because each round fixed the mistakes of the round before.

That is Boosting. Random Forest trains many independent models. Boosting trains models one after another. Each new model focuses on the examples the current team still gets wrong.
एक student गणित की तीन परीक्षाएँ देता है। पहली परीक्षा के बाद teacher सिर्फ़ वे सवाल देखता है जो student ने गलत किए। अगली class सिर्फ़ उन कठिन सवालों पर होती है। दूसरी परीक्षा के बाद फिर वही: नई कमज़ोरियाँ खोजो और उनका अभ्यास करो। तीसरी परीक्षा तक student बहुत मज़बूत हो जाता है। प्रतिभा से नहीं, बल्कि इसलिए कि हर round ने पिछले round की गलतियाँ ठीक कीं।

यही Boosting है। Random Forest कई independent models train करता है। Boosting models को एक के बाद एक train करता है। हर नया model उन examples पर ध्यान देता है जो मौजूदा टीम अभी भी गलत करती है।
一个学生参加三次数学考试。第一次考完后,老师只标出学生做错的题,下一节课只讲这些难题。第二次考完后也一样:找出新的薄弱点并反复练习。到第三次考试时,这个学生已经非常强了。不是因为天赋,而是因为每一轮都修正了上一轮的错误。

这就是 Boosting。Random Forest 训练许多相互独立的 model,而 Boosting 一个接一个地训练 model。每个新 model 都专注于当前团队仍然做错的样本。

Boosting is a family of ensemble learning methods. The idea: combine many weak learners (models only a little better than guessing) into one strong learner. Each weak learner fixes what the earlier ones could not. The three most important members are:

Boosting, ensemble learning methods का एक परिवार है। विचार: कई weak learners (जो अंदाज़े से बस थोड़े बेहतर हों) को जोड़कर एक strong learner बनाना। हर weak learner वह ठीक करता है जो पहले वाले नहीं कर पाए। इसके तीन सबसे ज़रूरी सदस्य हैं:

Boosting 是一类 ensemble learning 方法。思路:把许多 weak learner(只比瞎猜好一点的 model)组合成一个 strong learner。每个 weak learner 修正前面的 learner 没能解决的问题。三个最重要的成员是:

📈
AdaBoost (1996)
Adaptive Boosting
Changes sample weights after each round. Wrong samples get heavier, so the next learner pays more attention to them. The final answer is a weighted vote.
हर round के बाद sample weights बदलता है। गलत samples भारी हो जाते हैं, इसलिए अगला learner उन पर ज़्यादा ध्यान देता है। आख़िरी जवाब एक weighted vote है।
每轮之后调整样本权重。错误的样本变"重",下一个 learner 就更关注它们。最终答案是加权投票。
📉
Gradient Boosting (1999)
Gradient descent in function spaceFunction space में gradient descent函数空间中的梯度下降
Each new tree fits the residuals (more precisely, the negative gradients) of the current model. Works with any differentiable loss: classification, regression, ranking.
हर नया tree मौजूदा model के residuals (सटीक रूप से, negative gradients) fit करता है। किसी भी differentiable loss के साथ काम करता है: classification, regression, ranking.
每棵新树拟合当前 model 的残差(更准确地说,是负梯度)。适用于任何可微 loss:分类、回归、排序。
⚡
XGBoost (2014)
Extreme Gradient Boosting
A fast, regularised version of gradient boosting. Adds L1/L2 penalties, handles missing values itself, supports GPUs. Still one of the top tools for tabular data.
Gradient boosting का तेज़, regularised version. L1/L2 penalties जोड़ता है, missing values खुद संभालता है, GPU support करता है। Tabular data के लिए अब भी सबसे अच्छे tools में से एक।
梯度提升的快速、带正则化版本。加入 L1/L2 惩罚,自己处理缺失值,支持 GPU。至今仍是表格数据的顶级工具之一。
💡
Bagging vs Boosting — The Core DifferenceBagging vs Boosting — मुख्य अंतरBagging vs Boosting — 核心区别

Bagging (Random Forest) builds trees in parallel. Each tree is independent. The goal is lower variance. Boosting builds trees one after another, each fixing the last. The goal is lower bias. This makes boosting more powerful, but it can overfit if you do not regularise it and stop it in time.

Bagging (Random Forest) trees को parallel में बनाता है। हर tree independent है। लक्ष्य: कम variance. Boosting trees को एक के बाद एक बनाता है, हर tree पिछले को सुधारता है। लक्ष्य: कम bias. इससे boosting ज़्यादा ताक़तवर है, पर अगर आप उसे regularise न करें और समय पर न रोकें तो वह overfit कर सकता है।

Bagging(Random Forest)并行建树,每棵树相互独立,目标是降低 variance。Boosting 逐个建树,每棵树修正上一棵,目标是降低 bias。这让 boosting 更强大,但如果不加正则化、不及时停止,就会过拟合。


SectionSection第 02 节

AdaBoost — Where It All StartedAdaBoost — जहाँ से सब शुरू हुआAdaBoost — 一切的起点

AdaBoost (Adaptive Boosting) was introduced by Freund & Schapire in the mid-1990s. Their work won the 2003 Gödel Prize. It is the simplest boosting method, and once you understand it, everything after it is easier.

AdaBoost (Adaptive Boosting) को Freund & Schapire ने 1990 के दशक के मध्य में पेश किया। उनके काम को 2003 का Gödel Prize मिला। यह सबसे सरल boosting method है, और इसे समझने के बाद आगे की हर चीज़ आसान हो जाती है।

AdaBoost(Adaptive Boosting)由 Freund 和 Schapire 在 1990 年代中期提出,他们的工作获得了 2003 年哥德尔奖。它是最简单的 boosting 方法,理解了它,后面的内容都会更容易。

The Panel of Distracted Judgesध्यान भटके Judges का Panel心不在焉的评委团
A talent show has five judges. Each one is half-asleep and only a little better than guessing. After every round, the producers find the contestants the judges got wrong. Those contestants perform first in the next round, so the judges watch them closely. Over time, the judges build a sharp picture of every contestant, especially the tricky ones. The final verdict gives more say to the judges who proved more reliable. That is AdaBoost.
एक talent show में पाँच judges हैं। हर कोई आधा सोया हुआ है और अंदाज़े से बस थोड़ा बेहतर है। हर round के बाद producers उन contestants को खोजते हैं जिनके बारे में judges गलत थे। वे contestants अगले round में सबसे पहले perform करते हैं, ताकि judges उन्हें ध्यान से देखें। धीरे-धीरे judges हर contestant की, ख़ासकर मुश्किल वालों की, साफ़ तस्वीर बना लेते हैं। आख़िरी फ़ैसले में ज़्यादा भरोसेमंद साबित हुए judges की बात ज़्यादा सुनी जाती है। यही AdaBoost है।
一场选秀有五位评委,每位都半睡半醒,只比瞎猜好一点。每轮结束后,制作人找出评委判断错误的选手,让他们在下一轮最先表演,迫使评委仔细观察。慢慢地,评委们对每位选手、尤其是难判断的选手形成了清晰的认识。最终裁决中,被证明更可靠的评委话语权更大。这就是 AdaBoost。

The AdaBoost Algorithm — Step by StepAdaBoost Algorithm — Step by StepAdaBoost 算法 — 逐步讲解

01
Start with equal weightsबराबर weights से शुरू करें从相同权重开始
Give every training sample the same weight: wᵢ = 1/N. In round one, every sample matters equally.
हर training sample को बराबर weight दें: wᵢ = 1/N. पहले round में हर sample बराबर मायने रखता है।
给每个训练样本相同的权重:wᵢ = 1/N。第一轮中每个样本同样重要。
02
Train a weak learnerएक weak learner train करें训练一个 weak learner
Fit a tiny decision tree, usually a stump (depth 1), on the weighted data. Heavy samples count more.
Weighted data पर एक छोटा decision tree fit करें, आमतौर पर एक stump (depth 1)। भारी samples ज़्यादा गिने जाते हैं।
在加权数据上拟合一棵很小的决策树,通常是 stump(深度 1)。权重大的样本影响更大。
03
Compute the weighted error εWeighted error ε निकालें计算加权误差 ε
ε = sum of the weights of the misclassified samples. A perfect stump gives ε = 0. A coin flip gives ε = 0.5.
ε = गलत classify हुए samples के weights का जोड़। Perfect stump पर ε = 0. सिक्का उछालने पर ε = 0.5.
ε = 所有分类错误样本的权重之和。完美的 stump 得 ε = 0,抛硬币得 ε = 0.5。
04
Compute the learner weight αLearner weight α निकालें计算 learner 权重 α
α = ½ · ln((1−ε)/ε). ε = 0.1 gives α ≈ 1.10 (strong vote). ε = 0.4 gives α ≈ 0.20 (weak vote). ε = 0.5 gives α = 0 (ignored). Try it in the simulator below.
α = ½ · ln((1−ε)/ε). ε = 0.1 पर α ≈ 1.10 (मज़बूत vote)। ε = 0.4 पर α ≈ 0.20 (कमज़ोर vote)। ε = 0.5 पर α = 0 (अनदेखा)। नीचे simulator में आज़माएँ।
α = ½ · ln((1−ε)/ε)。ε = 0.1 时 α ≈ 1.10(强投票);ε = 0.4 时 α ≈ 0.20(弱投票);ε = 0.5 时 α = 0(忽略)。在下面的模拟器里试试。
05
Update the sample weightsSample weights update करें更新样本权重
Wrong samples: weight × eα (bigger). Right samples: weight × e−α (smaller). Then divide by the total so the weights add up to 1.
गलत samples: weight × eα (बड़ा)। सही samples: weight × e−α (छोटा)। फिर total से भाग दें ताकि weights का जोड़ 1 हो।
错误样本:权重 × eα(变大);正确样本:权重 × e−α(变小)。然后除以总和,使权重之和为 1。
06
Repeat and combineदोहराएँ और जोड़ें重复并组合
Repeat steps 2–5 for T rounds. Final prediction: F(x) = sign(Σ αₜ · hₜ(x)), a weighted vote of all T stumps.
Steps 2–5 को T rounds तक दोहराएँ। आख़िरी prediction: F(x) = sign(Σ αₜ · hₜ(x)), सभी T stumps का weighted vote.
把第 2–5 步重复 T 轮。最终预测:F(x) = sign(Σ αₜ · hₜ(x)),即所有 T 个 stump 的加权投票。
📊 ADABOOST — HOW WEIGHTS CHANGE OVER 3 ROUNDSADABOOST — 3 ROUNDS में WEIGHTS कैसे बदलते हैंADABOOST — 3 轮中权重如何变化
AdaBoost weights over 3 rounds ROUND 1ROUND 1第 1 轮 all equal: 1/8सभी बराबर: 1/8全部相同:1/8 ε = 0.375 → α₁ = 0.26 ½·ln(0.625 / 0.375) ROUND 2ROUND 2第 2 轮 the 3 old mistakes grewपुरानी 3 गलतियाँ बड़ी हुईं之前的 3 个错误变大 ε = 0.200 → α₂ = 0.69 ½·ln(0.800 / 0.200) ROUND 3ROUND 3第 3 轮 new mistakes grewनई गलतियाँ बड़ी हुईं新的错误变大 ε = 0.062 → α₃ = 1.35 ½·ln(0.938 / 0.062) Correct this roundइस round में सही本轮正确 Wrong this round → weight growsइस round में गलत → weight बढ़ता है本轮错误 → 权重变大 Circle size = sample weight. Each round, the wrong points take exactly half of the total weight.Circle का आकार = sample weight. हर round के बाद गलत points के पास कुल weight का ठीक आधा होता है।圆的大小 = 样本权重。每一轮之后,错误点恰好占总权重的一半。

8 samples. Every number here comes from the formulas above. After each update, the wrong points always hold half of the total weight. That forces the next stump to take them seriously.

8 samples. यहाँ का हर number ऊपर के formulas से आया है। हर update के बाद गलत points के पास हमेशा कुल weight का आधा होता है। इससे अगला stump उन्हें गंभीरता से लेने पर मजबूर होता है।

8 个样本。这里每个数字都来自上面的公式。每次更新后,错误点总是占总权重的一半,这迫使下一个 stump 认真对待它们。

LIVELIVE互动AdaBoost Round by RoundAdaBoost Round दर RoundAdaBoost 逐轮演示

Squares belong inside the circle; dots are outside. Each round adds one stump (purple dashed line). Point size = weight. Red ring = still wrong. Watch the live ε, α and weight multipliers.

Squares घेरे के अंदर हैं; dots बाहर। हर round एक stump जोड़ता है (बैंगनी dashed line)। Point का आकार = weight. लाल घेरा = अभी भी गलत। Live ε, α और weight multipliers देखें।

方块在圆内,圆点在圆外。每一轮加入一个 stump(紫色虚线)。点的大小 = 权重,红圈 = 仍然错误。观察实时的 ε、α 和权重乘数。

RoundRound轮次
ε
α

Train accuracyTrain accuracyTrain accuracy
—

LIVELIVE互动How Error ε Becomes Vote Weight αError ε कैसे Vote Weight α बनता है误差 ε 如何变成投票权重 α

Move ε. The curve is α = ½ · ln((1−ε)/ε). The red zone (ε > 0.5) is worse than a coin flip.

ε को खिसकाएँ। Curve है α = ½ · ln((1−ε)/ε). लाल क्षेत्र (ε > 0.5) सिक्का उछालने से भी बुरा है।

拖动 ε。曲线是 α = ½ · ln((1−ε)/ε)。红色区域(ε > 0.5)比抛硬币还差。

α
wrong weightगलत का weight错误点权重 × eα
right weightसही का weight正确点权重 × e−α


SectionSection第 03 节

Gradient Boosting — The GeneralisationGradient Boosting — सामान्य रूपGradient Boosting — 推广形式

Gradient Boosting (Friedman, 1999; published 2001) took the idea of AdaBoost and turned it into gradient descent in function space. Instead of re-weighting samples, each new tree directly predicts the residual errors (more precisely, the negative gradients of the loss) of the current model.

Gradient Boosting (Friedman, 1999; प्रकाशित 2001) ने AdaBoost के विचार को function space में gradient descent बना दिया। Samples का weight बदलने के बजाय हर नया tree सीधे मौजूदा model की residual errors (सटीक रूप से, loss के negative gradients) predict करता है।

Gradient Boosting(Friedman,1999 年提出,2001 年发表)把 AdaBoost 的思想变成了函数空间中的梯度下降。它不再重新加权样本,而是让每棵新树直接预测当前 model 的残差(更准确地说,是 loss 的负梯度)。

🧮
The Key Insight — Residuals as New Labelsमुख्य बात — Residuals नए Labels हैं关键思想 — 把残差当作新标签

Your model predicts ₹72 lakh for a house worth ₹100 lakh. The residual is 28. Train the next tree to predict 28 (the error), not 100. If the tree gets it right and the learning rate η = 0.1, the new prediction is 72 + 0.1 × 28 = 74.8. A bit closer. Repeat, and each tree removes part of what is left.

आपका model ₹100 lakh के घर के लिए ₹72 lakh predict करता है। Residual 28 है। अगले tree को 28 (error) predict करना सिखाएँ, 100 नहीं। अगर tree सही है और learning rate η = 0.1 है, तो नया prediction है 72 + 0.1 × 28 = 74.8. थोड़ा पास। दोहराते रहें, हर tree बचे हुए error का एक हिस्सा हटाता है।

你的 model 对一套价值 ₹100 lakh 的房子预测为 ₹72 lakh,残差是 28。训练下一棵树去预测 28(误差),而不是 100。如果树预测准确且学习率 η = 0.1,新预测就是 72 + 0.1 × 28 = 74.8,更接近了一点。不断重复,每棵树都消除一部分剩余误差。

Gradient Boosting — The AlgorithmGradient Boosting — AlgorithmGradient Boosting — 算法

1. Start1. शुरुआत1. 初始化
F₀(x) = argminγ Σ L(yᵢ, γ)
Start with the best constant: the mean for MSE regression, the log-odds for classification.
सबसे अच्छे constant से शुरू करें: MSE regression के लिए mean, classification के लिए log-odds.
从最佳常数开始:MSE 回归用均值,分类用 log-odds。
2. Pseudo-residuals (gradient)2. Pseudo-residuals (gradient)2. 伪残差(梯度)
rᵢₘ = −∂L(yᵢ, F(xᵢ)) / ∂F(xᵢ)
The negative gradient of the loss. For L = ½(y − F)², this is simply yᵢ − F(xᵢ): the plain residual.
Loss का negative gradient. L = ½(y − F)² के लिए यह बस yᵢ − F(xᵢ) है: साधारण residual.
loss 的负梯度。对 L = ½(y − F)²,它就是 yᵢ − F(xᵢ),也就是普通残差。
3. Fit a tree to the residuals3. Residuals पर tree fit करें3. 用树拟合残差
hₘ(x) ≈ rᵢₘ
Train a small tree to predict the pseudo-residuals, not the original labels.
Original labels नहीं, pseudo-residuals predict करने के लिए एक छोटा tree train करें।
训练一棵小树去预测伪残差,而不是原始标签。
4. Update4. Update4. 更新
Fₘ(x) = Fₘ₋₁(x) + η · hₘ(x)
Add the new tree, scaled by the learning rate η (0 < η ≤ 1). Small η needs more trees but usually generalises better.
नया tree learning rate η (0 < η ≤ 1) से scale करके जोड़ें। छोटे η को ज़्यादा trees चाहिए पर यह आमतौर पर बेहतर generalise करता है।
把新树乘以学习率 η(0 < η ≤ 1)后加上。η 小需要更多树,但通常泛化更好。
📊 GRADIENT BOOSTING — THE LOOPGRADIENT BOOSTING — LOOPGRADIENT BOOSTING — 循环
Gradient boosting loop INITIALISEशुरुआत初始化 F₀(x) = mean(y) e.g. predict 50 for allजैसे सबके लिए 50例如全部预测 50 RESIDUALSRESIDUALS残差 r = y − F(x) e.g. +20, −15, +40 …जैसे +20, −15, +40 …例如 +20, −15, +40 … FIT TREE hₘTREE hₘ FIT करें拟合树 hₘ target = r small tree, depth 3–6छोटा tree, depth 3–6小树,深度 3–6 UPDATE FF UPDATE करें更新 F Fₘ = Fₘ₋₁ + η·hₘ η = learning rateη = learning rateη = 学习率 Repeat M times — one new tree per roundM बार दोहराएँ — हर round में एक नया tree重复 M 次 — 每轮一棵新树 F_M(x) = F₀ + η·h₁ + η·h₂ + … + η·h_M

Each round adds one tree whose only job is to predict the current mistakes. The learning rate η shrinks each tree, so no single tree can push the model too far.

हर round एक tree जोड़ता है जिसका एकमात्र काम मौजूदा गलतियाँ predict करना है। Learning rate η हर tree को छोटा करता है, ताकि कोई एक tree model को बहुत दूर न धकेले।

每一轮加入一棵树,它唯一的任务就是预测当前的错误。学习率 η 缩小每棵树的作用,避免任何一棵树把 model 推得太远。

LIVELIVE互动Watch Trees Fit the ResidualsTrees को Residuals Fit करते देखें看树如何拟合残差

Filled dots = training data. Hollow dots = validation data. Red lines = residuals (what is still wrong). Each round, one small tree fits those red lines, and the green curve moves. Below: training error keeps falling; validation error turns back up.

भरे dots = training data. खोखले dots = validation data. लाल lines = residuals (जो अभी भी गलत है)। हर round में एक छोटा tree उन लाल lines को fit करता है और हरा curve खिसकता है। नीचे: training error घटता रहता है; validation error फिर बढ़ने लगता है।

实心点 = 训练数据,空心点 = 验证数据,红线 = 残差(仍然错的部分)。每一轮,一棵小树拟合这些红线,绿色曲线随之移动。下方:训练误差持续下降,验证误差却会掉头上升。

Train MSEValidation MSEBest roundBest round最佳轮次
Train MSE
—
Validation MSE
—

Gradient Boosting From Scratch — 15 LinesGradient Boosting Scratch से — 15 Lines从零实现 Gradient Boosting — 15 行

The four formulas above fit in a short loop. The scikit-learn version with the same settings gives exactly the same training error, so this really is the whole algorithm (for MSE loss).

ऊपर के चार formulas एक छोटे loop में आ जाते हैं। उन्हीं settings वाला scikit-learn version बिल्कुल वही training error देता है, इसलिए (MSE loss के लिए) यही पूरा algorithm है।

上面四个公式可以写成一个很短的循环。相同设置下的 scikit-learn 版本给出完全相同的训练误差,所以(对 MSE loss 来说)这就是整个算法。

import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import GradientBoostingRegressor

# Toy data: a noisy sine wave
rng = np.random.default_rng(42)
X = np.sort(rng.uniform(0, 10, 200)).reshape(-1, 1)
y = 3 * np.sin(X).ravel() + rng.normal(0, 0.5, 200)

eta, n_rounds = 0.1, 100
F = np.full_like(y, y.mean())          # Step 1: F0 = mean of y
trees = []

for m in range(1, n_rounds + 1):
    residuals = y - F                  # Step 2: residuals (negative gradient of MSE)
    tree = DecisionTreeRegressor(max_depth=2).fit(X, residuals)   # Step 3
    F += eta * tree.predict(X)         # Step 4: F_m = F_(m-1) + eta * h_m
    trees.append(tree)
    if m in (1, 5, 20, 50, 100):
        print(f"Round {m:3d}: train MSE = {np.mean((y - F) ** 2):.4f}")

# Same settings in scikit-learn give the same answer
sk = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1,
                               max_depth=2, random_state=0).fit(X, y)
print(f"\nOur model      : train MSE = {np.mean((y - F) ** 2):.4f}")
print(f"scikit-learn   : train MSE = {np.mean((y - sk.predict(X)) ** 2):.4f}")
OUTPUT
Round 1: train MSE = 3.8419 Round 5: train MSE = 2.3920 Round 20: train MSE = 0.7429 Round 50: train MSE = 0.2163 Round 100: train MSE = 0.1415 Our model : train MSE = 0.1415 scikit-learn : train MSE = 0.1415
LIVELIVE互动Learning Rate RaceLearning Rate की दौड़学习率赛跑

Three models with the same depth, different learning rates, trained side by side. The lines show validation error. The dots mark each model's lowest point.

एक ही depth पर अलग learning rates वाले तीन models साथ-साथ train होते हैं। Lines validation error दिखाती हैं। Dots हर model का सबसे निचला बिंदु दिखाते हैं।

三个深度相同、学习率不同的 model 同时训练。曲线是验证误差,圆点标出每个 model 的最低点。

Lowest validation MSE @ roundसबसे कम validation MSE @ round最低验证 MSE @ 轮次
η = 0.02
—
η = 0.2
—
η = 1.0
—


SectionSection第 04 节

XGBoost — Extreme Gradient BoostingXGBoost — Extreme Gradient BoostingXGBoost — 极端梯度提升

How XGBoost Took Over KaggleXGBoost ने Kaggle को कैसे जीताXGBoost 如何征服 Kaggle
In 2014, Tianqi Chen, then a PhD student at the University of Washington, released XGBoost as a research project. It spread fast. In the 2016 XGBoost paper, the authors counted the 29 challenge-winning solutions published on Kaggle's blog in 2015: 17 of them used XGBoost. There was no magic. It did four things better than plain gradient boosting: regularisation, speed, missing-value handling and second-order gradients.
2014 में Tianqi Chen ने, जो उस समय University of Washington में PhD student थे, XGBoost को एक research project के रूप में जारी किया। यह तेज़ी से फैला। 2016 के XGBoost paper में authors ने 2015 में Kaggle के blog पर छपे 29 challenge-winning solutions गिने: उनमें से 17 ने XGBoost इस्तेमाल किया। कोई जादू नहीं था। इसने चार चीज़ें साधारण gradient boosting से बेहतर कीं: regularisation, speed, missing values संभालना और second-order gradients.
2014 年,当时还是华盛顿大学博士生的陈天奇把 XGBoost 作为研究项目发布,它迅速流行开来。在 2016 年的 XGBoost 论文中,作者统计了 2015 年 Kaggle 博客上发布的 29 个获奖方案:其中 17 个用了 XGBoost。这并不是魔法。它在四个方面比普通梯度提升做得更好:正则化、速度、缺失值处理和二阶梯度。

What Makes XGBoost DifferentXGBoost को क्या अलग बनाता हैXGBoost 有何不同

🔒
RegularisationRegularisation正则化
L1 (alpha) + L2 (lambda) + γ
Adds penalties on leaf weights and on the number of leaves directly in the objective. Complexity now has a price, which fights overfitting.
Leaf weights और leaves की संख्या पर penalties सीधे objective में जोड़ता है। अब complexity की एक कीमत है, जो overfitting से लड़ती है।
直接在目标函数中对叶子权重和叶子数量加惩罚。复杂度有了代价,从而抑制过拟合。
🧮
Second-order gradientsSecond-order gradients二阶梯度
Newton boosting
Uses the gradient and the Hessian (curvature). This gives a better step size for each leaf, much like Newton's method vs plain gradient descent.
Gradient और Hessian (curvature) दोनों इस्तेमाल करता है। इससे हर leaf के लिए बेहतर step size मिलता है, जैसे Newton's method बनाम साधारण gradient descent.
同时使用梯度和 Hessian(曲率),为每个叶子给出更好的步长,就像牛顿法相对于普通梯度下降。
❓
Native missing valuesMissing values खुद संभालता है原生处理缺失值
Sparsity-aware
Each split learns a default direction. Rows with a missing value follow it. No imputation needed. See the simulator below.
हर split एक default direction सीखता है। Missing value वाली rows उसी पर जाती हैं। Imputation की ज़रूरत नहीं। नीचे simulator देखें।
每个分裂都会学习一个默认方向,缺失值的行走这个方向,无需填补。见下面的模拟器。
🎲
Row and column samplingRow और column sampling行和列抽样
subsample · colsample_*
subsample and colsample_bytree/bylevel/bynode add randomness like Random Forest. Trees become less alike, which helps against overfitting.
subsample और colsample_bytree/bylevel/bynode Random Forest जैसी randomness जोड़ते हैं। Trees कम एक जैसे होते हैं, जिससे overfitting घटता है।
subsample 和 colsample_bytree/bylevel/bynode 像 Random Forest 一样加入随机性,让树之间差异更大,有助于防止过拟合。
🌳
Histogram splitsHistogram splits直方图分裂
tree_method='hist'
Puts each feature into bins (256 by default) before searching for splits. Much faster and lighter on memory. It is the default since XGBoost 2.0.
Split खोजने से पहले हर feature को bins (default 256) में बाँटता है। बहुत तेज़ और कम memory. XGBoost 2.0 से यही default है।
在寻找分裂点之前,先把每个特征分到若干个桶(默认 256 个)。速度快得多,内存占用也小。从 XGBoost 2.0 开始是默认方式。
💾
Built for speedSpeed के लिए बना为速度而生
CPU cache · device='cuda'
Cache-friendly data layout and multi-core training. With device='cuda' it trains on a GPU, which is often many times faster on large data.
Cache-friendly data layout और multi-core training. device='cuda' से GPU पर train होता है, जो बड़े data पर अक्सर कई गुना तेज़ है।
对缓存友好的数据布局和多核训练。用 device='cuda' 可在 GPU 上训练,在大数据上通常快很多倍。

The XGBoost Objective FunctionXGBoost Objective FunctionXGBoost 目标函数

Full objectiveपूरा objective完整目标
Obj = Σᵢ L(yᵢ, ŷᵢ) + Σₖ Ω(fₖ)
Loss (how well we fit) plus regularisation (how complex the trees are). XGBoost minimises both together.
Loss (fit कितना अच्छा है) + regularisation (trees कितने complex हैं)। XGBoost दोनों को साथ में कम करता है।
loss(拟合得多好)加上正则项(树有多复杂)。XGBoost 同时最小化两者。
Regularisation termRegularisation term正则项
Ω(f) = γT + ½λ Σⱼ wⱼ² + α Σⱼ |wⱼ|
T = number of leaves, wⱼ = leaf weights. γ charges for each leaf, λ is L2 on weights, α is L1 on weights.
T = leaves की संख्या, wⱼ = leaf weights. γ हर leaf की कीमत लेता है, λ weights पर L2 है, α weights पर L1 है।
T = 叶子数量,wⱼ = 叶子权重。γ 对每个叶子收费,λ 是权重的 L2,α 是权重的 L1。
Best leaf weightसबसे अच्छा leaf weight最优叶子权重
wⱼ* = −Gⱼ / (Hⱼ + λ)
G = sum of gradients in the leaf, H = sum of Hessians. (Shown for α = 0.) For MSE, h = 1, so this is the mean residual pulled toward 0 by λ.
G = leaf में gradients का जोड़, H = Hessians का जोड़। (α = 0 के लिए।) MSE में h = 1, इसलिए यह λ से 0 की ओर खींचा गया औसत residual है।
G = 叶子中梯度之和,H = Hessian 之和(α = 0 时)。对 MSE,h = 1,所以它就是被 λ 拉向 0 的平均残差。
Split gainSplit gain分裂增益
Gain = ½[GL²/(HL+λ) + GR²/(HR+λ) − G²/(H+λ)] − γ
How much a split improves the objective. If Gain < 0, the split is not worth its cost and is pruned.
Split से objective कितना सुधरता है। अगर Gain < 0, तो split अपनी कीमत के लायक नहीं और prune कर दिया जाता है।
分裂让目标函数改善了多少。如果 Gain < 0,说明分裂不值得,会被剪掉。
🔑
Why the Hessian HelpsHessian क्यों मदद करता है为什么 Hessian 有帮助

Plain gradient boosting follows the slope and then picks a step size. XGBoost also uses the curvature (second derivative), so each leaf gets a well-sized step straight away, like Newton's method. For log-loss this often means good results with fewer trees. For MSE the Hessian is constant (h = 1), so the two methods behave the same way.

साधारण gradient boosting ढलान का पीछा करता है और फिर step size चुनता है। XGBoost curvature (second derivative) भी इस्तेमाल करता है, इसलिए हर leaf को तुरंत सही आकार का step मिलता है, Newton's method की तरह। Log-loss में इसका मतलब अक्सर कम trees में अच्छे results है। MSE में Hessian constant (h = 1) है, इसलिए दोनों methods एक जैसे चलते हैं।

普通梯度提升沿着斜率走,然后再选步长。XGBoost 还使用曲率(二阶导数),所以每个叶子一开始就得到合适的步长,就像牛顿法。对 log-loss,这通常意味着用更少的树就能得到好结果。对 MSE,Hessian 是常数(h = 1),两种方法表现一样。

📊 XGBOOST TREE — GAIN, LEAF WEIGHTS AND PRUNINGXGBOOST TREE — GAIN, LEAF WEIGHTS और PRUNINGXGBOOST 树 — 增益、叶子权重与剪枝
XGBoost tree with gain and pruning Age < 35 ?G = 2.0 H = 14Gain = 7.49 > 0 ✓ yesहाँ是noनहीं否 Income < 50k ?G = −7.0 H = 7Gain = 0.16 > 0 ✓ Credit < 650 ?G = 9.0 H = 7Gain = -0.16 < 0 ✗ LEAFG=−6.0 H=4w* = +1.20 LEAFG=−1.0 H=3w* = +0.25 LEAF (pruned split)G=9.0 H=7w* = -1.125 Gain below 0 → keep it as one leafGain 0 से कम → एक ही leaf रखेंGain 小于 0 → 保留为一个叶子 λ = 1, γ = 0.5. MSE loss: g = ŷ − y, h = 1 per row.

Every number follows from the formulas above. The right-hand split has Gain = −0.16, which is below zero after subtracting γ, so XGBoost prunes it and keeps one leaf.

हर number ऊपर के formulas से आता है। दाईं ओर के split का Gain = −0.16 है, जो γ घटाने के बाद zero से कम है, इसलिए XGBoost उसे prune करके एक ही leaf रखता है।

每个数字都由上面的公式算出。右侧分裂的 Gain = −0.16,减去 γ 后小于 0,所以 XGBoost 把它剪掉,只保留一个叶子。

LIVELIVE互动XGBoost Split-Gain CalculatorXGBoost Split-Gain CalculatorXGBoost 分裂增益计算器

10 houses sorted by size. Bars = residuals the next tree must fix. Move the split. Change λ and γ. The thick lines are the leaf weights w*. The small bars at the bottom show the gain of every possible split.

10 घर size के क्रम में। Bars = residuals जिन्हें अगले tree को ठीक करना है। Split खिसकाएँ। λ और γ बदलें। मोटी lines leaf weights w* हैं। नीचे की छोटी bars हर संभव split का gain दिखाती हैं।

10 套房子按面积排序。柱子 = 下一棵树要修正的残差。移动分裂点,改变 λ 和 γ。粗线是叶子权重 w*。底部的小柱子显示每个可能分裂的增益。

Try λ = 10: every leaf weight shrinks toward 0. Raise γ until even the best split turns red: the tree stops growing.

λ = 10 आज़माएँ: हर leaf weight 0 की ओर सिकुड़ता है। γ को तब तक बढ़ाएँ जब तक सबसे अच्छा split भी लाल न हो जाए: tree बढ़ना बंद कर देता है।

试试 λ = 10:每个叶子权重都向 0 收缩。把 γ 调大,直到连最佳分裂也变红:树就不再生长。

LIVELIVE互动Missing Values: The Learned Default DirectionMissing Values: सीखी हुई Default Direction缺失值:学到的默认方向

The split is "Age < 30". Three passengers have no Age. XGBoost tries sending them left, then right, computes the gain for each (λ = 1), and keeps the better one. That choice is stored in the tree.

Split है "Age < 30"। तीन passengers की Age नहीं है। XGBoost उन्हें पहले left, फिर right भेजकर देखता है, हर एक का gain (λ = 1) निकालता है, और बेहतर वाला रखता है। यह फ़ैसला tree में save हो जाता है।

分裂条件是 "Age < 30"。有三位乘客没有 Age。XGBoost 先试着把他们放到左边,再放到右边,分别计算增益(λ = 1),保留更好的那个。这个选择会被存进树里。

LeftLeft左 (Age < 30)
RightRight右 (Age ≥ 30)

Small number = residual of that passenger.छोटी संख्या = उस passenger का residual.小数字 = 该乘客的残差。

—
—


SectionSection第 05 节

Python Implementation — AdaBoostPython Implementation — AdaBoostPython 实现 — AdaBoost

Let's start with AdaBoost on a classic yes/no problem: will a bank customer default on a loan? (The data is synthetic.)

AdaBoost से एक classic हाँ/नहीं वाले सवाल पर शुरू करें: क्या bank customer loan default करेगा? (Data synthetic है।)

先用 AdaBoost 解决一个经典的是/否问题:银行客户会不会贷款违约?(数据是合成的。)

import numpy as np
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.datasets import make_classification

# ── Synthetic "loan default" dataset ──────────────────────
X, y = make_classification(
    n_samples=5000, n_features=15, n_informative=10,
    n_redundant=3, class_sep=0.8, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# ── AdaBoost with decision stumps (depth = 1) ─────────────
# Note: do NOT pass algorithm='SAMME'. That parameter was removed
# from recent scikit-learn; SAMME is now the only algorithm.
ada = AdaBoostClassifier(
    estimator=DecisionTreeClassifier(max_depth=1),
    n_estimators=200,        # number of stumps / boosting rounds
    learning_rate=0.5,       # shrinks each stump's vote
    random_state=42
)

# ── Cross-validation ──────────────────────────────────────
cv_auc = cross_val_score(ada, X_train, y_train, cv=5, scoring='roc_auc')
print(f"CV ROC-AUC  : {cv_auc.mean():.4f} ± {cv_auc.std():.4f}")

# ── Fit and evaluate ──────────────────────────────────────
ada.fit(X_train, y_train)
y_pred  = ada.predict(X_test)
y_proba = ada.predict_proba(X_test)[:, 1]
print(f"Test ROC-AUC: {roc_auc_score(y_test, y_proba):.4f}\n")
print(classification_report(y_test, y_pred))

# ── Look at the stump weights (alpha) ─────────────────────
print("Top 5 stump weights:")
for i in np.argsort(ada.estimator_weights_)[::-1][:5]:
    print(f"  Stump {i:3d}: weight = {ada.estimator_weights_[i]:.4f}")
OUTPUT
CV ROC-AUC : 0.9024 ± 0.0146 Test ROC-AUC: 0.9026 precision recall f1-score support 0 0.84 0.82 0.83 499 1 0.83 0.85 0.84 501 accuracy 0.83 1000 macro avg 0.84 0.83 0.83 1000 weighted avg 0.84 0.83 0.83 1000 Top 5 stump weights: Stump 0: weight = 0.4207 Stump 1: weight = 0.3277 Stump 5: weight = 0.2245 Stump 6: weight = 0.2118 Stump 8: weight = 0.2081
⚠️
Two Things to Know About scikit-learn's AdaBoostscikit-learn के AdaBoost के बारे में दो बातें关于 scikit-learn AdaBoost 的两件事

1. Older code passes algorithm='SAMME'. That parameter was deprecated in scikit-learn 1.6 and is now removed, so old code crashes. Just delete it.
2. estimator_weights_ are not the textbook α. For two classes, scikit-learn stores learning_rate × ln((1−ε)/ε), which is 2 × learning_rate × α. The model is the same; only the scale differs.

1. पुराना code algorithm='SAMME' देता है। यह parameter scikit-learn 1.6 में deprecated हुआ और अब हटा दिया गया है, इसलिए पुराना code crash होता है। बस इसे हटा दें।
2. estimator_weights_ textbook वाला α नहीं हैं। दो classes के लिए scikit-learn learning_rate × ln((1−ε)/ε) रखता है, जो 2 × learning_rate × α है। Model वही है; सिर्फ़ scale अलग है।

1. 旧代码会传入 algorithm='SAMME'。这个参数在 scikit-learn 1.6 中已弃用,现在已移除,旧代码会报错,直接删掉即可。
2. estimator_weights_ 不是教科书里的 α。对二分类,scikit-learn 存储的是 learning_rate × ln((1−ε)/ε),即 2 × learning_rate × α。model 是一样的,只是尺度不同。


SectionSection第 06 节

Python Implementation — XGBoost End-to-EndPython Implementation — XGBoost शुरू से अंत तकPython 实现 — XGBoost 端到端

Now the real workhorse: a full XGBoost pipeline on the classic Titanic survival data (Kaggle train.csv, 891 passengers), with feature engineering, early stopping and annotated hyperparameters.

अब असली workhorse: classic Titanic survival data (Kaggle train.csv, 891 passengers) पर पूरी XGBoost pipeline, feature engineering, early stopping और समझाए गए hyperparameters के साथ।

现在来看真正的主力:在经典的 Titanic 生存数据(Kaggle train.csv,891 名乘客)上搭建完整的 XGBoost 流程,包括特征工程、early stopping 和带注释的超参数。

import xgboost as xgb
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.preprocessing import LabelEncoder

# ── Load data (Kaggle Titanic train.csv) ──────────────────
df = pd.read_csv('titanic.csv')

# ── Feature engineering ───────────────────────────────────
df['Title'] = df['Name'].str.extract(r' ([A-Za-z]+)\.', expand=False)
df['Title'] = df['Title'].replace({
    'Mlle': 'Miss', 'Ms': 'Miss', 'Mme': 'Mrs',
    'Lady': 'Rare', 'Countess': 'Rare', 'Capt': 'Rare', 'Col': 'Rare',
    'Don': 'Rare', 'Dr': 'Rare', 'Major': 'Rare', 'Rev': 'Rare',
    'Sir': 'Rare', 'Jonkheer': 'Rare', 'Dona': 'Rare'
})
df['FamilySize'] = df['SibSp'] + df['Parch'] + 1
df['IsAlone']    = (df['FamilySize'] == 1).astype(int)

# pandas 3: assign back. df['Age'].fillna(..., inplace=True) does NOTHING.
# (XGBoost can also handle NaN itself; we fill here only for Embarked/Fare.)
df['Embarked'] = df['Embarked'].fillna(df['Embarked'].mode()[0])
df['Fare']     = df['Fare'].fillna(df['Fare'].median())

# Encode text columns as integers
for col in ['Sex', 'Embarked', 'Title']:
    df[col] = LabelEncoder().fit_transform(df[col].astype(str))

features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch',
            'Fare', 'Embarked', 'Title', 'FamilySize', 'IsAlone']
X, y = df[features], df['Survived']     # Age keeps its NaNs on purpose

# ── XGBoost model — annotated hyperparameters ─────────────
model = xgb.XGBClassifier(
    # Boosting structure
    n_estimators     = 1000,     # upper limit; early stopping picks the real number
    learning_rate    = 0.05,     # eta: shrinks each tree's contribution
    max_depth        = 4,        # tree depth: 3-6 is typical
    # Regularisation
    reg_alpha        = 0.1,      # L1 on leaf weights
    reg_lambda       = 1.0,      # L2 on leaf weights
    gamma            = 0.05,     # minimum gain needed to split
    min_child_weight = 3,        # minimum Hessian sum in a leaf
    # Randomisation (like Random Forest)
    subsample        = 0.8,      # rows per tree
    colsample_bytree = 0.7,      # columns per tree
    # Performance
    tree_method      = 'hist',   # fast histogram splits (the default in XGBoost 2+)
    device           = 'cpu',    # 'cuda' for GPU
    n_jobs           = -1,
    random_state     = 42,
    eval_metric      = 'logloss',  # smooth metric: better for early stopping than AUC
    early_stopping_rounds = 50   # stop after 50 rounds with no improvement
)

# ── Hold out a validation set for early stopping ──────────
X_tr, X_val, y_tr, y_val = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
model.fit(X_tr, y_tr, eval_set=[(X_val, y_val)], verbose=50)

print(f"\nBest iteration : {model.best_iteration}")
print(f"Best val loss  : {model.best_score:.4f}")

# ── Cross-validated AUC with the chosen number of trees ───
cv_model = xgb.XGBClassifier(
    n_estimators=model.best_iteration + 1,   # best_iteration is 0-based
    learning_rate=0.05, max_depth=4, subsample=0.8,
    colsample_bytree=0.7, tree_method='hist', n_jobs=-1, random_state=42
)
cv = StratifiedKFold(5, shuffle=True, random_state=42)
cv_auc = cross_val_score(cv_model, X, y, cv=cv, scoring='roc_auc')
print(f"CV ROC-AUC     : {cv_auc.mean():.4f} ± {cv_auc.std():.4f}")

# ── Feature importance (the default type is 'gain') ───────
imp = pd.Series(model.feature_importances_, index=features)
print("\nFeature importance (gain):")
print(imp.sort_values(ascending=False).round(4).to_string())
OUTPUT
[0] validation_0-logloss:0.64713 [50] validation_0-logloss:0.44345 [99] validation_0-logloss:0.44845 Best iteration : 49 Best val loss : 0.4423 CV ROC-AUC : 0.8807 ± 0.0172 Feature importance (gain): Sex 0.4231 Title 0.1535 Pclass 0.1055 FamilySize 0.0703 SibSp 0.0515 Embarked 0.0440 Fare 0.0439 Age 0.0420 Parch 0.0348 IsAlone 0.0312
🐛
pandas 3 Trap: inplace=True on a Columnpandas 3 का जाल: Column पर inplace=Truepandas 3 陷阱:在列上用 inplace=True

Many tutorials write df['Age'].fillna(x, inplace=True). In pandas 3 (Copy-on-Write), this changes a temporary copy, and df stays the same. Always assign back: df['Age'] = df['Age'].fillna(x). Here we leave Age empty on purpose, because XGBoost handles NaN by itself.

कई tutorials df['Age'].fillna(x, inplace=True) लिखते हैं। pandas 3 (Copy-on-Write) में यह एक temporary copy बदलता है, और df वैसा ही रहता है। हमेशा वापस assign करें: df['Age'] = df['Age'].fillna(x). यहाँ हम Age को जानबूझकर खाली छोड़ते हैं, क्योंकि XGBoost NaN को खुद संभालता है।

很多教程写 df['Age'].fillna(x, inplace=True)。在 pandas 3(Copy-on-Write)中,这只会修改一个临时副本,df 本身不变。一定要赋值回去:df['Age'] = df['Age'].fillna(x)。这里我们故意让 Age 保持缺失,因为 XGBoost 能自己处理 NaN。

🎯
Early Stopping — The Most Important XGBoost HabitEarly Stopping — XGBoost की सबसे ज़रूरी आदतEarly Stopping — 最重要的 XGBoost 习惯

Set n_estimators high and add early_stopping_rounds with a validation set. Training stops when the validation score stops improving. Here it stopped at round 49 out of a possible 1000. Two tips from this run: (1) stop on logloss, not AUC. On small validation sets AUC is jumpy. With AUC this same model stopped at round 3 and its CV AUC fell from 0.881 to 0.872. (2) best_iteration counts from 0, so retrain with best_iteration + 1 trees.

n_estimators ऊँचा रखें और validation set के साथ early_stopping_rounds जोड़ें। जब validation score सुधरना बंद करता है तो training रुक जाती है। यहाँ यह 1000 में से round 49 पर रुकी। इस run से दो tips: (1) AUC नहीं, logloss पर रोकें। छोटे validation sets पर AUC उछलता है। AUC के साथ यही model round 3 पर रुका और उसका CV AUC 0.881 से गिरकर 0.872 हो गया। (2) best_iteration 0 से गिनता है, इसलिए best_iteration + 1 trees के साथ दोबारा train करें।

把 n_estimators 设大,并配合验证集使用 early_stopping_rounds。验证分数不再提升时训练就会停止。这里它在 1000 轮中的第 49 轮停下。从这次运行得到两个建议:(1) 用 logloss 而不是 AUC 来停止。小验证集上 AUC 波动大,用 AUC 时同一个 model 在第 3 轮就停了,CV AUC 从 0.881 降到 0.872。(2) best_iteration 从 0 开始计数,所以重新训练时用 best_iteration + 1 棵树。


SectionSection第 07 节

XGBoost for RegressionRegression के लिए XGBoostXGBoost 回归

XGBoost works just as well for regression. You mainly change the objective. Here we predict house prices in California.

XGBoost regression के लिए भी उतना ही अच्छा है। मुख्य रूप से आप objective बदलते हैं। यहाँ हम California में घरों की कीमत predict करते हैं।

XGBoost 做回归同样出色,主要只需改 objective。这里我们预测加州的房价。

import numpy as np
import xgboost as xgb
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.metrics import root_mean_squared_error, mean_absolute_error, r2_score

# ── Load California housing ───────────────────────────────
data = fetch_california_housing(as_frame=True)
X, y = data.data, data.target          # y = median house value in $100,000

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
X_tr, X_val, y_tr, y_val = train_test_split(
    X_train, y_train, test_size=0.15, random_state=42
)

# ── XGBoost regressor ─────────────────────────────────────
reg = xgb.XGBRegressor(
    objective        = 'reg:squarederror',   # MSE loss
    n_estimators     = 3000,
    learning_rate    = 0.04,
    max_depth        = 5,
    min_child_weight = 5,
    subsample        = 0.8,
    colsample_bytree = 0.8,
    reg_alpha        = 0.05,
    reg_lambda       = 1.5,
    gamma            = 0.1,
    tree_method      = 'hist',
    eval_metric      = 'rmse',
    early_stopping_rounds = 50,
    n_jobs           = -1,
    random_state     = 42
)
reg.fit(X_tr, y_tr, eval_set=[(X_val, y_val)], verbose=200)

# ── Evaluate on the untouched test set ────────────────────
y_pred = reg.predict(X_test)
print(f"\nTest RMSE : {root_mean_squared_error(y_test, y_pred):.4f}")
print(f"Test MAE  : {mean_absolute_error(y_test, y_pred):.4f}")
print(f"Test R²   : {r2_score(y_test, y_pred):.4f}")
print(f"Best iter : {reg.best_iteration}")
OUTPUT
[0] validation_0-rmse:1.14718 [200] validation_0-rmse:0.50320 [400] validation_0-rmse:0.48749 [600] validation_0-rmse:0.48231 [800] validation_0-rmse:0.47808 [1000] validation_0-rmse:0.47606 [1200] validation_0-rmse:0.47402 [1400] validation_0-rmse:0.47293 [1600] validation_0-rmse:0.47202 [1620] validation_0-rmse:0.47198 Test RMSE : 0.4423 Test MAE : 0.2914 Test R² : 0.8507 Best iter : 1570
📏
Compute RMSE DirectlyRMSE सीधे निकालें直接计算 RMSE

Some versions of this example compute RMSE as sqrt(MAE² + var(error)). That is not RMSE: MAE² is not the same as the squared mean error, so the number is wrong. Use root_mean_squared_error (scikit-learn 1.4+) or np.sqrt(mean_squared_error(...)). Also note that early stopping never touched the test set; it used the separate validation split.

इस example के कुछ versions RMSE को sqrt(MAE² + var(error)) से निकालते हैं। यह RMSE नहीं है: MAE², squared mean error के बराबर नहीं होता, इसलिए number गलत आता है। root_mean_squared_error (scikit-learn 1.4+) या np.sqrt(mean_squared_error(...)) इस्तेमाल करें। यह भी देखें कि early stopping ने test set को कभी नहीं छुआ; उसने अलग validation split इस्तेमाल किया।

这个例子的某些版本用 sqrt(MAE² + var(error)) 计算 RMSE。这不是 RMSE:MAE² 不等于平均误差的平方,所以结果是错的。请使用 root_mean_squared_error(scikit-learn 1.4+)或 np.sqrt(mean_squared_error(...))。另外注意,early stopping 从未接触测试集,它用的是单独的验证集。


SectionSection第 08 节

Hyperparameter Guide — The Complete ReferenceHyperparameter Guide — पूरा Reference超参数指南 — 完整参考

XGBoost has dozens of hyperparameters. These are the ones that matter in practice. Defaults are for XGBoost 2.x/3.x.

XGBoost में दर्जनों hyperparameters हैं। ये वे हैं जो असल में मायने रखते हैं। Defaults XGBoost 2.x/3.x के हैं।

XGBoost 有几十个超参数,下面是实践中真正重要的。默认值适用于 XGBoost 2.x/3.x。

ParameterDefaultEffectअसर作用How to tuneकैसे tune करें如何调整
n_estimators100Number of boosting rounds (trees)Boosting rounds (trees) की संख्या提升轮数(树的数量)Set high, use early stoppingऊँचा रखें, early stopping लगाएँ设大,用 early stopping
learning_rate (η)0.3Shrinks each tree. Lower = more trees, usually better generalisationहर tree को छोटा करता है। कम = ज़्यादा trees, आमतौर पर बेहतर generalisation缩小每棵树的作用。越低 = 树越多,通常泛化更好0.01–0.1 for the final modelFinal model के लिए 0.01–0.1最终 model 用 0.01–0.1
max_depth6Depth of each tree. Deeper = more complex, more overfit riskहर tree की depth. ज़्यादा = ज़्यादा complex, overfit का ख़तरा每棵树的深度。越深越复杂,过拟合风险越高3–6 is the usual rangeआमतौर पर 3–6通常 3–6
min_child_weight1Minimum Hessian sum in a leaf. Higher = more careful splitsLeaf में न्यूनतम Hessian जोड़। ज़्यादा = ज़्यादा सावधान splits叶子中 Hessian 和的最小值。越高分裂越保守1–10; raise if overfitting1–10; overfit हो तो बढ़ाएँ1–10;过拟合时调大
gamma (γ)0Minimum gain needed to split. Prunes weak splitsSplit के लिए न्यूनतम gain. कमज़ोर splits prune करता है分裂所需的最小增益,剪掉弱分裂0–5; raise if overfitting0–5; overfit हो तो बढ़ाएँ0–5;过拟合时调大
subsample1.0Share of rows used per treeहर tree के लिए rows का हिस्सा每棵树使用的行比例0.6–0.9 reduces overfitting0.6–0.9 overfitting घटाता है0.6–0.9 可减少过拟合
colsample_bytree1.0Share of columns used per treeहर tree के लिए columns का हिस्सा每棵树使用的列比例0.5–0.9; try 0.7 first0.5–0.9; पहले 0.7 आज़माएँ0.5–0.9;先试 0.7
reg_alpha (α)0L1 penalty on leaf weightsLeaf weights पर L1 penalty叶子权重的 L1 惩罚0, 0.01, 0.1, 1
reg_lambda (λ)1L2 penalty on leaf weights. Shrinks them toward 0Leaf weights पर L2 penalty. उन्हें 0 की ओर सिकोड़ता है叶子权重的 L2 惩罚,把它们向 0 收缩1, 2, 5; raise if overfitting1, 2, 5; overfit हो तो बढ़ाएँ1, 2, 5;过拟合时调大
scale_pos_weight1For imbalanced classesImbalanced classes के लिए用于类别不平衡sum(neg) / sum(pos)
tree_method'hist'How splits are searched. 'hist' is the default since XGBoost 2.0Splits कैसे खोजे जाते हैं। XGBoost 2.0 से 'hist' default है如何搜索分裂点。从 XGBoost 2.0 起默认是 'hist'Keep 'hist'; 'exact' only for small data'hist' रखें; 'exact' सिर्फ़ छोटे data के लिए保持 'hist';只有小数据才用 'exact'
🎓
A Tuning Order That WorksTuning का एक क्रम जो काम करता है一个有效的调参顺序

① Fix learning_rate=0.1 and find the number of trees with early stopping. ② Tune max_depth and min_child_weight together. ③ Tune gamma. ④ Tune subsample and colsample_bytree. ⑤ Tune reg_alpha and reg_lambda. ⑥ Lower learning_rate and retrain with more trees. This avoids searching a 10-dimensional space blindly. Or let Optuna do it (next section).

① learning_rate=0.1 तय करें और early stopping से trees की संख्या खोजें। ② max_depth और min_child_weight साथ tune करें। ③ gamma tune करें। ④ subsample और colsample_bytree tune करें। ⑤ reg_alpha और reg_lambda tune करें। ⑥ learning_rate घटाएँ और ज़्यादा trees के साथ दोबारा train करें। इससे 10-dimensional space में अंधेरे में खोज से बचते हैं। या यह काम Optuna को करने दें (अगला section)।

① 固定 learning_rate=0.1,用 early stopping 找出树的数量。② 一起调 max_depth 和 min_child_weight。③ 调 gamma。④ 调 subsample 和 colsample_bytree。⑤ 调 reg_alpha 和 reg_lambda。⑥ 降低 learning_rate,用更多树重新训练。这样可以避免在 10 维空间里盲目搜索。或者让 Optuna 来做(下一节)。


SectionSection第 09 节

Hyperparameter Tuning with OptunaOptuna से Hyperparameter Tuning用 Optuna 调超参数

Manual tuning works, but Optuna's smart (Bayesian-style) search is faster and often finds better combinations. Here it searches 9 hyperparameters on the Titanic data from Section 06.

Manual tuning काम करती है, पर Optuna की smart (Bayesian-style) search तेज़ है और अक्सर बेहतर combinations खोजती है। यहाँ यह Section 06 के Titanic data पर 9 hyperparameters खोजती है।

手动调参可行,但 Optuna 的智能(贝叶斯式)搜索更快,常常能找到更好的组合。这里它在第 06 节的 Titanic 数据上搜索 9 个超参数。

import optuna
import xgboost as xgb
from sklearn.model_selection import StratifiedKFold, cross_val_score

optuna.logging.set_verbosity(optuna.logging.WARNING)   # quiet output

# X, y: the Titanic features from the previous section
def objective(trial):
    params = {
        'n_estimators'    : trial.suggest_int('n_estimators', 100, 800),
        'learning_rate'   : trial.suggest_float('learning_rate', 0.01, 0.3, log=True),
        'max_depth'       : trial.suggest_int('max_depth', 2, 8),
        'min_child_weight': trial.suggest_int('min_child_weight', 1, 10),
        'gamma'           : trial.suggest_float('gamma', 0, 5),
        'subsample'       : trial.suggest_float('subsample', 0.5, 1.0),
        'colsample_bytree': trial.suggest_float('colsample_bytree', 0.4, 1.0),
        'reg_alpha'       : trial.suggest_float('reg_alpha', 1e-8, 10, log=True),
        'reg_lambda'      : trial.suggest_float('reg_lambda', 1e-8, 10, log=True),
    }
    model = xgb.XGBClassifier(**params, tree_method='hist', n_jobs=-1, random_state=42)
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
    return cross_val_score(model, X, y, cv=cv, scoring='roc_auc').mean()

study = optuna.create_study(direction='maximize',
                            sampler=optuna.samplers.TPESampler(seed=42))
study.optimize(objective, n_trials=100, timeout=300)   # 5 minutes max

print(f"Trials run : {len(study.trials)}")
print(f"Best AUC   : {study.best_value:.4f}")
print("Best params:")
for k, v in study.best_params.items():
    print(f"  {k:<17}: {v:.4g}" if isinstance(v, float) else f"  {k:<17}: {v}")

# ── Retrain the final model with the best params ──────────
best = xgb.XGBClassifier(**study.best_params, tree_method='hist',
                         n_jobs=-1, random_state=42)
best.fit(X, y)
OUTPUT
Trials run : 100 Best AUC : 0.8892 Best params: n_estimators : 479 learning_rate : 0.01489 max_depth : 6 min_child_weight : 1 gamma : 0.6808 subsample : 0.5488 colsample_bytree : 0.7535 reg_alpha : 0.01015 reg_lambda : 7.049e-07

After 100 trials, the best CV AUC is 0.889, up from 0.881 with our hand-picked settings. Notice the pattern Optuna found: a very low learning rate (0.015) with many trees (479). That matches the advice in the table above.

100 trials के बाद best CV AUC 0.889 है, हमारी हाथ से चुनी settings के 0.881 से ज़्यादा। Optuna को मिला pattern देखें: बहुत कम learning rate (0.015) और कई trees (479)। यह ऊपर की table की सलाह से मेल खाता है।

100 次试验后,最佳 CV AUC 为 0.889,高于我们手动选择参数时的 0.881。注意 Optuna 找到的规律:很低的学习率(0.015)加上很多树(479 棵),这和上表的建议一致。


SectionSection第 10 节

Feature Importance in XGBoost — Three TypesXGBoost में Feature Importance — तीन प्रकारXGBoost 特征重要性 — 三种类型

XGBoost can measure feature importance in three ways. They tell different stories, and on real data they can disagree a lot.

XGBoost feature importance को तीन तरीकों से माप सकता है। वे अलग कहानियाँ बताते हैं, और असली data पर उनमें बहुत अंतर हो सकता है।

XGBoost 可以用三种方式衡量特征重要性。它们讲述的故事不同,在真实数据上可能差别很大。

📊
weight
Split countSplit की गिनती分裂次数
How many times a feature is used to split, across all trees. Fast, but biased toward features with many unique values.
सभी trees में किसी feature पर कितनी बार split हुआ। तेज़, पर कई unique values वाले features की ओर झुका हुआ।
某个特征在所有树中被用来分裂的次数。速度快,但偏向取值很多的特征。
📈
gain
Average gainऔसत gain平均增益
Average loss reduction when the feature is used to split. More reliable than weight. This is the default for feature_importances_.
जब feature पर split होता है तो औसतन loss कितना घटता है। weight से ज़्यादा भरोसेमंद। feature_importances_ का default यही है।
用该特征分裂时 loss 的平均下降量。比 weight 更可靠。它是 feature_importances_ 的默认值。
🔍
cover
Average coverageऔसत coverage平均覆盖
Average number of samples (Hessian sum) touched by splits on this feature. Shows which features affect the most rows.
इस feature के splits औसतन कितने samples (Hessian जोड़) को छूते हैं। दिखाता है कि कौन से features सबसे ज़्यादा rows पर असर डालते हैं।
在该特征上分裂时平均影响的样本数(Hessian 和)。显示哪些特征影响最多的行。
import matplotlib.pyplot as plt
from xgboost import plot_importance
import shap

# `model` and `X_val` come from the Titanic example above
booster = model.get_booster()

# ── The three built-in importance types ───────────────────
for imp_type in ['weight', 'gain', 'cover']:
    scores = booster.get_score(importance_type=imp_type)
    top3 = sorted(scores.items(), key=lambda kv: -kv[1])[:3]
    print(f"{imp_type:<7}: " + ", ".join(f"{f} ({v:.1f})" for f, v in top3))

fig, axes = plt.subplots(1, 3, figsize=(18, 5))
for ax, imp_type in zip(axes, ['weight', 'gain', 'cover']):
    plot_importance(model, importance_type=imp_type, ax=ax,
                    title=f'Importance ({imp_type})')
plt.tight_layout()
plt.savefig('xgb_importance.png', dpi=150)

# ── SHAP values: the most reliable importance ─────────────
explainer   = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_val)
mean_abs = abs(shap_values).mean(axis=0)
top3 = sorted(zip(X_val.columns, mean_abs), key=lambda kv: -kv[1])[:3]
print("SHAP   : " + ", ".join(f"{f} ({v:.3f})" for f, v in top3))
shap.summary_plot(shap_values, X_val, plot_type='bar', show=False)
OUTPUT
weight : Fare (282.0), Age (250.0), Pclass (74.0) gain : Sex (26.1), Title (9.5), Pclass (6.5) cover : Sex (85.0), Title (57.5), Pclass (46.6) SHAP : Sex (0.792), Pclass (0.369), Title (0.291)
LIVELIVE互动Same Model, Four Different Rankingsएक ही Model, चार अलग Rankings同一个 model,四种不同的排名

Real numbers from the Titanic model above (shares add up to 100%). Switch between the importance types and watch the ranking change.

ऊपर वाले Titanic model के असली numbers (हिस्सों का जोड़ 100%)। Importance types के बीच बदलें और ranking बदलते देखें।

来自上面 Titanic model 的真实数字(各项之和为 100%)。在不同的重要性类型之间切换,看排名如何变化。

⭐
Use SHAP for Decisionsफ़ैसलों के लिए SHAP इस्तेमाल करें做决策时用 SHAP

Built-in scores are quick checks, but as you just saw, "weight" ranked Fare and Age first while every other method ranked Sex first. SHAP values (SHapley Additive exPlanations) come from game theory, are consistent, and show the direction of each feature's effect, not just its size. Use SHAP for any model that goes into production or a client presentation.

Built-in scores जल्दी जाँच के लिए हैं, पर जैसा आपने अभी देखा, "weight" ने Fare और Age को पहले रखा जबकि बाकी हर method ने Sex को पहले रखा। SHAP values (SHapley Additive exPlanations) game theory से आती हैं, consistent हैं, और हर feature के असर की दिशा भी दिखाती हैं, सिर्फ़ आकार नहीं। Production या client presentation में जाने वाले हर model के लिए SHAP इस्तेमाल करें।

内置分数适合快速检查,但正如你刚才看到的,"weight" 把 Fare 和 Age 排在最前,而其他所有方法都把 Sex 排第一。SHAP 值(SHapley Additive exPlanations)来自博弈论,具有一致性,并能显示每个特征影响的方向,而不只是大小。任何要上线或给客户展示的 model 都应使用 SHAP。


SectionSection第 11 节

The Full Boosting LandscapeBoosting का पूरा नक्शाBoosting 全景图

📊 THE BOOSTING FAMILY TREEBOOSTING का FAMILY TREEBOOSTING 家族树
Boosting family tree ENSEMBLE LEARNING combine many modelsकई models जोड़ें组合多个 model BAGGINGparallel · less variance STACKINGmeta-learner BOOSTINGsequential · less bias Random ForestBreiman, 2001 AdaBoostFreund & Schapire, 1996 Gradient BoostingFriedman, 1999–2001 XGBoost ⭐Chen, 2014 LightGBMMicrosoft, 2017 CatBoostYandex, 2017

XGBoost is the best-known member of the gradient boosting family. LightGBM grows trees leaf-wise and is often faster on very large data. CatBoost handles categorical features natively and is strong with little tuning.

XGBoost, gradient boosting परिवार का सबसे जाना-माना सदस्य है। LightGBM trees को leaf-wise उगाता है और बहुत बड़े data पर अक्सर तेज़ है। CatBoost categorical features को खुद संभालता है और कम tuning में अच्छा करता है।

XGBoost 是梯度提升家族中最知名的成员。LightGBM 按叶子生长,在超大数据上通常更快。CatBoost 原生处理类别特征,几乎不调参也表现很好。


SectionSection第 12 节

Boosting vs Random Forest — When to Use WhichBoosting vs Random Forest — कब कौन-साBoosting vs Random Forest — 何时用哪个

Dimensionपहलू方面Random ForestXGBoost / Gradient Boosting
How trees are builtTrees कैसे बनते हैं如何建树Parallel, independentParallel, independent并行、独立One after another, each fixes the lastएक के बाद एक, हर tree पिछले को सुधारता है逐个构建,每棵修正上一棵
What it reducesक्या घटाता है降低什么VarianceVarianceVarianceBias (and variance through regularisation)Bias (और regularisation से variance)Bias(通过正则化也降低 variance)
Overfitting riskOverfitting का ख़तरा过拟合风险Lowकम低Higher: needs early stoppingज़्यादा: early stopping चाहिए较高:需要 early stopping
Training speedTraining speed训练速度Fast, easy to paralleliseतेज़, आसानी से parallel快,易并行Rounds are sequential (each tree is built in parallel)Rounds sequential हैं (हर tree parallel में बनता है)轮次是串行的(每棵树内部并行)
Sensitivity to settingsSettings के प्रति sensitivity对参数的敏感度Low: defaults work wellकम: defaults अच्छे हैं低:默认值就很好High: needs tuningज़्यादा: tuning चाहिए高:需要调参
Peak accuracy (tabular)Peak accuracy (tabular)峰值精度(表格)Very goodबहुत अच्छी很好Often the highestअक्सर सबसे ज़्यादा通常最高
Missing valuesMissing values缺失值scikit-learn 1.4+ supports NaN; older versions need imputationscikit-learn 1.4+ NaN support करता है; पुराने versions में imputation चाहिएscikit-learn 1.4+ 支持 NaN;旧版本需要填补Handled nativelyखुद संभालता है原生处理
InterpretabilityInterpretability可解释性Moderate (importance, SHAP)मध्यम (importance, SHAP)中等(重要性、SHAP)Moderate (SHAP)मध्यम (SHAP)中等(SHAP)
Best choice when…सबसे अच्छा जब…最适合…You want a fast, robust baselineआपको तेज़, robust baseline चाहिए需要快速、稳健的 baselineYou want maximum accuracy and can tuneआपको ज़्यादा से ज़्यादा accuracy चाहिए और tuning कर सकते हैं追求最高精度且愿意调参

SectionSection第 13 节

Common Mistakes & How to Avoid Themआम गलतियाँ और उनसे कैसे बचें常见错误及避免方法

❌ What People Do Wrongलोग क्या गलत करते हैं常见错误做法
Use the defaults learning_rate=0.3, n_estimators=100 without early stopping: the model ends up under- or over-trained.
Early stopping के बिना defaults learning_rate=0.3, n_estimators=100 इस्तेमाल करना: model या तो कम या ज़्यादा train होता है।
不用 early stopping,直接用默认的 learning_rate=0.3、n_estimators=100:model 不是欠训练就是过训练。
Scale features before XGBoost. Trees do not care about scale. It wastes time and can add bugs.
XGBoost से पहले features scale करना। Trees को scale से फ़र्क नहीं पड़ता। समय बर्बाद होता है और bugs आ सकते हैं।
在 XGBoost 之前缩放特征。树不关心尺度,这只会浪费时间,还可能引入 bug。
Grid-search n_estimators by hand. Very wasteful: early stopping does it for free.
n_estimators को हाथ से grid-search करना। बहुत बर्बादी: early stopping यह मुफ़्त में करता है।
手动网格搜索 n_estimators。非常浪费:early stopping 可以免费做到。
Early-stop on the test set, then report the test score. The test set leaked into training.
Test set पर early-stop करना और फिर test score report करना। Test set training में leak हो गया।
在测试集上做 early stopping,然后报告测试分数。测试集已经泄漏进训练了。
Use accuracy on imbalanced classes. It hides failure on the rare class.
Imbalanced classes पर accuracy इस्तेमाल करना। यह rare class पर विफलता छिपा देता है।
在类别不平衡时用 accuracy,它会掩盖少数类上的失败。
✅ What to Do Insteadइसके बजाय क्या करें正确做法
Use learning_rate=0.05–0.1, a high n_estimators, and early_stopping_rounds=30–50 on a validation set.
Validation set पर learning_rate=0.05–0.1, ऊँचा n_estimators, और early_stopping_rounds=30–50 इस्तेमाल करें।
在验证集上使用 learning_rate=0.05–0.1、较大的 n_estimators 和 early_stopping_rounds=30–50。
Feed raw numbers directly. Encode text categories as integers, or use enable_categorical=True with pandas category columns.
Raw numbers सीधे दें। Text categories को integers में बदलें, या pandas category columns के साथ enable_categorical=True इस्तेमाल करें।
直接输入原始数值。把文本类别编码成整数,或对 pandas category 列使用 enable_categorical=True。
Set n_estimators high and let early stopping pick the round.
n_estimators ऊँचा रखें और early stopping को round चुनने दें।
把 n_estimators 设大,让 early stopping 选择轮次。
Split train / validation / test. Early-stop on validation. Touch the test set once. (XGBoost has no OOB score; use cross-validation.)
Train / validation / test अलग करें। Validation पर early-stop करें। Test set को एक बार छुएँ। (XGBoost में OOB score नहीं है; cross-validation इस्तेमाल करें।)
划分训练 / 验证 / 测试集。在验证集上 early stop,只用一次测试集。(XGBoost 没有 OOB 分数,请用交叉验证。)
Set scale_pos_weight = neg / pos and judge with ROC-AUC, PR-AUC or F1.
scale_pos_weight = neg / pos रखें और ROC-AUC, PR-AUC या F1 से परखें।
设 scale_pos_weight = neg / pos,用 ROC-AUC、PR-AUC 或 F1 来评估。

SectionSection第 14 节

Golden RulesGolden Rules黄金法则

⚡ XGBoost & Boosting — Rules to RememberXGBoost और Boosting — याद रखने के नियमXGBoost 与 Boosting — 必记规则
1
Always use early stopping. Set n_estimators high and early_stopping_rounds=30–50 on a validation set. Stop on a smooth metric like logloss. Do not grid-search the number of trees.
हमेशा early stopping इस्तेमाल करें। Validation set पर n_estimators ऊँचा और early_stopping_rounds=30–50 रखें। logloss जैसे smooth metric पर रोकें। Trees की संख्या को grid-search न करें।
始终使用 early stopping。 在验证集上把 n_estimators 设大,并设 early_stopping_rounds=30–50。用 logloss 这类平滑指标来停止。不要网格搜索树的数量。
2
Prefer a low learning rate for the final model. learning_rate=0.05 with more trees usually matches or beats 0.3 with fewer, and it is far more forgiving about when you stop (see the learning-rate race). Optuna also picked η ≈ 0.015 on Titanic.
Final model के लिए कम learning rate रखें। learning_rate=0.05 और ज़्यादा trees आमतौर पर 0.3 और कम trees के बराबर या बेहतर होते हैं, और रुकने के समय को लेकर बहुत ज़्यादा माफ़ करने वाले हैं (learning-rate race देखें)। Titanic पर Optuna ने भी η ≈ 0.015 चुना।
最终 model 用较低的学习率。 learning_rate=0.05 配更多树,通常不输于甚至胜过 0.3 配更少树,而且对何时停止宽容得多(见学习率赛跑)。在 Titanic 上 Optuna 也选择了 η ≈ 0.015。
3
Add row and column sampling. subsample=0.8 and colsample_bytree=0.7 make trees less alike and usually reduce overfitting at little cost.
Row और column sampling जोड़ें। subsample=0.8 और colsample_bytree=0.7 trees को कम एक जैसा बनाते हैं और आमतौर पर कम कीमत पर overfitting घटाते हैं।
加入行和列抽样。 subsample=0.8 和 colsample_bytree=0.7 让树之间差异更大,通常以很小的代价减少过拟合。
4
You do not need to impute missing values. XGBoost learns a default direction for NaN at every split. Imputing first can even hide useful signal, because "missing" itself can carry information. Test both if unsure.
Missing values impute करने की ज़रूरत नहीं। XGBoost हर split पर NaN के लिए default direction सीखता है। पहले impute करने से उपयोगी signal छिप भी सकता है, क्योंकि "missing" होना खुद जानकारी दे सकता है। शक हो तो दोनों test करें।
不需要填补缺失值。 XGBoost 在每个分裂上都会为 NaN 学习默认方向。先填补反而可能掩盖有用信号,因为"缺失"本身就可能带有信息。不确定时两种都试试。
5
Keep tree_method='hist'. It is the default since XGBoost 2.0, much faster than 'exact' on large data, and its accuracy is almost always the same.
tree_method='hist' रखें। यह XGBoost 2.0 से default है, बड़े data पर 'exact' से बहुत तेज़ है, और इसकी accuracy लगभग हमेशा वही रहती है।
保持 tree_method='hist'。 从 XGBoost 2.0 开始它就是默认值,在大数据上比 'exact' 快得多,精度几乎总是一样。
6
Use SHAP over built-in importance. "weight" importance is biased (it ranked Fare first on Titanic). Use shap.TreeExplainer for anything you show to stakeholders or put into production.
Built-in importance के बजाय SHAP इस्तेमाल करें। "weight" importance पक्षपाती है (Titanic पर इसने Fare को पहले रखा)। Stakeholders को दिखाई जाने वाली या production में जाने वाली हर चीज़ के लिए shap.TreeExplainer इस्तेमाल करें।
用 SHAP 代替内置重要性。 "weight" 重要性有偏差(在 Titanic 上它把 Fare 排第一)。任何要给相关方看或要上线的内容,都用 shap.TreeExplainer。
7
Start with Random Forest as the baseline. It is fast, robust and competitive with zero tuning. Move to XGBoost when you need the extra accuracy and can spend time tuning. Many production systems run Random Forest happily.
Random Forest को baseline के रूप में शुरू करें। यह तेज़, robust और बिना tuning के competitive है। जब आपको ज़्यादा accuracy चाहिए और tuning पर समय दे सकें, तब XGBoost पर जाएँ। कई production systems Random Forest पर ही अच्छे से चलते हैं।
先用 Random Forest 作为 baseline。 它速度快、稳健,不调参也很有竞争力。当你需要更高精度并愿意花时间调参时,再换成 XGBoost。很多生产系统一直用 Random Forest 也运行得很好。