Machine Learning 📂 Supervised Learning · 18 of 19 137 min read

Gradient Boosting

A deep-dive into Gradient Boosting from first principles, covering how trees are built sequentially, loss functions, regularisation, and every major hyperparameter tuning strategy: Grid Search, Random Search, Optuna, and Bayesian Optimisation — with working Python code, stories, and visual diagrams.

🌐
SectionSection第 01 节

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

The Student Who Learns Only From Mistakesवह Student जो सिर्फ़ गलतियों से सीखती है只从错误中学习的学生
A student sits an exam in rounds. In Round 1 she scores 60/100. Her teacher does not throw the answer sheet away. The teacher circles only the questions she got wrong and hands them back. In Round 2 she studies only those wrong answers and improves. In Round 3 she studies the errors that are still left.

After ten rounds, each one focused on the last round's mistakes, she scores 98/100. The teacher never re-taught everything from scratch. She only corrected what was wrong.

That is the whole logic of Gradient Boosting. Each new tree does not learn the original target. It learns the residual errors (the mistakes) left by all the previous trees together. Add them all up, and you get a very accurate model.
एक student rounds में परीक्षा देती है। Round 1 में उसके 60/100 आते हैं। Teacher answer sheet फेंकता नहीं। वह सिर्फ़ गलत सवालों पर घेरा लगाकर उसे लौटा देता है। Round 2 में वह सिर्फ़ उन गलत जवाबों को पढ़ती है और सुधरती है। Round 3 में वह बची हुई गलतियाँ पढ़ती है।

दस rounds के बाद, जिनमें हर round पिछली गलतियों पर था, उसके 98/100 आते हैं। Teacher ने कभी सब कुछ शुरू से नहीं पढ़ाया। उसने सिर्फ़ वही सुधारा जो गलत था।

यही Gradient Boosting का पूरा तर्क है। हर नया tree असली target नहीं सीखता। वह पिछले सभी trees की मिली-जुली residual errors (गलतियाँ) सीखता है। सबको जोड़ दें, तो एक बहुत सटीक model मिलता है।
一个学生分几轮参加考试。第 1 轮她得了 60/100。老师没有把答卷扔掉,而是只圈出她做错的题还给她。第 2 轮她只复习这些错题,成绩提高了。第 3 轮她再复习剩下的错误。

十轮之后,每一轮都只针对上一轮的错误,她考到了 98/100。老师从来没有从头重讲一切。她只纠正了错的地方。

这就是 Gradient Boosting 的全部逻辑。每棵新树学的不是原始目标,而是前面所有树加起来之后剩下的残差(错误)。把它们全部加起来,就得到一个非常准确的 model。

Gradient Boosting is a sequential ensemble method. It builds a series of small, shallow decision trees. Each tree is trained to fix the combined error of all the trees before it. Random Forest builds trees independently and in parallel. Gradient Boosting is sequential: each tree depends on the ones before it.

Gradient Boosting एक sequential ensemble method है। यह छोटे, shallow decision trees की एक श्रृंखला बनाता है। हर tree को पिछले सभी trees की मिली-जुली error ठीक करने के लिए train किया जाता है। Random Forest trees को अलग-अलग और parallel में बनाता है। Gradient Boosting sequential है: हर tree पिछले trees पर निर्भर है।

Gradient Boosting 是一种串行的 ensemble 方法。它构建一系列又小又浅的决策树,每棵树都被训练来修正前面所有树的总误差。Random Forest 独立、并行地建树,而 Gradient Boosting 是串行的:每棵树都依赖前面的树。

🌲
Why "Gradient"?"Gradient" क्यों?为什么叫"Gradient"?

The gradient of the loss function tells us which way to change each prediction to reduce the error fastest. Each new tree is fit to the negative gradient of the loss. For squared-error regression, that is simply the residual. The same recipe works for any differentiable loss, which makes the method very flexible.

Loss function का gradient बताता है कि error सबसे तेज़ी से घटाने के लिए हर prediction को किस ओर बदलें। हर नया tree loss के negative gradient पर fit होता है। Squared-error regression में यह बस residual है। यही तरीका किसी भी differentiable loss पर काम करता है, इसलिए यह method बहुत flexible है।

损失函数的梯度告诉我们,每个预测应往哪个方向改变才能最快降低误差。每棵新树拟合的是 loss 的负梯度。对平方误差回归,它就是残差。同样的方法适用于任何可微 loss,所以这个方法非常灵活。


SectionSection第 02 节

Boosting vs Bagging — Two Different PhilosophiesBoosting vs Bagging — दो अलग सोचBoosting vs Bagging — 两种不同的思路

Both boosting and bagging combine many models. But how they combine them is very different.

Boosting और bagging दोनों कई models जोड़ते हैं। पर वे उन्हें कैसे जोड़ते हैं, यह बहुत अलग है।

Boosting 和 bagging 都组合多个 model,但组合方式截然不同。

🎲 Bagging (e.g. Random Forest)Bagging (जैसे Random Forest)Bagging(如 Random Forest)
Propertyगुण属性Detailविवरण详情
Tree orderTrees का क्रम建树顺序Parallel: all trees built independentlyParallel: सभी trees अलग-अलग बनते हैं并行:所有树独立构建
Each tree trains onहर tree किस पर train होता है每棵树训练于A random bootstrap sample of the dataData का random bootstrap sample数据的随机 bootstrap 样本
Error focusError पर ध्यान关注错误No: each tree sees the full targetनहीं: हर tree पूरा target देखता है否:每棵树都看完整目标
DepthDepth深度Deep trees (low bias, high variance)Deep trees (कम bias, ज़्यादा variance)深树(低 bias,高 variance)
Mainly reducesमुख्य रूप से घटाता है主要降低Variance
Parallel?Parallel?可并行?✓ Yes, easily✓ हाँ, आसानी से✓ 是,很容易
🎯 Boosting (Gradient Boosting)Boosting (Gradient Boosting)Boosting(Gradient Boosting)
Propertyगुण属性Detailविवरण详情
Tree orderTrees का क्रम建树顺序Sequential: each tree follows the lastSequential: हर tree पिछले के बाद串行:每棵树紧跟上一棵
Each tree trains onहर tree किस पर train होता है每棵树训练于Residuals (pseudo-residuals) of the trees so farअब तक के trees के residuals (pseudo-residuals)目前所有树的残差(伪残差)
Error focusError पर ध्यान关注错误Yes: each tree fixes earlier mistakesहाँ: हर tree पिछली गलतियाँ सुधारता है是:每棵树修正之前的错误
DepthDepth深度Shallow trees (depth 3–5)Shallow trees (depth 3–5)浅树(深度 3–5)
Mainly reducesमुख्य रूप से घटाता है主要降低Bias (variance is controlled by shrinkage and subsampling)Bias (variance को shrinkage और subsampling से नियंत्रित किया जाता है)Bias(variance 由 shrinkage 和子抽样控制)
Parallel?Parallel?可并行?✗ Not across rounds (each tree can be built in parallel)✗ Rounds के बीच नहीं (हर tree parallel में बन सकता है)✗ 轮次之间不行(单棵树内部可并行)
🎯 BIAS VS VARIANCE — HOW EACH METHOD GETS TO THE CENTREBIAS VS VARIANCE — हर METHOD केंद्र तक कैसे पहुँचता हैBIAS VS VARIANCE — 每种方法如何到达靶心
Bias and variance Low varianceकम variance低 variance High varianceज़्यादा variance高 variance Low biasकम bias低 bias High biasज़्यादा bias高 bias Accurate & consistent — the goalसटीक और स्थिर — लक्ष्य准确且稳定 — 目标 Centred but scattered — overfittingबीच में पर बिखरे — overfitting居中但分散 — 过拟合 Consistent but off — underfittingस्थिर पर गलत — underfitting稳定但偏离 — 欠拟合 Off and scattered — worst caseगलत और बिखरे — सबसे बुरा偏离且分散 — 最差 Random Forest: averagingRandom Forest: averagingRandom Forest:取平均 deep trees → less variancedeep trees → कम variance深树 → 更低 variance Gradient Boosting:Gradient Boosting:Gradient Boosting: shallow trees,shallow trees,浅树, rounds → less biasrounds → कम bias多轮 → 更低 bias

Random Forest starts with deep trees: centred but scattered (top right). Averaging pulls the shots together. Gradient Boosting starts with shallow trees: consistent but off target (bottom left). Each round removes bias and moves the shots toward the centre.

Random Forest deep trees से शुरू करता है: बीच में पर बिखरे (ऊपर दाएँ)। Averaging निशानों को पास लाती है। Gradient Boosting shallow trees से शुरू करता है: स्थिर पर निशाने से दूर (नीचे बाएँ)। हर round bias हटाता है और निशानों को केंद्र की ओर ले जाता है।

