The Story That Explains Gradient Boostingवह कहानी जो Gradient Boosting समझाती है一个解释 Gradient Boosting 的故事
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.
दस rounds के बाद, जिनमें हर round पिछली गलतियों पर था, उसके 98/100 आते हैं। Teacher ने कभी सब कुछ शुरू से नहीं पढ़ाया। उसने सिर्फ़ वही सुधारा जो गलत था।
यही Gradient Boosting का पूरा तर्क है। हर नया tree असली target नहीं सीखता। वह पिछले सभी trees की मिली-जुली residual errors (गलतियाँ) सीखता है। सबको जोड़ दें, तो एक बहुत सटीक model मिलता है।
十轮之后,每一轮都只针对上一轮的错误,她考到了 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 是串行的:每棵树都依赖前面的树。
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,所以这个方法非常灵活。
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,但组合方式截然不同。
| 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✓ हाँ, आसानी से✓ 是,很容易 |
| 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 में बन सकता है)✗ 轮次之间不行(单棵树内部可并行) |
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,把落点推向中心。
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 抓不到的复杂模式的原因,也是不调参时它更容易过拟合的原因。
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 करना।
我们用一个回归问题来讲解算法:预测房价。
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残差 |
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。小而稳的步子,一步步接近真相。
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 下降最快的方向。
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 探索器里看到每一种。
Visual Diagram — The Sequential ProcessVisual Diagram — Sequential प्रक्रिया图解 — 串行过程
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 决定了什么算"错误",以及每个错误的代价有多大。
alpha sets the switch point as a quantile of the errors.alpha errors के quantile के रूप में switch point तय करता है।alpha 以误差分位数的形式设定切换点。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 会被它带走。
Best constantसबसे अच्छा constant最佳常数:
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。
Key Hyperparameters — The Control Panelमुख्य Hyperparameters — Control Panel关键超参数 — 控制面板
🍎 Family 1 — Ensemble Structure🍎 Family 1 — Ensemble का ढाँचा🍎 第 1 类 — 集成结构
| Parameter | Default | What it controlsक्या नियंत्रित करता है控制什么 | Practical adviceव्यावहारिक सलाह实用建议 |
|---|---|---|---|
n_estimators | 100 | Number 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.1 | Shrinkage 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。 |
loss | task-basedtask पर निर्भर取决于任务 | The loss being minimisedजिस loss को कम किया जा रहा है被最小化的 loss | Match 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 类 — 树结构(复杂度)
| Parameter | Default | What it controlsक्या नियंत्रित करता है控制什么 | Practical adviceव्यावहारिक सलाह实用建议 |
|---|---|---|---|
max_depth | 3 | Depth 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_leaf | 1 | Minimum rows in a leafLeaf में न्यूनतम rows叶子的最少样本数 | Raise to 5–20 on noisy or small data.Noisy या छोटे data पर 5–20 तक बढ़ाएँ।数据噪声大或数据量小时调到 5–20。 |
max_features | None | Features 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_nodes | None | Maximum 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
| Parameter | Default | What it controlsक्या नियंत्रित करता है控制什么 | Practical adviceव्यावहारिक सलाह实用建议 |
|---|---|---|---|
subsample | 1.0 | Share 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_fraction | 0.1 | Share 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_change | None | Early-stopping patienceEarly-stopping का धैर्यearly stopping 的耐心值 | Set 10–25. Training stops when the validation score stops improving.10–25 रखें। Validation score सुधरना बंद होने पर training रुक जाती है।设为 10–25。验证分数不再提升时训练停止。 |
Shrinkage — The Most Important Tuning DecisionShrinkage — Tuning का सबसे ज़रूरी फ़ैसलाShrinkage — 最重要的调参决定
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.
Surgeon A तेज़ है, पर अगर वह 0.5 mm भी ज़्यादा कर दे तो नया नुकसान होता है। Surgeon B को समय ज़्यादा लगता है पर उसे हमेशा पता रहता है कि वह कहाँ है और वह आगे नहीं निकलती।
Learning rate Surgeon B का तरीका है: छोटे कदम, लगातार जाँच, कम हादसे।
医生 A 更快,但哪怕多矫正 0.5 毫米,也会造成新的伤害。医生 B 用时更长,但始终知道自己在哪,不会矫枉过正。
学习率就是医生 B 的方法:小步前进,持续检查,减少灾难。
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 的最低点。
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 选择树的数量。
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 节的模拟器里试试。
| 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)较慢(数据更多) |
| Bias | Slightly lowerथोड़ा कम略低 |
| Variance | Higherज़्यादा较高 |
| 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%) |
| Bias | Slightly higherथोड़ा ज़्यादा略高 |
| Variance | Lowerकम较低 |
Overfitting and RegularisationOverfitting और Regularisation过拟合与正则化
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。它会在过拟合前免费停下。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,然后点击播放。
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。
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))
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())}")
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)")
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 是微软的高速实现。拟合残差的逻辑相同,但两个工程上的创新让它在大数据上快得多:基于直方图的分裂和按叶生长。
| 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हाथ से संभालना पड़ता है需要手动处理 |
| 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 类型) |
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))
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}")
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 万行的数据上使用它。
Feature Importance in Gradient BoostingGradient Boosting में Feature Importance梯度提升中的特征重要性
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}")
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)。
Gradient Boosting vs Random Forest — Full ComparisonGradient Boosting vs Random Forest — पूरी तुलनाGradient Boosting vs Random Forest — 全面对比
| Propertyगुण属性 | Gradient Boosting | Random 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 stopping | Lowकम低 |
| 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 |
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,后者在大数据上会变得非常慢。
Golden RulesGolden Rules黄金法则
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.n_iter_no_change=20 और validation_fraction=0.1, या LightGBM में early_stopping_rounds=50 रखें। Trees की संख्या चुनना early stopping का काम है।n_iter_no_change=20 和 validation_fraction=0.1,或在 LightGBM 中设 early_stopping_rounds=50。选择树的数量是 early stopping 的工作。max_depth=3 is a strong default. Rarely go above 6. Deep trees in boosting memorise noise.max_depth=3 एक मज़बूत default है। 6 से ऊपर शायद ही जाएँ। Boosting में deep trees noise रट लेते हैं।max_depth=3 是很好的默认值,很少需要超过 6。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.subsample=0.7–0.8 एक अच्छा default है। यह सेहतमंद randomness जोड़ता है, variance घटाता है, training तेज़ करता है, और असली noisy data पर आमतौर पर मदद करता है।subsample=0.7–0.8 是不错的默认值。它带来有益的随机性,降低 variance,加快训练,在真实的噪声数据上通常有帮助。HistGradientBoosting, LightGBM or XGBoost. On this page they trained in about 3 seconds versus 404 seconds, with the same AUC.HistGradientBoosting, LightGBM या XGBoost इस्तेमाल करें। इस page पर वे 404 seconds के मुक़ाबले लगभग 3 seconds में train हुए, वही AUC के साथ।HistGradientBoosting、LightGBM 或 XGBoost。在本页中它们约 3 秒就训练完,而经典版本用了 404 秒,AUC 相同。