Random Forest 从深树出发:居中但分散(右上)。取平均把落点拉到一起。Gradient Boosting 从浅树出发:稳定但偏离靶心(左下)。每一轮都消除一部分 bias,把落点推向中心。

🔐
The Key Insightमुख्य बात关键点

Random Forest reduces variance by averaging many different trees. Gradient Boosting reduces bias by fixing errors round after round. That is why GB can fit complex patterns that Random Forest misses, and also why it overfits more easily if you do not tune it.

Random Forest कई अलग trees का average लेकर variance घटाता है। Gradient Boosting round दर round errors ठीक करके bias घटाता है। इसीलिए GB वे complex patterns पकड़ सकता है जो Random Forest से छूट जाते हैं, और इसीलिए tuning न करने पर यह ज़्यादा आसानी से overfit भी करता है।

Random Forest 通过平均许多不同的树来降低 variance。Gradient Boosting 通过一轮又一轮地修正错误来降低 bias。这就是 GB 能拟合 Random Forest 抓不到的复杂模式的原因,也是不调参时它更容易过拟合的原因。


SectionSection第 03 节

The Algorithm — Step by StepAlgorithm — Step by Step算法 — 逐步讲解

Let's walk through the algorithm with a regression problem: predicting house prices.

आइए algorithm को एक regression problem से समझें: घरों की कीमत predict करना।

我们用一个回归问题来讲解算法:预测房价。

01
Start with a constant predictionएक constant prediction से शुरू करें从常数预测开始
The model starts with the simplest guess: the mean of the target (for classification, the log-odds). If the average house costs ₹28 lakh, every house is first predicted at ₹28 lakh. This is F₀(x) = ȳ.
Model सबसे सरल अनुमान से शुरू करता है: target का mean (classification में log-odds)। अगर औसत घर ₹28 lakh का है, तो पहले हर घर ₹28 lakh predict होता है। यह है F₀(x) = ȳ.
model 从最简单的猜测开始:目标的均值(分类时是 log-odds)。如果平均房价是 ₹28 lakh,那么一开始每套房子都预测为 ₹28 lakh。这就是 F₀(x) = ȳ。
02
Compute the residualsResiduals निकालें计算残差
For each row: rᵢ = yᵢ − F(xᵢ). A house worth ₹40 lakh has residual +₹12 lakh. One worth ₹18 lakh has residual −₹10 lakh. These are the current mistakes.
हर row के लिए: rᵢ = yᵢ − F(xᵢ). ₹40 lakh के घर का residual +₹12 lakh है। ₹18 lakh वाले का −₹10 lakh. ये अभी की गलतियाँ हैं।
对每一行:rᵢ = yᵢ − F(xᵢ)。价值 ₹40 lakh 的房子残差为 +₹12 lakh,价值 ₹18 lakh 的房子残差为 −₹10 lakh。这些就是当前的错误。
03
Fit a shallow tree to the residualsResiduals पर एक shallow tree fit करें用浅树拟合残差
Train a small tree (depth 3–5) with the residuals as the new target, not the prices. It learns "how wrong is the model for this house?"
Prices नहीं, residuals को नया target बनाकर एक छोटा tree (depth 3–5) train करें। यह सीखता है "इस घर के लिए model कितना गलत है?"
用残差(而不是价格)作为新目标训练一棵小树(深度 3–5)。它学的是"model 对这套房子错了多少?"
04
Add the tree, scaled downTree को छोटा करके जोड़ें缩小后加入树
Multiply the tree's output by the learning rate η (e.g. 0.1), then add it: F₁(x) = F₀(x) + η · h₁(x). So no single tree can take over.
Tree के output को learning rate η (जैसे 0.1) से गुणा करें, फिर जोड़ें: F₁(x) = F₀(x) + η · h₁(x). इससे कोई एक tree हावी नहीं हो पाता।
把树的输出乘以学习率 η(如 0.1)后再加上:F₁(x) = F₀(x) + η · h₁(x)。这样任何一棵树都无法主导。
05
Recompute the residualsResiduals फिर से निकालें重新计算残差
With the updated model F₁(x), compute new residuals. They are smaller now. The next tree learns these.
Updated model F₁(x) से नए residuals निकालें। अब वे छोटे हैं। अगला tree इन्हें सीखता है।
用更新后的 model F₁(x)计算新的残差,它们变小了。下一棵树学习这些残差。
06
Repeat M timesM बार दोहराएँ重复 M 次
Repeat steps 2–5. Final model: F(x) = F₀ + η·h₁ + η·h₂ + … + η·h_M. Stop when the validation error stops improving.
Steps 2–5 दोहराएँ। Final model: F(x) = F₀ + η·h₁ + η·h₂ + … + η·h_M. जब validation error सुधरना बंद हो, रुक जाएँ।
重复第 2–5 步。最终 model:F(x) = F₀ + η·h₁ + η·h₂ + … + η·h_M。当验证误差不再改善时停止。
LIVELIVE互动One House, Round by Roundएक घर, Round दर Round一套房子,逐轮演示

The house is worth ₹40 lakh. The model starts at ₹28 lakh. Each tree predicts about 92% of the current residual, and we add η times that. Bars = residual after each round (red = too low, blue = too high). Try η above 1.1.

घर ₹40 lakh का है। Model ₹28 lakh से शुरू करता है। हर tree मौजूदा residual का लगभग 92% predict करता है, और हम उसका η गुना जोड़ते हैं। Bars = हर round के बाद residual (लाल = बहुत कम, नीला = बहुत ज़्यादा)। η को 1.1 से ऊपर आज़माएँ।

房子价值 ₹40 lakh,model 从 ₹28 lakh 开始。每棵树预测当前残差的约 92%,我们加上它的 η 倍。柱子 = 每轮后的残差(红 = 偏低,蓝 = 偏高)。试试 η 大于 1.1。

RoundRound轮次
PredictionPrediction预测
ResidualResidual残差
₹20 L  →  ₹50 L   (true price ₹40 Lअसली कीमत ₹40 L真实价格 ₹40 L)

🏅
Concrete Numeric Example (η = 0.1)ठोस Numeric उदाहरण (η = 0.1)具体数字例子(η = 0.1)

One house is worth ₹40 lakh.
Round 0: constant prediction ₹28 lakh → residual +₹12 lakh.
Round 1: the tree predicts ₹11 lakh → 28 + 0.1 × 11 = ₹29.1 lakh (residual now 10.9).
Round 2: the tree predicts ₹10 lakh → 29.1 + 0.1 × 10 = ₹30.1 lakh.
Each round closes about 9% of the remaining gap, so after a few dozen rounds the prediction is close to ₹40 lakh. Small, steady steps toward the truth.

एक घर की कीमत ₹40 lakh है।
Round 0: constant prediction ₹28 lakh → residual +₹12 lakh.
Round 1: tree ₹11 lakh predict करता है → 28 + 0.1 × 11 = ₹29.1 lakh (अब residual 10.9)।
Round 2: tree ₹10 lakh predict करता है → 29.1 + 0.1 × 10 = ₹30.1 lakh.
हर round बचे हुए अंतर का लगभग 9% भरता है, इसलिए कुछ दर्जन rounds के बाद prediction ₹40 lakh के पास होता है। सच की ओर छोटे, स्थिर कदम।

一套房子价值 ₹40 lakh。
第 0 轮:常数预测 ₹28 lakh → 残差 +₹12 lakh。
第 1 轮:树预测 ₹11 lakh → 28 + 0.1 × 11 = ₹29.1 lakh(残差变为 10.9)。
第 2 轮:树预测 ₹10 lakh → 29.1 + 0.1 × 10 = ₹30.1 lakh。
每一轮缩小剩余差距的约 9%,所以几十轮后预测就接近 ₹40 lakh。小而稳的步子,一步步接近真相。


SectionSection第 04 节

The Mathematics — What "Gradient" Actually Meansगणित — "Gradient" का असली मतलब数学 — "梯度"到底是什么意思

Gradient Boosting is gradient descent in function space. A neural network uses gradients to update its parameters. Gradient Boosting uses gradients to update the predictions directly, step by step, in the direction that lowers the loss most.

Gradient Boosting function space में gradient descent है। Neural network gradients से अपने parameters update करता है। Gradient Boosting gradients से सीधे predictions को, step दर step, उस दिशा में update करता है जहाँ loss सबसे ज़्यादा घटता है।

Gradient Boosting 是函数空间中的梯度下降。神经网络用梯度更新参数,而 Gradient Boosting 用梯度直接一步步更新预测值,朝着让 loss 下降最快的方向。

Loss (regression)Loss (regression)Loss(回归)
L(y, F) = ½ (y − F)²
Squared error. The residual is rᵢ = yᵢ − F(xᵢ), and each tree fits it directly.
Squared error. Residual है rᵢ = yᵢ − F(xᵢ), और हर tree इसे सीधे fit करता है।
平方误差。残差是 rᵢ = yᵢ − F(xᵢ),每棵树直接拟合它。
Negative gradient (general)Negative gradient (सामान्य)负梯度(一般形式)
rᵢ = − ∂L(yᵢ, F(xᵢ)) / ∂F(xᵢ)
For any loss L, the pseudo-residual is the negative gradient of L with respect to the current prediction. This is what the next tree learns.
किसी भी loss L के लिए pseudo-residual, मौजूदा prediction के सापेक्ष L का negative gradient है। अगला tree यही सीखता है।
对任何 loss L,伪残差就是 L 对当前预测的负梯度。下一棵树学的就是它。
Update ruleUpdate rule更新规则
Fₘ(x) = Fₘ₋₁(x) + η · hₘ(x)
η = learning rate (shrinkage). hₘ = the m-th tree, trained on the pseudo-residuals.
η = learning rate (shrinkage)। hₘ = m-वाँ tree, pseudo-residuals पर train किया गया।
η = 学习率(shrinkage)。hₘ = 第 m 棵树,用伪残差训练。
Final modelFinal model最终 model
F(x) = F₀ + Σₘ η · hₘ(x)
The starting constant plus all M scaled trees. No voting, just a sum. (sklearn also fits the best value for each leaf when the loss is not squared error.)
शुरुआती constant और सभी M scaled trees का जोड़। कोई voting नहीं, बस जोड़। (जब loss squared error न हो तो sklearn हर leaf के लिए सबसे अच्छा value भी fit करता है।)
初始常数加上所有 M 棵缩放后的树。没有投票,只是求和。(当 loss 不是平方误差时,sklearn 还会为每个叶子拟合最佳值。)
🔬
Why "Pseudo-Residuals" and Not Just "Residuals"?सिर्फ़ "Residuals" नहीं, "Pseudo-Residuals" क्यों?为什么叫"伪残差"而不只是"残差"?

For squared-error loss, the negative gradient is exactly the plain residual yᵢ − F(xᵢ). For other losses it is something else: for absolute error it is just the sign (±1), and for log-loss it is yᵢ − p̂ᵢ. "Pseudo-residual" is the general name that covers every case. You can see each one in the loss explorer below.

Squared-error loss में negative gradient बिल्कुल साधारण residual yᵢ − F(xᵢ) है। दूसरे losses में यह कुछ और है: absolute error में बस sign (±1), और log-loss में yᵢ − p̂ᵢ. "Pseudo-residual" सामान्य नाम है जो हर case को cover करता है। नीचे loss explorer में आप हर एक देख सकते हैं।

对平方误差 loss,负梯度恰好就是普通残差 yᵢ − F(xᵢ)。对其他 loss 则不同:绝对误差时只是符号(±1),log-loss 时是 yᵢ − p̂ᵢ。"伪残差"是涵盖所有情况的统称。你可以在下面的 loss 探索器里看到每一种。


SectionSection第 05 节

Visual Diagram — The Sequential ProcessVisual Diagram — Sequential प्रक्रिया图解 — 串行过程

📊 HOW GRADIENT BOOSTING BUILDS, ONE TREE AT A TIMEGRADIENT BOOSTING कैसे बनता है, एक-एक TREE करकेGRADIENT BOOSTING 如何一棵一棵地构建
Gradient boosting step by step F₀(x)mean = ₹28 L F₁(x)28 + 0.1×11.0= ₹29.1 L F₂(x)29.1 + 0.1×10.0= ₹30.1 L r = y − F₀+12.0 tree h₁predicts 11.0 r = y − F₁+10.9 tree h₂predicts 10.0 + η·h₁ + η·h₂ … F₀ + Σ η·hₘ final modelfinal model最终 model ≈ ₹40 L ✓ One house worth ₹40 lakh. η = 0.1. Top row: the model so far. Bottom row: what is still wrong, and the tree that learns it.एक घर जिसकी कीमत ₹40 lakh है। η = 0.1. ऊपर: अब तक का model. नीचे: जो अभी भी गलत है, और वह tree जो उसे सीखता है।一套价值 ₹40 lakh 的房子,η = 0.1。上排:目前的 model;下排:仍然错的部分,以及学习它的树。

SectionSection第 06 节

Loss Functions — The Heart of FlexibilityLoss Functions — Flexibility का दिल损失函数 — 灵活性的核心

Gradient Boosting works with any differentiable loss function. The loss decides what counts as a "mistake" and how much each mistake costs.

Gradient Boosting किसी भी differentiable loss function के साथ काम करता है। Loss तय करता है कि "गलती" क्या है और हर गलती की कीमत कितनी है।

Gradient Boosting 适用于任何可微损失函数。loss 决定了什么算"错误",以及每个错误的代价有多大。

📈
Squared Error (MSE)
loss='squared_error'
Default for regression. Pseudo-residuals are exactly yᵢ − Fᵢ. Sensitive to outliers, because big errors are squared.
Regression का default. Pseudo-residuals बिल्कुल yᵢ − Fᵢ हैं। Outliers के प्रति sensitive, क्योंकि बड़ी errors square होती हैं।
回归的默认值。伪残差恰好是 yᵢ − Fᵢ。对 outlier 敏感,因为大误差会被平方。
💷
Absolute Error (MAE)
loss='absolute_error'
Pseudo-residuals are just the sign of the error: ±1. Robust to outliers. Predictions aim at the median.
Pseudo-residuals बस error का sign हैं: ±1. Outliers के प्रति robust. Predictions median की ओर जाते हैं।
伪残差只是误差的符号:±1。对 outlier 稳健,预测趋向中位数。
💡
Huber Loss
loss='huber'
Squared for small errors, linear for large ones. Robust, but still efficient on clean data. In sklearn, alpha sets the switch point as a quantile of the errors.
छोटी errors के लिए squared, बड़ी के लिए linear. Robust, पर साफ़ data पर भी efficient. sklearn में alpha errors के quantile के रूप में switch point तय करता है।
小误差取平方,大误差取线性。稳健,在干净数据上也高效。在 sklearn 中,alpha 以误差分位数的形式设定切换点。
📋
Log-Loss (Deviance)
loss='log_loss'
For binary and multiclass classification (the default). Pseudo-residuals are yᵢ − p̂ᵢ, where p̂ is the current predicted probability.
Binary और multiclass classification के लिए (default)। Pseudo-residuals हैं yᵢ − p̂ᵢ, जहाँ p̂ मौजूदा predicted probability है।
用于二分类和多分类(默认)。伪残差是 yᵢ − p̂ᵢ,p̂ 是当前预测概率。
📊
Exponential Loss
loss='exponential'
Turns gradient boosting into AdaBoost (binary only). Very sensitive to outliers and label noise; log-loss is usually better.
Gradient boosting को AdaBoost बना देता है (सिर्फ़ binary)। Outliers और label noise के प्रति बहुत sensitive; log-loss आमतौर पर बेहतर है।
让梯度提升变成 AdaBoost(仅二分类)。对 outlier 和标签噪声非常敏感,通常 log-loss 更好。
🔄
Quantile Loss
loss='quantile'
Predicts a chosen percentile. Train two models (e.g. 10th and 90th) to get a prediction interval. Great for forecasting with uncertainty.
चुना हुआ percentile predict करता है। Prediction interval के लिए दो models (जैसे 10th और 90th) train करें। Uncertainty के साथ forecasting के लिए बढ़िया।
预测指定的百分位数。训练两个 model(如第 10 和第 90 百分位)即可得到预测区间。非常适合带不确定性的预测。
LIVELIVE互动Loss Function ExplorerLoss Function Explorer损失函数探索器

Left: the loss curve (solid) and its pseudo-residual (dashed). Right: 8 normal values and 1 outlier (red). The thick line is the single best constant prediction under the chosen loss. Drag the outlier and watch which losses follow it.

बाएँ: loss curve (solid) और उसका pseudo-residual (dashed)। दाएँ: 8 सामान्य values और 1 outlier (लाल)। मोटी line चुने गए loss के तहत सबसे अच्छा एक constant prediction है। Outlier को खिसकाएँ और देखें कौन से losses उसके पीछे जाते हैं।

左:loss 曲线(实线)及其伪残差(虚线)。右:8 个正常值和 1 个 outlier(红色)。粗线是所选 loss 下最好的单个常数预测。拖动 outlier,看哪些 loss 会被它带走。

Loss L(r)Loss L(r)Loss L(r)Pseudo-residual −∂L/∂F (dashed)Pseudo-residual −∂L/∂F (dashed)伪残差 −∂L/∂F(虚线)

Best constantसबसे अच्छा constant最佳常数:

🎯
Which Loss Should You Use?कौन-सा Loss इस्तेमाल करें?该用哪种 Loss?

Regression on clean data: squared_error. Regression with outliers: huber or absolute_error. Classification: log_loss (the default). Prediction intervals: quantile, with two separate models.

साफ़ data पर regression: squared_error. Outliers वाला regression: huber या absolute_error. Classification: log_loss (default)। Prediction intervals: दो अलग models के साथ quantile.

干净数据的回归:squared_error。有 outlier 的回归:huber 或 absolute_error。分类:log_loss(默认)。预测区间:用两个独立 model 的 quantile。


SectionSection第 07 节

Key Hyperparameters — The Control Panelमुख्य Hyperparameters — Control Panel关键超参数 — 控制面板

🍎 Family 1 — Ensemble Structure🍎 Family 1 — Ensemble का ढाँचा🍎 第 1 类 — 集成结构

ParameterDefaultWhat it controlsक्या नियंत्रित करता है控制什么Practical adviceव्यावहारिक सलाह实用建议
n_estimators100Number of trees (boosting rounds)Trees (boosting rounds) की संख्या树的数量(提升轮数)Set high (300–3000) and let early stopping find the right number.ऊँचा रखें (300–3000) और early stopping को सही संख्या खोजने दें।设大(300–3000),让 early stopping 找到合适的数量。
learning_rate (η)0.1Shrinkage applied to each treeहर tree पर लगने वाला shrinkage每棵树的缩放系数Lower usually generalises better but needs more trees. Typical: 0.01–0.1.कम आमतौर पर बेहतर generalise करता है पर ज़्यादा trees चाहिए। आमतौर पर: 0.01–0.1.越低通常泛化越好,但需要更多树。常用:0.01–0.1。
losstask-basedtask पर निर्भर取决于任务The loss being minimisedजिस loss को कम किया जा रहा है被最小化的 lossMatch it to your task: squared_error, log_loss, huber, quantile.अपने task से मिलाएँ: squared_error, log_loss, huber, quantile.与任务匹配:squared_error、log_loss、huber、quantile。

🌵 Family 2 — Tree Structure (Complexity)🌵 Family 2 — Tree का ढाँचा (Complexity)🌵 第 2 类 — 树结构(复杂度)

ParameterDefaultWhat it controlsक्या नियंत्रित करता है控制什么Practical adviceव्यावहारिक सलाह实用建议
max_depth3Depth of each treeहर tree की depth每棵树的深度Keep it shallow. 3–5 is ideal; above 6 rarely helps and often overfits.Shallow रखें। 3–5 आदर्श है; 6 से ऊपर शायद ही मदद करता है और अक्सर overfit करता है।保持浅。3–5 最理想;超过 6 很少有帮助,还常常过拟合。
min_samples_leaf1Minimum rows in a leafLeaf में न्यूनतम rows叶子的最少样本数Raise to 5–20 on noisy or small data.Noisy या छोटे data पर 5–20 तक बढ़ाएँ।数据噪声大或数据量小时调到 5–20。
max_featuresNoneFeatures tried at each splitहर split पर आज़माए गए features每次分裂考虑的特征数'sqrt' or 0.3–0.7 adds randomness and reduces overfitting.'sqrt' या 0.3–0.7 randomness जोड़ता है और overfitting घटाता है।'sqrt' 或 0.3–0.7 增加随机性,减少过拟合。
max_leaf_nodesNoneMaximum number of leavesLeaves की अधिकतम संख्या叶子的最大数量An alternative to max_depth. Try 8–64.max_depth का विकल्प। 8–64 आज़माएँ।max_depth 的替代方案。试试 8–64。

🎗 Family 3 — Randomness and Early Stopping🎗 Family 3 — Randomness और Early Stopping🎗 第 3 类 — 随机性与 Early Stopping

ParameterDefaultWhat it controlsक्या नियंत्रित करता है控制什么Practical adviceव्यावहारिक सलाह实用建议
subsample1.0Share of rows used per treeहर tree के लिए rows का हिस्सा每棵树使用的行比例0.6–0.8 turns on Stochastic GB and usually reduces overfitting.0.6–0.8 Stochastic GB चालू करता है और आमतौर पर overfitting घटाता है।0.6–0.8 开启随机梯度提升,通常可减少过拟合。
validation_fraction0.1Share of training data held out for early stoppingEarly stopping के लिए अलग रखा गया training data为 early stopping 留出的训练数据比例Only used when n_iter_no_change is set.तभी इस्तेमाल होता है जब n_iter_no_change set हो।只有设置了 n_iter_no_change 才会使用。
n_iter_no_changeNoneEarly-stopping patienceEarly-stopping का धैर्यearly stopping 的耐心值Set 10–25. Training stops when the validation score stops improving.10–25 रखें। Validation score सुधरना बंद होने पर training रुक जाती है।设为 10–25。验证分数不再提升时训练停止。

SectionSection第 08 节

Shrinkage — The Most Important Tuning DecisionShrinkage — Tuning का सबसे ज़रूरी फ़ैसलाShrinkage — 最重要的调参决定

The Surgeon's Steady HandSurgeon का स्थिर हाथ外科医生稳定的手
Two surgeons must correct a 5 mm misalignment in a spine. Surgeon A makes one bold 5 mm correction. Surgeon B makes fifty 0.1 mm corrections, checking after each one.

Surgeon A is faster, but if she overshoots by even 0.5 mm, she causes new damage. Surgeon B takes longer but always knows where she is and does not overshoot.

The learning rate is Surgeon B's method: small steps, constant checking, fewer disasters.
दो surgeons को रीढ़ में 5 mm का टेढ़ापन ठीक करना है। Surgeon A एक बार में 5 mm का साहसी सुधार करती है। Surgeon B पचास बार 0.1 mm का सुधार करती है, हर बार जाँचते हुए।

Surgeon A तेज़ है, पर अगर वह 0.5 mm भी ज़्यादा कर दे तो नया नुकसान होता है। Surgeon B को समय ज़्यादा लगता है पर उसे हमेशा पता रहता है कि वह कहाँ है और वह आगे नहीं निकलती।

Learning rate Surgeon B का तरीका है: छोटे कदम, लगातार जाँच, कम हादसे।
两位外科医生要矫正脊柱 5 毫米的错位。医生 A 一次大胆矫正 5 毫米。医生 B 分五十次、每次矫正 0.1 毫米,每次都检查。

医生 A 更快,但哪怕多矫正 0.5 毫米,也会造成新的伤害。医生 B 用时更长,但始终知道自己在哪,不会矫枉过正。

学习率就是医生 B 的方法:小步前进,持续检查,减少灾难。
➕
More trees neededज़्यादा trees चाहिए需要更多树
n_estimators ↑
With η = 0.01 you need about 10× as many trees as with η = 0.1 to make the same total correction. Training takes longer.
η = 0.01 के साथ उतना ही कुल सुधार पाने के लिए η = 0.1 से लगभग 10 गुना trees चाहिए। Training में ज़्यादा समय लगता है।
η = 0.01 时,要达到同样的总修正量,需要的树大约是 η = 0.1 时的 10 倍,训练更慢。
⚠ Higher compute costज़्यादा compute cost计算成本更高
🌍
Usually better generalisationआमतौर पर बेहतर generalisation通常泛化更好
test score ↑
A lower η makes the model learn gradually, so no single tree can lock in noise. It usually improves held-out scores, though the gain is often small.
कम η से model धीरे-धीरे सीखता है, इसलिए कोई एक tree noise को पक्का नहीं कर पाता। यह आमतौर पर held-out scores सुधारता है, हालाँकि फ़ायदा अक्सर छोटा होता है।
较低的 η 让 model 逐步学习,任何一棵树都无法把噪声固化下来。它通常能提高留出集分数,但提升往往不大。
✓ Lower test error, more forgivingकम test error, ज़्यादा माफ़ करने वाला测试误差更低、更宽容
⚔️
The trade-off ruleTrade-off का नियम权衡规则
η × n_estimators ≈ constant
Halve η and roughly double the trees, and you get similar accuracy with a smoother fit. Let early stopping pick the exact number.
η आधा करें और trees लगभग दोगुने करें, तो smooth fit के साथ लगभग वैसी ही accuracy मिलती है। सही संख्या early stopping को चुनने दें।
η 减半、树大约翻倍,就能得到相近的精度和更平滑的拟合。具体数量交给 early stopping。
✓ Proven in practiceव्यवहार में साबित实践检验过
LIVELIVE互动Learning Rate RaceLearning Rate की दौड़学习率赛跑

Real gradient boosting on the same data with three learning rates (depth 2). Lines = validation error. Dots = each model's lowest point.

एक ही data पर तीन learning rates (depth 2) के साथ असली gradient boosting. Lines = validation error. Dots = हर model का सबसे निचला बिंदु।

在同一数据上用三种学习率(深度 2)运行真实的梯度提升。曲线 = 验证误差,圆点 = 每个 model 的最低点。

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

💡
Friedman's FindingsFriedman के निष्कर्षFriedman 的发现

In his 2001 paper, Jerome Friedman found that small learning rates (below 0.1) with many trees gave clearly better test error than large ones. In 2002 he showed that row subsampling (Stochastic Gradient Boosting, Section 09) helps further. The practical recipe: η around 0.05 or lower, and early stopping to choose the number of trees.

अपने 2001 के paper में Jerome Friedman ने पाया कि छोटे learning rates (0.1 से कम) और कई trees बड़े learning rates से साफ़ तौर पर बेहतर test error देते हैं। 2002 में उन्होंने दिखाया कि row subsampling (Stochastic Gradient Boosting, Section 09) और मदद करता है। व्यावहारिक तरीका: η लगभग 0.05 या कम, और trees की संख्या चुनने के लिए early stopping.

Jerome Friedman 在 2001 年的论文中发现,小学习率(低于 0.1)配合大量的树,测试误差明显好于大学习率。2002 年他又证明行子抽样(随机梯度提升,第 09 节)能进一步提升效果。实用方案:η 约 0.05 或更低,用 early stopping 选择树的数量。


SectionSection第 09 节

Stochastic Gradient Boosting — Adding RandomnessStochastic Gradient Boosting — Randomness जोड़ना随机梯度提升 — 加入随机性

Instead of using all training rows for each tree, use a random subsample of rows (drawn without replacement). The subsample parameter controls this. Any value below 1.0 gives Stochastic Gradient Boosting. Try it in the simulator in Section 10.

हर tree के लिए सारी training rows इस्तेमाल करने के बजाय rows का random subsample (without replacement) लें। subsample parameter इसे नियंत्रित करता है। 1.0 से कम कोई भी value Stochastic Gradient Boosting देती है। इसे Section 10 के simulator में आज़माएँ।

不是每棵树都用全部训练行,而是用随机抽取的子样本(无放回)。这由 subsample 参数控制,小于 1.0 就是随机梯度提升。可以在第 10 节的模拟器里试试。

🔴 Standard GB (subsample = 1.0)Standard GB (subsample = 1.0)标准 GB(subsample = 1.0)
Propertyगुण属性Effectअसर效果
Data per treeहर tree का data每棵树的数据100% of the training setTraining set का 100%训练集的 100%
DeterministicDeterministic确定性Yes (with a fixed seed)हाँ (fixed seed के साथ)是(固定种子时)
Overfitting riskOverfitting का ख़तरा过拟合风险Higher on noisy dataNoisy data पर ज़्यादा噪声数据上更高
Speed per treeहर tree की speed每棵树的速度Slower (more data)धीमा (ज़्यादा data)较慢(数据更多)
BiasSlightly lowerथोड़ा कम略低
VarianceHigherज़्यादा较高
🟢 Stochastic GB (subsample = 0.7)Stochastic GB (subsample = 0.7)随机 GB(subsample = 0.7)
Propertyगुण属性Effectअसर效果
Data per treeहर tree का data每棵树的数据A random 70% of the training setTraining set का random 70%训练集中随机的 70%
DeterministicDeterministic确定性Only with a fixed random_stateसिर्फ़ fixed random_state के साथ仅在固定 random_state 时
Overfitting riskOverfitting का ख़तरा过拟合风险Lower: trees see different dataकम: trees अलग data देखते हैं更低:每棵树看到不同数据
Speed per treeहर tree की speed每棵树的速度Faster (30% less data)तेज़ (30% कम data)更快(数据少 30%)
BiasSlightly higherथोड़ा ज़्यादा略高
VarianceLowerकम较低

SectionSection第 10 节

Overfitting and RegularisationOverfitting और Regularisation过拟合与正则化

🎗 Regularisation Levers — Ranked by ImpactRegularisation के साधन — असर के क्रम में正则化手段 — 按影响排序
1st
Learning rate (η) — Lower η (try 0.01–0.05). The biggest single regulariser. Always pair it with early stopping.η घटाएँ (0.01–0.05 आज़माएँ)। सबसे बड़ा अकेला regulariser. हमेशा early stopping के साथ इस्तेमाल करें।降低 η(试 0.01–0.05)。这是最大的单一正则手段,一定要配合 early stopping。
2nd
max_depth — Keep trees shallow (3–5). Deep trees memorise noise. Depth 3 is a common sweet spot.Trees को shallow रखें (3–5)। Deep trees noise रट लेते हैं। Depth 3 एक आम sweet spot है।保持树浅(3–5)。深树会记住噪声,深度 3 是常见的最佳点。
3rd
subsample — Set 0.6–0.8. Row sampling adds helpful randomness and lowers variance.0.6–0.8 रखें। Row sampling मददगार randomness जोड़ता है और variance घटाता है।设为 0.6–0.8。行抽样带来有益的随机性,降低 variance。
4th
max_features — Sample features per split ('sqrt' or 0.5), like Random Forest does.हर split पर features का sample लें ('sqrt' या 0.5), जैसे Random Forest करता है।每次分裂抽样特征('sqrt' 或 0.5),和 Random Forest 一样。
5th
min_samples_leaf — Raise to 5–20 on noisy data, so each leaf stands for a real pattern.Noisy data पर 5–20 तक बढ़ाएँ, ताकि हर leaf किसी असली pattern को दिखाए।数据噪声大时调到 5–20,让每个叶子代表真实的规律。
6th
Early stopping — Set n_iter_no_change=20 and validation_fraction=0.1. It stops before overfitting, for free.n_iter_no_change=20 और validation_fraction=0.1 रखें। यह overfitting से पहले मुफ़्त में रोक देता है।设 n_iter_no_change=20 和 validation_fraction=0.1。它会在过拟合前免费停下。
LIVELIVE互动Watch It Learn — and Overfitइसे सीखते — और Overfit होते देखें看它学习——以及过拟合

Filled dots = training rows used by the current tree; hollow purple dots = rows left out by subsample. Grey circles = validation data. Red lines = residuals. Change η, depth and subsample, then press Play.

भरे dots = मौजूदा tree द्वारा इस्तेमाल की गई training rows; खोखले बैंगनी dots = subsample से छूटी rows. Grey circles = validation data. लाल lines = residuals. η, depth और subsample बदलें, फिर Play दबाएँ।

实心点 = 当前树使用的训练行;空心紫点 = 被 subsample 排除的行。灰色圆圈 = 验证数据,红线 = 残差。调整 η、深度和 subsample,然后点击播放。

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

⚠️
The Overfitting TrapOverfitting का जाल过拟合陷阱

In Random Forest, more trees do not cause overfitting. In Gradient Boosting, more trees will eventually overfit. A lower learning rate only delays that point; it does not remove it. Always track training and validation loss. If training loss keeps falling while validation loss flattens or rises, you are overfitting. Turn on early stopping.

Random Forest में ज़्यादा trees overfitting नहीं करते। Gradient Boosting में ज़्यादा trees आख़िरकार overfit करेंगे। कम learning rate उस बिंदु को बस आगे खिसकाता है; हटाता नहीं। Training और validation loss दोनों पर नज़र रखें। अगर training loss घटता रहे और validation loss सपाट हो या बढ़े, तो overfitting हो रहा है। Early stopping चालू करें।

在 Random Forest 中,树多不会导致过拟合。在 Gradient Boosting 中,树多了终究会过拟合。较低的学习率只能推迟这个点,不能消除它。一定要同时跟踪训练和验证 loss。如果训练 loss 一直下降而验证 loss 走平或上升,就是过拟合了,请开启 early stopping。


SectionSection第 11 节

Python — scikit-learn GradientBoostingPython — scikit-learn GradientBoostingPython — scikit-learn GradientBoosting

🛠️ Classification: Credit Card Fraud Detection🛠️ Classification: Credit Card Fraud Detection🛠️ 分类:信用卡欺诈检测

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.datasets import make_classification

# Synthetic "credit card fraud" data: 95% legit, 5% fraud
X, y = make_classification(
    n_samples=8000, n_features=20,
    n_informative=12, n_redundant=4,
    weights=[0.95, 0.05],
    random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)

gb = GradientBoostingClassifier(
    n_estimators=500,          # upper limit; early stopping decides
    learning_rate=0.05,        # small steps, better generalisation
    max_depth=4,               # shallow trees
    min_samples_leaf=10,       # regularise leaf size
    subsample=0.75,            # stochastic GB: 75% of rows per tree
    max_features=0.5,          # 50% of features per split
    loss='log_loss',           # binary classification
    validation_fraction=0.1,   # 10% of training data for early stopping
    n_iter_no_change=20,       # stop after 20 rounds with no improvement
    tol=1e-4,
    random_state=42
)
gb.fit(X_train, y_train)

print(f"Trees used (early stopping): {gb.n_estimators_}")
print(f"Test ROC-AUC: {roc_auc_score(y_test, gb.predict_proba(X_test)[:, 1]):.4f}\n")
print(classification_report(y_test, gb.predict(X_test), digits=4))
OUTPUT
Trees used (early stopping): 265 Test ROC-AUC: 0.9428 precision recall f1-score support 0 0.9699 0.9993 0.9844 1513 1 0.9756 0.4598 0.6250 87 accuracy 0.9700 1600 macro avg 0.9727 0.7296 0.8047 1600 weighted avg 0.9702 0.9700 0.9648 1600
🚨
High AUC, Low Recall — Check the Thresholdऊँचा AUC, कम Recall — Threshold जाँचेंAUC 高、召回率低 — 检查阈值

Look at the fraud row: precision 0.98 but recall only 0.46. The model ranks fraud well (AUC 0.94), but at the default 0.5 threshold it catches less than half of the frauds. With only 5% fraud, the predicted probabilities rarely pass 0.5. Accuracy (97%) hides this completely. Lower the threshold to trade some precision for more recall:

Fraud वाली row देखें: precision 0.98 पर recall सिर्फ़ 0.46. Model fraud को अच्छी तरह rank करता है (AUC 0.94), पर default 0.5 threshold पर आधे से भी कम frauds पकड़ता है। सिर्फ़ 5% fraud होने से predicted probabilities शायद ही 0.5 पार करती हैं। Accuracy (97%) इसे पूरी तरह छिपा देती है। ज़्यादा recall के लिए थोड़ी precision छोड़कर threshold घटाएँ:

看欺诈那一行:precision 0.98,但 recall 只有 0.46。model 对欺诈的排序很好(AUC 0.94),但在默认阈值 0.5 下只抓到了不到一半的欺诈。欺诈只占 5%,预测概率很少超过 0.5。accuracy(97%)把这一点完全掩盖了。降低阈值,用一些 precision 换更多 recall:

from sklearn.metrics import precision_score, recall_score

# `gb`, `X_test`, `y_test` come from the fraud example above
proba = gb.predict_proba(X_test)[:, 1]

print(f"{'Threshold':>9} {'Precision':>10} {'Recall':>8} {'Frauds caught':>14}")
for t in [0.5, 0.3, 0.2, 0.1, 0.05]:
    pred = (proba >= t).astype(int)
    caught = int(((pred == 1) & (y_test == 1)).sum())
    print(f"{t:>9} {precision_score(y_test, pred):>10.3f} "
          f"{recall_score(y_test, pred):>8.3f} {caught:>7} / {int(y_test.sum())}")
OUTPUT
Threshold Precision Recall Frauds caught 0.5 0.976 0.460 40 / 87 0.3 0.946 0.609 53 / 87 0.2 0.826 0.655 57 / 87 0.1 0.650 0.747 65 / 87 0.05 0.438 0.805 70 / 87

At a 0.1 threshold the model catches 65 of 87 frauds instead of 40. Pick the threshold from the real cost of a missed fraud versus a false alarm, and choose it on validation data, not the test set.

0.1 threshold पर model 87 में से 40 के बजाय 65 frauds पकड़ता है। Threshold को छूटे fraud बनाम झूठे alarm की असली कीमत से चुनें, और इसे validation data पर चुनें, test set पर नहीं।

阈值为 0.1 时,model 抓到 87 个欺诈中的 65 个,而不是 40 个。阈值应根据漏掉欺诈与误报的真实代价来定,并在验证集上选择,而不是测试集。

📈 Regression: Predicting House Prices📈 Regression: घरों की कीमत Predict करना📈 回归:预测房价

from sklearn.ensemble import GradientBoostingRegressor
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, r2_score

housing = fetch_california_housing()
X, y = housing.data, housing.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
)

gb_reg = GradientBoostingRegressor(
    n_estimators=2000,
    learning_rate=0.05,
    max_depth=4,
    subsample=0.8,
    max_features='sqrt',
    loss='huber',              # robust to outlier prices
    alpha=0.9,                 # Huber switches to linear beyond the 90th percentile of |residual|
    validation_fraction=0.1,
    n_iter_no_change=25,
    random_state=42
)
gb_reg.fit(X_train, y_train)
y_pred = gb_reg.predict(X_test)

print(f"R² Score : {r2_score(y_test, y_pred):.4f}")
print(f"MAE      : ${mean_absolute_error(y_test, y_pred) * 100_000:,.0f}")
print(f"Trees    : {gb_reg.n_estimators_} (early stopped)")
OUTPUT
R² Score : 0.8324 MAE : $30,393 Trees : 1433 (early stopped)

SectionSection第 12 节

LightGBM — Faster, Scalable Gradient BoostingLightGBM — तेज़, Scalable Gradient BoostingLightGBM — 更快、可扩展的梯度提升

LightGBM is Microsoft's high-speed implementation. The residual-fitting logic is the same, but two engineering ideas make it much faster on large data: histogram-based splits and leaf-wise tree growth.

LightGBM Microsoft का तेज़ implementation है। Residual-fitting का तर्क वही है, पर दो engineering ideas इसे बड़े data पर बहुत तेज़ बनाते हैं: histogram-based splits और leaf-wise tree growth.

LightGBM 是微软的高速实现。拟合残差的逻辑相同,但两个工程上的创新让它在大数据上快得多:基于直方图的分裂和按叶生长。

🔴 scikit-learn GradientBoostingscikit-learn GradientBoostingscikit-learn GradientBoosting
Propertyगुण属性Detailविवरण详情
Tree growthTree growth树的生长Depth-first to max_depth (all branches equally deep)max_depth तक (सभी शाखाएँ बराबर गहरी)长到 max_depth(各分支深度相同)
Split findingSplit खोजना寻找分裂点Exact: tries every value of every featureExact: हर feature की हर value आज़माता है精确:尝试每个特征的每个值
Speed on 160k rows (this page)160k rows पर speed (इस page पर)16 万行上的速度(本页)404 s404 s404 秒
Missing values / categoriesMissing values / categories缺失值 / 类别Manual handling neededहाथ से संभालना पड़ता है需要手动处理
🟢 LightGBMLightGBMLightGBM
Propertyगुण属性Detailविवरण详情
Tree growthTree growth树的生长Leaf-wise: always splits the leaf with the biggest gainLeaf-wise: हमेशा सबसे बड़े gain वाली leaf को split करता है按叶:总是分裂增益最大的叶子
Split findingSplit खोजना寻找分裂点Histograms: features binned (255 bins by default)Histograms: features को bins में (default 255 bins)直方图:特征分桶(默认 255 个桶)
Speed on 160k rows (this page)160k rows पर speed (इस page पर)16 万行上的速度(本页)3 s, same AUC3 s, वही AUC3 秒,AUC 相同
Missing values / categoriesMissing values / categories缺失值 / 类别Native (categories via the category dtype)Native (category dtype के ज़रिए)原生支持(类别用 category 类型)
LIVELIVE互动Level-wise vs Leaf-wise Tree GrowthLevel-wise vs Leaf-wise Tree Growth按层生长 vs 按叶生长

Both trees get the same budget: 7 splits (8 leaves). Numbers show the order of splits. Each candidate split has a fixed gain; leaf-wise always takes the biggest one available.

दोनों trees को एक जैसा budget मिलता है: 7 splits (8 leaves)। Numbers splits का क्रम दिखाते हैं। हर संभावित split का gain तय है; leaf-wise हमेशा उपलब्ध सबसे बड़ा चुनता है।

两棵树的预算相同:7 次分裂(8 个叶子)。数字表示分裂顺序。每个候选分裂的增益是固定的,按叶生长总是选当前最大的那个。

import lightgbm as lgb
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score, classification_report

# Same fraud data as before, split into train / validation / test
X, y = make_classification(n_samples=8000, n_features=20, n_informative=12,
                           n_redundant=4, weights=[0.95, 0.05], random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
X_tr, X_val, y_tr, y_val = train_test_split(
    X_train, y_train, test_size=0.15, stratify=y_train, random_state=42)

train_data = lgb.Dataset(X_tr,  label=y_tr)
val_data   = lgb.Dataset(X_val, label=y_val, reference=train_data)

params = {
    'objective':         'binary',
    'metric':            'binary_logloss',
    'learning_rate':     0.05,
    'num_leaves':        31,      # main complexity control in LightGBM
    'max_depth':         -1,      # -1 = no limit; num_leaves controls size
    'min_child_samples': 20,
    'feature_fraction':  0.7,
    'bagging_fraction':  0.8,
    'bagging_freq':      5,
    'lambda_l1':         0.1,
    'lambda_l2':         1.0,
    'verbosity':         -1,
    'seed':              42
}
callbacks = [lgb.early_stopping(stopping_rounds=50, verbose=False),
             lgb.log_evaluation(period=100)]
model = lgb.train(params, train_data, num_boost_round=2000,
                  valid_sets=[val_data], callbacks=callbacks)

y_prob = model.predict(X_test, num_iteration=model.best_iteration)
print(f"\nBest iteration : {model.best_iteration}")
print(f"Test ROC-AUC   : {roc_auc_score(y_test, y_prob):.4f}\n")
print(classification_report(y_test, (y_prob > 0.5).astype(int), digits=4))
OUTPUT
[100] valid_0's binary_logloss: 0.0749624 [200] valid_0's binary_logloss: 0.0738056 Best iteration : 152 Test ROC-AUC : 0.9460 precision recall f1-score support 0 0.9711 0.9993 0.9850 1513 1 0.9767 0.4828 0.6462 87 accuracy 0.9712 1600 macro avg 0.9739 0.7410 0.8156 1600 weighted avg 0.9714 0.9712 0.9666 1600

LightGBM matches the scikit-learn model (AUC 0.946 vs 0.943) and stops after 152 rounds. Note the three-way split: early stopping uses the validation set, and the test set is used only once at the end.

LightGBM, scikit-learn model के बराबर है (AUC 0.946 बनाम 0.943) और 152 rounds के बाद रुकता है। तीन हिस्सों वाला split देखें: early stopping validation set इस्तेमाल करता है, और test set सिर्फ़ आख़िर में एक बार।

LightGBM 与 scikit-learn model 不相上下(AUC 0.946 vs 0.943),在 152 轮后停止。注意三段式划分:early stopping 用验证集,测试集只在最后用一次。

⏱️ Speed Check: 200,000 Rows⏱️ Speed जाँच: 200,000 Rows⏱️ 速度测试:20 万行

import time
import lightgbm as lgb
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score

X, y = make_classification(n_samples=200_000, n_features=20,
                           n_informative=12, random_state=42)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42)

models = {
    'GradientBoosting (exact)':  GradientBoostingClassifier(n_estimators=200, max_depth=3, random_state=42),
    'HistGradientBoosting':      HistGradientBoostingClassifier(max_iter=200, max_depth=3, early_stopping=False, random_state=42),
    'LightGBM':                  lgb.LGBMClassifier(n_estimators=200, max_depth=3, num_leaves=8, verbosity=-1, random_state=42),
}
print(f"{'Model':<26} {'Train time':>10} {'Test AUC':>9}")
for name, m in models.items():
    t0 = time.perf_counter()
    m.fit(X_tr, y_tr)
    secs = time.perf_counter() - t0
    auc = roc_auc_score(y_te, m.predict_proba(X_te)[:, 1])
    print(f"{name:<26} {secs:>9.1f}s {auc:>9.4f}")
OUTPUT
Model Train time Test AUC GradientBoosting (exact) 403.6s 0.9803 HistGradientBoosting 2.6s 0.9797 LightGBM 2.9s 0.9793
🚀
Don't Forget scikit-learn's Own Fast Versionscikit-learn का अपना तेज़ Version न भूलें别忘了 scikit-learn 自带的快速版本

HistGradientBoostingClassifier / Regressor is built into scikit-learn. It uses LightGBM-style histograms, handles NaN and categorical features natively, and has early stopping on by default for large data. Above (timings from this page's run; yours will differ), it was about 150× faster than the classic GradientBoostingClassifier with the same AUC. scikit-learn recommends it for datasets over about 10,000 rows.

HistGradientBoostingClassifier / Regressor scikit-learn में ही बना है। यह LightGBM जैसे histograms इस्तेमाल करता है, NaN और categorical features को खुद संभालता है, और बड़े data पर early stopping default रूप से चालू रहती है। ऊपर (इस page के run का समय; आपका अलग होगा) यह classic GradientBoostingClassifier से लगभग 150 गुना तेज़ था, वही AUC के साथ। scikit-learn लगभग 10,000 से ज़्यादा rows वाले datasets के लिए इसी की सलाह देता है।

HistGradientBoostingClassifier / Regressor 内置于 scikit-learn。它使用 LightGBM 风格的直方图,原生处理 NaN 和类别特征,数据量大时默认开启 early stopping。上面的测试中(本页运行的耗时,你的结果会不同),它比经典的 GradientBoostingClassifier 快约 150 倍,AUC 相同。scikit-learn 建议在超过约 1 万行的数据上使用它。


SectionSection第 13 节

Feature Importance in Gradient BoostingGradient Boosting में Feature Importance梯度提升中的特征重要性

📈 GainGain增益
importance_type='gain'
The total loss reduction from all splits on a feature. It tells you how much a feature actually helps the predictions.
किसी feature पर हुए सभी splits से loss में कुल कमी। यह बताता है कि feature सच में predictions में कितनी मदद करता है।
某个特征上所有分裂带来的 loss 总下降量。它说明该特征对预测的实际帮助有多大。
✓ Reflects real predictive valueअसली predictive value दिखाता है反映真实的预测价值
✗ Measured on training data onlyसिर्फ़ training data पर मापा जाता है只在训练数据上测量
🔄 Split countSplit की गिनती分裂次数
importance_type='split'
How many times a feature is used to split. Easy to compute, but biased toward continuous features: they can be split many times for little benefit.
Feature पर कितनी बार split हुआ। निकालना आसान, पर continuous features की ओर झुका: उन पर कम फ़ायदे के लिए भी कई बार split हो सकता है।
某个特征被用来分裂的次数。容易计算,但偏向连续特征:它们可以被分裂很多次却收益很小。
✓ Fast and simpleतेज़ और सरल快速简单
✗ Misleading for features with many valuesकई values वाले features के लिए गुमराह करता है对取值多的特征有误导
🎓 Permutation / SHAPPermutation / SHAPPermutation / SHAP
permutation · shap.TreeExplainer
Permutation: shuffle one column on test data and measure the score drop. SHAP: shows how much each feature pushes each prediction up or down, based on Shapley values.
Permutation: test data पर एक column shuffle करें और score में गिरावट मापें। SHAP: Shapley values के आधार पर दिखाता है कि हर feature हर prediction को कितना ऊपर या नीचे धकेलता है।
Permutation:在测试数据上打乱一列,测量分数下降。SHAP:基于 Shapley 值,显示每个特征把每个预测推高或拉低了多少。
✓ Measured on held-out data; SHAP is local + globalHeld-out data पर मापा जाता है; SHAP local + global है在留出数据上测量;SHAP 兼顾局部与全局
✗ Slower to computeनिकालने में धीमा计算较慢
import numpy as np
from sklearn.metrics import roc_auc_score

# `model`, `X_test`, `y_test` come from the LightGBM example above
best = model.best_iteration
split = model.feature_importance(importance_type='split')   # how often used
gain  = model.feature_importance(importance_type='gain')    # how much loss it removed

# Permutation importance: shuffle one column, see how much test AUC drops
base = roc_auc_score(y_test, model.predict(X_test, num_iteration=best))
rng = np.random.default_rng(42)
perm = []
for j in range(X_test.shape[1]):
    X_shuffled = X_test.copy()
    X_shuffled[:, j] = rng.permutation(X_shuffled[:, j])
    perm.append(base - roc_auc_score(y_test, model.predict(X_shuffled, num_iteration=best)))

print("Top 5 features by each method:")
for name, scores in [('split', split), ('gain', gain), ('permutation', np.array(perm))]:
    top = np.argsort(scores)[::-1][:5]
    print(f"  {name:<12}: " + ", ".join(f"f{i}" for i in top))
print(f"\nShuffling f{int(np.argmax(perm))} drops test AUC by {max(perm):.4f}")
OUTPUT
Top 5 features by each method: split : f18, f5, f13, f1, f6 gain : f18, f14, f6, f13, f1 permutation : f14, f13, f2, f6, f12 Shuffling f14 drops test AUC by 0.0408

The three methods disagree. Split count ranks f5 second, but by permutation on test data it ranks only 12th of 20. Permutation importance ranks f14 first: shuffling it drops test AUC by 0.04. When the ranking matters for a decision, trust held-out methods (permutation or SHAP).

तीनों methods सहमत नहीं हैं। Split count f5 को दूसरे स्थान पर रखता है, पर test data पर permutation से वह 20 में से सिर्फ़ 12वें स्थान पर है। Permutation importance f14 को पहले रखता है: उसे shuffle करने से test AUC 0.04 गिरता है। जब ranking किसी फ़ैसले के लिए मायने रखे, तो held-out methods (permutation या SHAP) पर भरोसा करें।

三种方法结论不一致。分裂次数把 f5 排第二,但按测试数据上的 permutation,它在 20 个特征中只排第 12。Permutation 重要性把 f14 排第一:打乱它会让测试 AUC 下降 0.04。当排名关系到决策时,请相信基于留出数据的方法(permutation 或 SHAP)。


SectionSection第 14 节

Gradient Boosting vs Random Forest — Full ComparisonGradient Boosting vs Random Forest — पूरी तुलनाGradient Boosting vs Random Forest — 全面对比

Propertyगुण属性Gradient BoostingRandom Forest
Core ideaमुख्य विचार核心思想Sequential error correctionSequential error सुधार串行纠错Parallel averagingParallel averaging并行平均
Mainly reducesमुख्य रूप से घटाता है主要降低Bias (variance via shrinkage, subsampling)Bias (variance shrinkage, subsampling से)Bias(variance 靠 shrinkage 和子抽样)VarianceVarianceVariance
Tree depthTree depth树深度Shallow (3–5), weak on purposeShallow (3–5), जानबूझकर कमज़ोर浅(3–5),故意设弱Deep, complex on purposeDeep, जानबूझकर complex深,故意设复杂
Parallel trainingParallel training并行训练Not across roundsRounds के बीच नहीं轮次之间不行Yes, easilyहाँ, आसानी से是,很容易
Overfitting riskOverfitting का ख़तरा过拟合风险Higher: needs early stoppingज़्यादा: early stopping चाहिए较高:需要 early stoppingLowकम低
Sensitivity to settingsSettings के प्रति sensitivity对参数的敏感度High: several knobs matterज़्यादा: कई knobs मायने रखते हैं高:多个参数都很重要Low: good defaultsकम: अच्छे defaults低:默认值很好
Peak accuracy (tabular)Peak accuracy (tabular)峰值精度(表格)Often the highestअक्सर सबसे ज़्यादा通常最高Very goodबहुत अच्छी很好
Feature scaling neededFeature scaling ज़रूरी是否需要缩放Noनहीं否Noनहीं否
Best useसबसे अच्छा उपयोग最佳用途Maximum accuracy, competitions, productionज़्यादा से ज़्यादा accuracy, competitions, production追求最高精度、竞赛、生产Fast, robust baselineतेज़, robust baseline快速、稳健的 baseline
💬
The Practitioner's Pathव्यावहारिक रास्ता实践路径

Start with Random Forest. If it misses your accuracy target after basic tuning, move to gradient boosting. For more than about 10,000 rows, use HistGradientBoosting, LightGBM or XGBoost rather than the classic GradientBoostingClassifier, which becomes very slow at scale.

Random Forest से शुरू करें। अगर basic tuning के बाद भी यह आपका accuracy target नहीं छूता, तो gradient boosting पर जाएँ। लगभग 10,000 से ज़्यादा rows के लिए classic GradientBoostingClassifier के बजाय HistGradientBoosting, LightGBM या XGBoost इस्तेमाल करें, क्योंकि बड़े data पर classic version बहुत धीमा हो जाता है।

先用 Random Forest。如果基本调参后仍达不到精度目标,再换成梯度提升。数据超过约 1 万行时,请使用 HistGradientBoosting、LightGBM 或 XGBoost,而不是经典的 GradientBoostingClassifier,后者在大数据上会变得非常慢。


SectionSection第 15 节

Golden RulesGolden Rules黄金法则

🌳 Gradient Boosting — Rules to RememberGradient Boosting — याद रखने के नियम梯度提升 — 必记规则
1
Always use early stopping. Set n_iter_no_change=20 and validation_fraction=0.1 in scikit-learn, or early_stopping_rounds=50 in LightGBM. Choosing the number of trees is early stopping's job.
हमेशा early stopping इस्तेमाल करें। scikit-learn में n_iter_no_change=20 और validation_fraction=0.1, या LightGBM में early_stopping_rounds=50 रखें। Trees की संख्या चुनना early stopping का काम है।
始终使用 early stopping。 在 scikit-learn 中设 n_iter_no_change=20 和 validation_fraction=0.1,或在 LightGBM 中设 early_stopping_rounds=50。选择树的数量是 early stopping 的工作。
2
Start with a low learning rate (0.05 or lower). It is one of the most reliable ways to improve a GB model. More trees with small steps usually match or beat fewer trees with big steps, and they are much less sensitive to exactly when you stop.
कम learning rate (0.05 या कम) से शुरू करें। GB model सुधारने का यह सबसे भरोसेमंद तरीकों में से एक है। छोटे steps वाले ज़्यादा trees आमतौर पर बड़े steps वाले कम trees के बराबर या बेहतर होते हैं, और रुकने के सही समय पर बहुत कम निर्भर करते हैं।
从较低的学习率(0.05 或更低)开始。 这是改进 GB model 最可靠的方法之一。小步长的更多树,通常不输于甚至胜过大步长的少量树,而且对何时停止敏感得多。
3
Keep trees shallow. max_depth=3 is a strong default. Rarely go above 6. Deep trees in boosting memorise noise.
Trees को shallow रखें। max_depth=3 एक मज़बूत default है। 6 से ऊपर शायद ही जाएँ। Boosting में deep trees noise रट लेते हैं।
保持树浅。 max_depth=3 是很好的默认值,很少需要超过 6。boosting 中的深树会记住噪声。
4
Turn on Stochastic Gradient Boosting. subsample=0.7–0.8 is a good default. It adds healthy randomness, lowers variance, speeds up training, and usually helps on noisy real-world data.
Stochastic Gradient Boosting चालू करें। subsample=0.7–0.8 एक अच्छा default है। यह सेहतमंद randomness जोड़ता है, variance घटाता है, training तेज़ करता है, और असली noisy data पर आमतौर पर मदद करता है।
开启随机梯度提升。 subsample=0.7–0.8 是不错的默认值。它带来有益的随机性,降低 variance,加快训练,在真实的噪声数据上通常有帮助。
5
Use a histogram-based booster for large data. Above about 10,000 rows, use HistGradientBoosting, LightGBM or XGBoost. On this page they trained in about 3 seconds versus 404 seconds, with the same AUC.
बड़े data के लिए histogram-based booster इस्तेमाल करें। लगभग 10,000 rows से ऊपर HistGradientBoosting, LightGBM या XGBoost इस्तेमाल करें। इस page पर वे 404 seconds के मुक़ाबले लगभग 3 seconds में train हुए, वही AUC के साथ।
大数据用基于直方图的 booster。 超过约 1 万行时,请用 HistGradientBoosting、LightGBM 或 XGBoost。在本页中它们约 3 秒就训练完,而经典版本用了 404 秒,AUC 相同。
6
Tune in the right order. Fix η → tune max_depth and min_samples_leaf → tune subsample and max_features → then lower η further. Or use a search tool like Optuna.
सही क्रम में tune करें। η तय करें → max_depth और min_samples_leaf tune करें → subsample और max_features tune करें → फिर η और घटाएँ। या Optuna जैसा search tool इस्तेमाल करें।
按正确顺序调参。 先固定 η → 调 max_depth 和 min_samples_leaf → 调 subsample 和 max_features → 再进一步降低 η。或者使用 Optuna 之类的搜索工具。
7
Match the loss to your goal, and check the threshold. If you care about MAE, consider absolute or Huber loss. For imbalanced classification, judge with recall, precision or PR-AUC, and tune the decision threshold (see Section 11).
Loss को अपने लक्ष्य से मिलाएँ, और threshold जाँचें। अगर आपको MAE की परवाह है, तो absolute या Huber loss पर विचार करें। Imbalanced classification में recall, precision या PR-AUC से परखें, और decision threshold tune करें (Section 11 देखें)।
让 loss 与目标一致,并检查阈值。 如果你关心 MAE,可以考虑绝对误差或 Huber loss。对类别不平衡的分类,用 recall、precision 或 PR-AUC 评估,并调整决策阈值(见第 11 节)。
8
Feature scaling is not needed. Tree splits only care about the order of values, not their size. StandardScaler or MinMaxScaler changes nothing for the trees and just adds a step.
Feature scaling की ज़रूरत नहीं। Tree splits सिर्फ़ values के क्रम की परवाह करते हैं, उनके आकार की नहीं। StandardScaler या MinMaxScaler trees के लिए कुछ नहीं बदलता, बस एक step बढ़ाता है।
不需要特征缩放。 树的分裂只关心数值的顺序,不关心大小。StandardScaler 或 MinMaxScaler 对树没有任何影响,只会多一个步骤。