The Story: Ramesh the Loan Officer
"First I check the credit score. If it's above 700, I look at their income. Income over 50K? Approved. Below 50K? Rejected. If credit score is low, I check employment status. Not employed? Rejected. Employed but debt ratio over 40%? Rejected. Employed and debt ratio fine? Approved."
The analyst stares at him. "That's... a decision tree."
Ramesh had been running a Decision Tree algorithm in his head for 20 years without knowing it. Machine learning learns these questions and thresholds automatically from data.
Look for the interactive boxes: the Loan Officer (Section 03), Classify a New Day (08), Watch the Tree Grow (10), the Overfitting Lab (11), the Hyperparameter Playground (12) and Weak Spots (14). The trees in Sections 10–14 are real CART trees, grown in your browser the same way scikit-learn grows them.
What Is a Decision Tree?
A Decision Tree is a supervised learning algorithm that models decisions as a flowchart-like tree structure. It learns a hierarchy of if-else questions from training data.
- You can read every decision
- No black box — full transparency
- Regulators and managers love it
- Easy to visualise and debug
- No distribution assumptions
- Handles non-linear boundaries
- Works with mixed data types
- No feature scaling required
- Base of Random Forests
- Base of XGBoost / LightGBM
- Used in medical diagnosis
- Core of ensemble methods
Anatomy of a Decision Tree
Purple = Root node. Blue = Internal decision nodes. Green = Approved leaf nodes. Red = Rejected leaf nodes. Each path from root to leaf is one complete decision rule.
| Term | Definition | Example in Ramesh's Tree |
|---|---|---|
| Root Node | The topmost node — the best initial split for the whole dataset | "Credit Score >= 700?" |
| Decision Node | An internal node that tests a feature and branches into sub-trees | "Annual Income >= 50K?", "Currently Employed?", "Debt Ratio <= 40%?" |
| Leaf Node | A terminal node — outputs the final prediction | APPROVED or REJECTED |
| Branch / Edge | The connection between nodes — labelled YES or NO | The arrows labelled YES / NO between nodes |
| Depth | Distance from root to a node. Max depth = tree height | Root=0, Income node=1, Debt node=2, final leaves=3 |
| Split | The threshold chosen to divide data at a node | Credit >= 700, Income >= 50K, Debt <= 40% |
| Pruning | Removing branches to prevent overfitting | Removing the Debt Ratio node if it doesn't help generalisation |
Try It — The Loan Officer
Be the applicant. Move the sliders and watch your path light up in Ramesh's tree. Each question sends you left (YES) or right (NO) until you reach a leaf — the final answer.
कहानी: Loan Officer रमेश
"पहले मैं credit score देखता हूँ। अगर यह 700 से ऊपर है, तो मैं उनकी आय देखता हूँ। आय 50K से ज़्यादा? मंज़ूर। 50K से कम? नामंज़ूर। अगर credit score कम है, तो मैं देखता हूँ कि नौकरी है या नहीं। नौकरी नहीं है? नामंज़ूर। नौकरी है, पर debt ratio 40% से ज़्यादा? नामंज़ूर। नौकरी है और debt ratio ठीक है? मंज़ूर।"
Analyst उन्हें देखता रह जाता है। "यह तो... एक decision tree है।"
रमेश 20 साल से अपने दिमाग में एक Decision Tree algorithm चला रहे थे, और उन्हें पता भी नहीं था। Machine learning ये सवाल और thresholds data से अपने आप सीखता है।
इन interactive boxes को ढूँढिए: Loan Officer (सेक्शन 03), Classify a New Day (08), Watch the Tree Grow (10), Overfitting Lab (11), Hyperparameter Playground (12) और Weak Spots (14)। सेक्शन 10–14 के trees असली CART trees हैं। ये आपके browser में ठीक वैसे ही बनते हैं, जैसे scikit-learn इन्हें बनाता है।
Decision Tree क्या है?
Decision Tree एक supervised learning algorithm है। यह फ़ैसलों को एक flowchart जैसे tree structure में दिखाता है। यह training data से if-else सवालों की एक सीढ़ी (hierarchy) सीखता है।
- आप हर फ़ैसला पढ़ सकते हैं
- कोई black box नहीं — सब कुछ साफ़ दिखता है
- Regulators और managers इसे बहुत पसंद करते हैं
- देखना और debug करना आसान
- Distribution के बारे में कोई मान्यता नहीं
- Non-linear boundaries संभाल लेता है
- अलग-अलग तरह के data के साथ चलता है
- Feature scaling की ज़रूरत नहीं
- Random Forests का आधार
- XGBoost / LightGBM का आधार
- बीमारी की जाँच (medical diagnosis) में इस्तेमाल
- Ensemble methods का मुख्य हिस्सा
Decision Tree की बनावट
बैंगनी = Root node। नीला = अंदर के decision nodes। हरा = मंज़ूर वाले leaf nodes। लाल = नामंज़ूर वाले leaf nodes। Root से leaf तक का हर रास्ता एक पूरा decision rule है।
| शब्द | मतलब | रमेश के Tree में उदाहरण |
|---|---|---|
| Root Node | सबसे ऊपर का node — पूरे dataset के लिए सबसे अच्छा पहला split | "Credit Score >= 700?" |
| Decision Node | अंदर का node, जो एक feature को जाँचता है और sub-trees में बँट जाता है | "सालाना आय >= 50K?", "अभी नौकरी है?", "Debt Ratio <= 40%?" |
| Leaf Node | आख़िरी node — यह final prediction देता है | मंज़ूर या नामंज़ूर |
| Branch / Edge | Nodes के बीच का जोड़ — इस पर हाँ या नहीं लिखा होता है | Nodes के बीच हाँ / नहीं वाले तीर |
| Depth | Root से किसी node तक की दूरी। Max depth = tree की ऊँचाई | Root=0, आय वाला node=1, Debt वाला node=2, आख़िरी leaves=3 |
| Split | वह threshold जो किसी node पर data को बाँटने के लिए चुना जाता है | Credit >= 700, आय >= 50K, Debt <= 40% |
| Pruning | Overfitting रोकने के लिए branches हटाना | अगर Debt Ratio node से generalisation में मदद नहीं मिलती, तो उसे हटाना |
ख़ुद आज़माइए — The Loan Officer
आप ख़ुद अर्ज़ी देने वाले बनिए। Sliders को खिसकाइए और रमेश के tree में अपना रास्ता चमकते हुए देखिए। हर सवाल आपको बाईं ओर (हाँ) या दाईं ओर (नहीं) भेजता है, जब तक आप एक leaf तक नहीं पहुँच जाते — वही final जवाब है।
故事:贷款员 Ramesh
“我先看信用分。如果高于 700,我就看收入。 收入超过 50K?批准。低于 50K?拒绝。如果信用分低,我就看 工作状态。没有工作?拒绝。有工作但负债率超过 40%? 拒绝。有工作而且负债率正常?批准。”
分析师盯着他看:“这……就是一棵 Decision Tree 啊。”
Ramesh 在脑子里运行 Decision Tree 算法 已经 20 年了,自己却不知道。Machine Learning 会学习这些问题和 threshold, 而且是自动从数据中学。
请找这些互动框:Loan Officer(第 03 节)、Classify a New Day(08)、 Watch the Tree Grow(10)、Overfitting Lab(11)、Hyperparameter Playground(12) 和 Weak Spots(14)。第 10–14 节里的 tree 都是真正的 CART tree,在你的浏览器里生长,方法和 scikit-learn 完全一样。
什么是 Decision Tree?
Decision Tree 是一种监督学习算法。它把决策画成像流程图一样的 tree 结构。它从 training 数据中学出一层一层的 if-else 问题。
- 每个决策你都能读懂
- 不是黑盒,完全透明
- 监管人员和经理都很喜欢
- 容易画出来,也容易调试
- 不需要假设数据分布
- 能处理非线性边界
- 能处理混合的数据类型
- 不需要 feature scaling
- Random Forest 的基础
- XGBoost / LightGBM 的基础
- 用于医学诊断
- ensemble 方法的核心
Decision Tree 的结构
紫色 = root node。蓝色 = internal node(决策 node)。绿色 = “批准”的 leaf node。红色 = “拒绝”的 leaf node。从 root 到 leaf 的每一条路径,就是一条完整的决策规则。
| 术语 | 定义 | 在 Ramesh 的 tree 中的例子 |
|---|---|---|
| Root Node | 最顶上的 node,是整个 dataset 最好的第一个 split | “信用分 >= 700?” |
| Decision Node | 一个 internal node,它检查一个 feature,然后分出子 tree | “年收入 >= 50K?”、“目前有工作?”、“负债率 <= 40%?” |
| Leaf Node | 末端的 node,输出最终的 prediction | 批准 或 拒绝 |
| Branch / Edge | node 之间的连线,标着“是”或“否” | node 之间标着“是 / 否”的箭头 |
| Depth | 从 root 到某个 node 的距离。最大 depth = tree 的高度 | Root=0,收入 node=1,负债 node=2,最后的 leaf=3 |
| Split | 在一个 node 上用来分开数据的 threshold | 信用分 >= 700,收入 >= 50K,负债 <= 40% |
| Pruning | 剪掉一些 branch,防止 overfitting | 如果负债率 node 对泛化没有帮助,就把它剪掉 |
动手试试 — Loan Officer
你来当申请人。拖动滑块,看你的路径在 Ramesh 的 tree 里亮起来。每个问题会把你送到左边(是) 或右边(否),直到你到达一个 leaf,也就是最终答案。
Real Worked Example: The "Play Tennis" Dataset
This is the canonical dataset used to teach ID3 — the original decision tree algorithm by Ross Quinlan (1986). The task: given weather conditions, should we play tennis today? We have 14 days of historical data with four weather features and the outcome.
| Day | Outlook | Temp | Humidity | Wind | Play Tennis? |
|---|---|---|---|---|---|
| D1 | Sunny | Hot | High | Weak | No |
| D2 | Sunny | Hot | High | Strong | No |
| D3 | Overcast | Hot | High | Weak | Yes |
| D4 | Rain | Mild | High | Weak | Yes |
| D5 | Rain | Cool | Normal | Weak | Yes |
| D6 | Rain | Cool | Normal | Strong | No |
| D7 | Overcast | Cool | Normal | Strong | Yes |
| D8 | Sunny | Mild | High | Weak | No |
| D9 | Sunny | Cool | Normal | Weak | Yes |
| D10 | Rain | Mild | Normal | Weak | Yes |
| D11 | Sunny | Mild | Normal | Strong | Yes |
| D12 | Overcast | Mild | High | Strong | Yes |
| D13 | Overcast | Hot | Normal | Weak | Yes |
| D14 | Rain | Mild | High | Strong | No |
The dataset has 9 Yes and 5 No — written as S = [9+, 5-].
ID3 must figure out which of the four features creates the most useful first split by calculating Information Gain for each.
Before any split, S = [9+, 5-] has entropy:
H(S) = -(9/14).log2(9/14) - (5/14).log2(5/14) = 0.940 bits
Every split's Information Gain is measured as a reduction from 0.940. Maximum binary entropy is 1.0 — we're close because 9:5 isn't far from equal.
Entropy and Information Gain — Choosing the Root Split
Attribute: Outlook — Gain = 0.246 bits (WINNER)
Outlook creates 3 groups: Sunny (D1,D2,D8,D9,D11), Overcast (D3,D7,D12,D13), Rain (D4,D5,D6,D10,D14).
H(Sunny) = -(2/5)log2(2/5) - (3/5)log2(3/5) = 0.971 bits
H(Overcast) = 0 — perfectly pure, always Yes! = 0.000 bits
H(Rain) = -(3/5)log2(3/5) - (2/5)log2(2/5) = 0.971 bits
| Attribute | Groups Created | Information Gain | Selected? |
|---|---|---|---|
| Outlook | Sunny [2+,3-], Overcast [4+,0-], Rain [3+,2-] | 0.246 bits | Root Node |
| Humidity | High [3+,4-], Normal [6+,1-] | 0.151 bits | 2nd Best |
| Wind | Strong [3+,3-], Weak [6+,2-] | 0.048 bits | 3rd |
| Temp | Hot [2+,2-], Mild [4+,2-], Cool [3+,1-] | 0.029 bits | 4th (never used!) |
Recursion: Sunny Branch uses Humidity
The Sunny subset (D1, D2, D8, D9, D11) has [2+, 3-], H = 0.971 bits. Recursing on the 3 remaining attributes:
Gain = 0.971 - (3/5 x 0 + 2/5 x 0) = 0.971 bits — WINNER (perfect split)
Gain(Sunny, Temp) = 0.971 - 0.400 = 0.570 bits
Gain(Sunny, Wind) = 0.971 - 0.951 = 0.019 bits
High Humidity: D1, D2, D8 all said No (no tennis when it's sunny and humid). Normal Humidity: D9, D11 both said Yes. Both child nodes are pure leaves — no further splitting needed on this branch.
Recursion: Rain Branch uses Wind
The Rain subset (D4, D5, D6, D10, D14) has [3+, 2-], H = 0.971 bits.
Gain(Rain, Wind) = 0.971 - 0 = 0.971 bits — WINNER (perfect split)
Gain(Rain, Humidity) = 0.019 bits
Gain(Rain, Temp) = 0.019 bits
D6 and D14 never played in rain with strong wind. D4, D5, D10 always played in rain with weak wind. The tree is now complete — all 5 leaf nodes are pure. The Temp feature was never used at all.
The Final Decision Tree: Play Tennis
The complete ID3 tree has max depth 2 and 5 leaf nodes — all pure (Gini = 0). It perfectly classifies all 14 training examples. Notice Temp is never used — it had the lowest information gain (0.029 bits) and was always outcompeted at every node.
Try It — Classify a New Day
The tree is finished, so now we can use it. Set tomorrow's weather and follow the path. The table highlights the training days that ended up in the same leaf.
असली हल किया हुआ उदाहरण: "Play Tennis" Dataset
यह वही मशहूर dataset है जिससे ID3 सिखाया जाता है। ID3 सबसे पहला decision tree algorithm है, जिसे Ross Quinlan (1986) ने बनाया था। काम यह है: मौसम को देखकर बताइए, क्या आज tennis खेलना चाहिए? हमारे पास 14 दिनों का पुराना data है। इसमें मौसम के चार features और नतीजा है।
| दिन | Outlook | Temp | Humidity | Wind | Play Tennis? |
|---|---|---|---|---|---|
| D1 | Sunny | Hot | High | Weak | No |
| D2 | Sunny | Hot | High | Strong | No |
| D3 | Overcast | Hot | High | Weak | Yes |
| D4 | Rain | Mild | High | Weak | Yes |
| D5 | Rain | Cool | Normal | Weak | Yes |
| D6 | Rain | Cool | Normal | Strong | No |
| D7 | Overcast | Cool | Normal | Strong | Yes |
| D8 | Sunny | Mild | High | Weak | No |
| D9 | Sunny | Cool | Normal | Weak | Yes |
| D10 | Rain | Mild | Normal | Weak | Yes |
| D11 | Sunny | Mild | Normal | Strong | Yes |
| D12 | Overcast | Mild | High | Strong | Yes |
| D13 | Overcast | Hot | Normal | Weak | Yes |
| D14 | Rain | Mild | High | Strong | No |
इस dataset में 9 Yes और 5 No हैं — इसे S = [9+, 5-] लिखते हैं।
ID3 को पता लगाना है कि चारों features में से कौन सा सबसे काम का पहला split बनाता है। इसके लिए वह हर feature का Information Gain निकालता है।
किसी भी split से पहले, S = [9+, 5-] की entropy है:
H(S) = -(9/14).log2(9/14) - (5/14).log2(5/14) = 0.940 bits
हर split का Information Gain, 0.940 से कितनी कमी आई, उससे नापा जाता है। Binary में सबसे ज़्यादा entropy 1.0 होती है। हम इसके क़रीब हैं, क्योंकि 9:5 बराबर से बहुत दूर नहीं है।
Entropy और Information Gain — Root Split चुनना
Attribute: Outlook — Gain = 0.246 bits (जीता)
Outlook 3 समूह बनाता है: Sunny (D1,D2,D8,D9,D11), Overcast (D3,D7,D12,D13), Rain (D4,D5,D6,D10,D14)।
H(Sunny) = -(2/5)log2(2/5) - (3/5)log2(3/5) = 0.971 bits
H(Overcast) = 0 — पूरी तरह pure, हमेशा Yes! = 0.000 bits
H(Rain) = -(3/5)log2(3/5) - (2/5)log2(2/5) = 0.971 bits
| Attribute | बने हुए समूह | Information Gain | चुना गया? |
|---|---|---|---|
| Outlook | Sunny [2+,3-], Overcast [4+,0-], Rain [3+,2-] | 0.246 bits | Root Node |
| Humidity | High [3+,4-], Normal [6+,1-] | 0.151 bits | दूसरा सबसे अच्छा |
| Wind | Strong [3+,3-], Weak [6+,2-] | 0.048 bits | तीसरा |
| Temp | Hot [2+,2-], Mild [4+,2-], Cool [3+,1-] | 0.029 bits | चौथा (कभी इस्तेमाल नहीं हुआ!) |
Recursion: Sunny Branch पर Humidity
Sunny वाले हिस्से (D1, D2, D8, D9, D11) में [2+, 3-] है, H = 0.971 bits। अब बचे हुए 3 attributes पर फिर से यही काम करते हैं:
Gain = 0.971 - (3/5 x 0 + 2/5 x 0) = 0.971 bits — जीता (perfect split)
Gain(Sunny, Temp) = 0.971 - 0.400 = 0.570 bits
Gain(Sunny, Wind) = 0.971 - 0.951 = 0.019 bits
High Humidity: D1, D2, D8 तीनों में No था (धूप और उमस हो तो tennis नहीं)। Normal Humidity: D9, D11 दोनों में Yes था। दोनों child nodes pure leaves हैं — इस branch पर अब और split की ज़रूरत नहीं।
Recursion: Rain Branch पर Wind
Rain वाले हिस्से (D4, D5, D6, D10, D14) में [3+, 2-] है, H = 0.971 bits।
Gain(Rain, Wind) = 0.971 - 0 = 0.971 bits — जीता (perfect split)
Gain(Rain, Humidity) = 0.019 bits
Gain(Rain, Temp) = 0.019 bits
D6 और D14 में बारिश और तेज़ हवा में कभी नहीं खेला गया। D4, D5, D10 में बारिश और हल्की हवा में हमेशा खेला गया। अब tree पूरा हो गया — सभी 5 leaf nodes pure हैं। Temp feature का तो कभी इस्तेमाल ही नहीं हुआ।
आख़िरी Decision Tree: Play Tennis
पूरे ID3 tree की max depth 2 है और इसमें 5 leaf nodes हैं — सभी pure (Gini = 0)। यह सभी 14 training examples को बिल्कुल सही classify करता है। ध्यान दीजिए, Temp का कभी इस्तेमाल नहीं हुआ। इसका information gain सबसे कम (0.029 bits) था, और हर node पर यह दूसरों से हार गया।
ख़ुद आज़माइए — Classify a New Day
Tree पूरा हो गया है, तो अब हम इसे इस्तेमाल कर सकते हैं। कल का मौसम चुनिए और रास्ते पर चलिए। Table उन training दिनों को highlight करती है जो उसी leaf में पहुँचे थे।
真实例题:“Play Tennis” dataset
这是教 ID3 时最经典的 dataset。ID3 是 Ross Quinlan(1986)提出的最早的 Decision Tree 算法。任务是:根据天气情况,今天要不要去打网球?我们有 14 天的历史数据,包含四个天气 feature 和结果。
| Day | Outlook | Temp | Humidity | Wind | Play Tennis? |
|---|---|---|---|---|---|
| D1 | Sunny | Hot | High | Weak | No |
| D2 | Sunny | Hot | High | Strong | No |
| D3 | Overcast | Hot | High | Weak | Yes |
| D4 | Rain | Mild | High | Weak | Yes |
| D5 | Rain | Cool | Normal | Weak | Yes |
| D6 | Rain | Cool | Normal | Strong | No |
| D7 | Overcast | Cool | Normal | Strong | Yes |
| D8 | Sunny | Mild | High | Weak | No |
| D9 | Sunny | Cool | Normal | Weak | Yes |
| D10 | Rain | Mild | Normal | Weak | Yes |
| D11 | Sunny | Mild | Normal | Strong | Yes |
| D12 | Overcast | Mild | High | Strong | Yes |
| D13 | Overcast | Hot | Normal | Weak | Yes |
| D14 | Rain | Mild | High | Strong | No |
这个 dataset 有 9 个 Yes 和 5 个 No,写作 S = [9+, 5-]。
ID3 要算出每个 feature 的 Information Gain,找出四个 feature 中哪一个能做出最有用的第一个 split。
在任何 split 之前,S = [9+, 5-] 的 entropy 是:
H(S) = -(9/14).log2(9/14) - (5/14).log2(5/14) = 0.940 bits
每个 split 的 Information Gain,都是看它比 0.940 降低了多少。二分类的最大 entropy 是 1.0。我们离它很近,因为 9:5 和对半分差得不多。
Entropy 和 Information Gain:选出 root 的 split
属性:Outlook — Gain = 0.246 bits(胜出)
Outlook 分出 3 组:Sunny(D1,D2,D8,D9,D11),Overcast(D3,D7,D12,D13),Rain(D4,D5,D6,D10,D14)。
H(Sunny) = -(2/5)log2(2/5) - (3/5)log2(3/5) = 0.971 bits
H(Overcast) = 0 — 完全纯,永远是 Yes!= 0.000 bits
H(Rain) = -(3/5)log2(3/5) - (2/5)log2(2/5) = 0.971 bits
| 属性 | 分出的组 | Information Gain | 是否选中? |
|---|---|---|---|
| Outlook | Sunny [2+,3-], Overcast [4+,0-], Rain [3+,2-] | 0.246 bits | Root Node |
| Humidity | High [3+,4-], Normal [6+,1-] | 0.151 bits | 第 2 好 |
| Wind | Strong [3+,3-], Weak [6+,2-] | 0.048 bits | 第 3 |
| Temp | Hot [2+,2-], Mild [4+,2-], Cool [3+,1-] | 0.029 bits | 第 4(从没被用过!) |
递归:Sunny branch 用 Humidity
Sunny 子集(D1, D2, D8, D9, D11)是 [2+, 3-],H = 0.971 bits。在剩下的 3 个属性上继续递归:
Gain = 0.971 - (3/5 x 0 + 2/5 x 0) = 0.971 bits — 胜出(完美 split)
Gain(Sunny, Temp) = 0.971 - 0.400 = 0.570 bits
Gain(Sunny, Wind) = 0.971 - 0.951 = 0.019 bits
Humidity 为 High:D1、D2、D8 都是 No(天晴又潮湿时不打网球)。 Humidity 为 Normal:D9、D11 都是 Yes。 两个子 node 都是纯的 leaf,这条 branch 不用再 split 了。
递归:Rain branch 用 Wind
Rain 子集(D4, D5, D6, D10, D14)是 [3+, 2-],H = 0.971 bits。
Gain(Rain, Wind) = 0.971 - 0 = 0.971 bits — 胜出(完美 split)
Gain(Rain, Humidity) = 0.019 bits
Gain(Rain, Temp) = 0.019 bits
D6 和 D14 在下雨又刮强风时从不打球。D4、D5、D10 在下雨但风弱时总是打球。 现在 tree 已经完成,5 个 leaf node 全都是纯的。Temp 这个 feature 一次都没被用过。
最终的 Decision Tree:Play Tennis
完整的 ID3 tree 最大 depth 是 2,有 5 个 leaf node,而且全都是纯的(Gini = 0)。它把 14 个 training 样本全部分对了。注意 Temp 从没被用过:它的 Information Gain 最低(0.029 bits),在每个 node 上都输给了别的 feature。
动手试试 — Classify a New Day
tree 已经建好了,现在可以用它了。设置明天的天气,然后沿着路径走。表格会高亮那些 落到同一个 leaf 的 training 日子。
Entropy and Gini Ranges for Multiple Classes
A key insight from the Play Tennis example: entropy maximum depends on the number of classes. This matters when comparing problems.
| Number of Classes (n) | Max Entropy = log2(n) | Max Gini = (n-1)/n |
|---|---|---|
| 2 (Binary — Play Tennis) | 1.000 | 0.500 |
| 3 | 1.585 | 0.667 |
| 4 | 2.000 | 0.750 |
| 5 | 2.322 | 0.800 |
| 10 | 3.322 | 0.900 |
1. Always non-negative (minimum = 0, when a node is pure).
2. Maximum when all classes are equally likely — the system is most uncertain.
3. Increases with the number of classes — a 10-class problem can have entropy up to 3.322 bits, far higher than binary's 1.0 ceiling.
If p1 = p2 = p3 = 1/3 (all three classes equally likely):
Gini = 1 - ((1/3)^2 + (1/3)^2 + (1/3)^2) = 1 - (3 x 1/9) = 1 - 1/3 = 2/3 = 0.667
This matches the formula (n-1)/n = 2/3 exactly. Both Gini and Entropy reach maximum when classes are perfectly balanced — you have no information about the correct answer.
Gini Impurity vs Entropy — Full Comparison
| Property | Detail |
|---|---|
| Algorithm | CART (sklearn default) |
| Formula | 1 - Sum(pi^2) |
| Range (binary) | 0 to 0.5 |
| Range (n classes) | 0 to (n-1)/n |
| Computation | Faster — no logarithm |
| Sensitivity | Less sensitive to class distribution |
| Property | Detail |
|---|---|
| Algorithm | ID3, C4.5 |
| Formula | -Sum(pi . log2(pi)) |
| Range (binary) | 0 to 1.0 |
| Range (n classes) | 0 to log2(n) |
| Computation | Slower — log operation per class |
| Sensitivity | More sensitive — better for skewed distributions |
Gini is faster and the sklearn default — use it unless you have a reason not to. Entropy is more sensitive to class probabilities — better for skewed datasets. For binary classification like Play Tennis, they produce nearly identical trees. For large multi-class problems, entropy's extra sensitivity to small probability differences can matter.
How the CART Algorithm Builds the Tree
Try It — Watch the Tree Grow
40 past loan applicants: ● approved and ■ rejected, placed by credit score and debt ratio. Press Next to let the algorithm add one split at a time. Watch the boxes on the left and the tree on the right grow together. Change max_depth or min_samples_split to see other stopping rules in action.
कई Classes के लिए Entropy और Gini की Range
Play Tennis उदाहरण से एक ज़रूरी बात: entropy की सबसे बड़ी value classes की गिनती पर निर्भर करती है। अलग-अलग problems की तुलना करते समय यह मायने रखता है।
| Classes की गिनती (n) | Max Entropy = log2(n) | Max Gini = (n-1)/n |
|---|---|---|
| 2 (Binary — Play Tennis) | 1.000 | 0.500 |
| 3 | 1.585 | 0.667 |
| 4 | 2.000 | 0.750 |
| 5 | 2.322 | 0.800 |
| 10 | 3.322 | 0.900 |
1. यह कभी negative नहीं होती (सबसे कम = 0, जब node pure हो)।
2. जब सभी classes बराबर संभावना वाली हों, तब यह सबसे ज़्यादा होती है — तब system सबसे ज़्यादा अनिश्चित होता है।
3. Classes की गिनती बढ़ने पर यह बढ़ती है — 10 classes वाली problem में entropy 3.322 bits तक जा सकती है, जो binary की 1.0 की सीमा से बहुत ऊपर है।
अगर p1 = p2 = p3 = 1/3 (तीनों classes बराबर संभावना वाली):
Gini = 1 - ((1/3)^2 + (1/3)^2 + (1/3)^2) = 1 - (3 x 1/9) = 1 - 1/3 = 2/3 = 0.667
यह formula (n-1)/n = 2/3 से बिल्कुल मेल खाता है। Gini और Entropy दोनों तब सबसे ज़्यादा होते हैं जब classes पूरी तरह बराबर हों — तब आपको सही जवाब के बारे में कोई जानकारी नहीं होती।
Gini Impurity बनाम Entropy — पूरी तुलना
| गुण | विवरण |
|---|---|
| Algorithm | CART (sklearn default) |
| Formula | 1 - Sum(pi^2) |
| Range (binary) | 0 से 0.5 |
| Range (n classes) | 0 से (n-1)/n |
| हिसाब | तेज़ — कोई logarithm नहीं |
| संवेदनशीलता | Class distribution के लिए कम संवेदनशील |
| गुण | विवरण |
|---|---|
| Algorithm | ID3, C4.5 |
| Formula | -Sum(pi . log2(pi)) |
| Range (binary) | 0 से 1.0 |
| Range (n classes) | 0 से log2(n) |
| हिसाब | धीमा — हर class के लिए log निकालना पड़ता है |
| संवेदनशीलता | ज़्यादा संवेदनशील — टेढ़े-मेढ़े (skewed) distributions के लिए बेहतर |
Gini तेज़ है और sklearn का default है — जब तक कोई ख़ास वजह न हो, इसी को इस्तेमाल कीजिए। Entropy class probabilities के लिए ज़्यादा संवेदनशील है — skewed datasets के लिए बेहतर। Binary classification में, जैसे Play Tennis, दोनों लगभग एक जैसे trees बनाते हैं। बड़ी multi-class problems में, probability के छोटे फ़र्क़ के लिए entropy की ज़्यादा संवेदनशीलता मायने रख सकती है।
CART Algorithm Tree कैसे बनाता है
ख़ुद आज़माइए — Watch the Tree Grow
40 पुराने loan आवेदक: ● मंज़ूर और ■ नामंज़ूर, इन्हें credit score और debt ratio के हिसाब से रखा गया है। अगला split दबाइए, ताकि algorithm एक बार में एक split जोड़े। बाईं ओर के boxes और दाईं ओर का tree साथ-साथ बढ़ते देखिए। रुकने के दूसरे नियम काम करते देखने के लिए max_depth या min_samples_split बदलिए।
多分类时 entropy 和 Gini 的范围
Play Tennis 例子给我们一个重要启示:entropy 的最大值取决于类别的数量。比较不同问题时,这一点很重要。
| 类别数(n) | 最大 entropy = log2(n) | 最大 Gini = (n-1)/n |
|---|---|---|
| 2(二分类 — Play Tennis) | 1.000 | 0.500 |
| 3 | 1.585 | 0.667 |
| 4 | 2.000 | 0.750 |
| 5 | 2.322 | 0.800 |
| 10 | 3.322 | 0.900 |
1. 永远不是负数(最小值 = 0,此时 node 是纯的)。
2. 所有类别出现的可能性相同时最大,这时系统最不确定。
3. 类别越多,它越大:一个 10 类的问题,entropy 最高可达 3.322 bits,远高于二分类的上限 1.0。
如果 p1 = p2 = p3 = 1/3(三个类别可能性相同):
Gini = 1 - ((1/3)^2 + (1/3)^2 + (1/3)^2) = 1 - (3 x 1/9) = 1 - 1/3 = 2/3 = 0.667
这和公式 (n-1)/n = 2/3 完全一致。类别完全平衡时,Gini 和 entropy 都达到最大值。这时你对正确答案一点信息都没有。
Gini impurity 和 entropy — 全面对比
| 性质 | 说明 |
|---|---|
| 算法 | CART(sklearn 默认) |
| 公式 | 1 - Sum(pi^2) |
| 范围(二分类) | 0 到 0.5 |
| 范围(n 个类别) | 0 到 (n-1)/n |
| 计算 | 更快,不用算对数 |
| 敏感度 | 对类别分布不太敏感 |
| 性质 | 说明 |
|---|---|
| 算法 | ID3, C4.5 |
| 公式 | -Sum(pi . log2(pi)) |
| 范围(二分类) | 0 到 1.0 |
| 范围(n 个类别) | 0 到 log2(n) |
| 计算 | 更慢,每个类别都要算一次对数 |
| 敏感度 | 更敏感,更适合分布不均的数据 |
Gini 更快,而且是 sklearn 的默认值。没有特别理由就用它。 entropy 对类别概率更敏感,更适合不平衡的 dataset。 对于二分类 classification,比如 Play Tennis,两者得到的 tree 几乎一样。 对于很大的多分类问题,entropy 对小概率差别更敏感,这一点可能会有影响。
CART 算法是怎样建 tree 的
动手试试 — Watch the Tree Grow
40 个过去的贷款申请人:● 批准 和 ■ 拒绝,按信用分和负债率摆放。 按下一个 split,让算法每次加一个 split。看左边的方框和右边的 tree 一起生长。 改变 max_depth 或 min_samples_split,看看其他停止规则是怎样起作用的。
Overfitting and Pruning
Left unconstrained, a tree grows until every leaf is pure — memorising every training sample including noise. The Play Tennis tree happened to generalise perfectly because the dataset is clean. Real datasets have noise, and deep trees overfit badly.
| Tree Configuration | Train Accuracy | Test Accuracy | Verdict |
|---|---|---|---|
| max_depth=2 (shallow) | 87% | 86% | Slight underfitting |
| max_depth=4 (tuned) | 93% | 90% | Good fit |
| max_depth=None (full) | 100% | 82% | Severe overfitting |
A fully grown tree that achieves 100% training accuracy is always overfitting on real-world noisy data. An 18-point gap between train and test accuracy (as shown above) means the model memorised noise rather than learned the true pattern. Always evaluate on a held-out test set, never just on training data.
Try It — The Overfitting Lab
200 training applicants, but some labels are wrong on purpose (noise — like real data). Grow the tree deeper and watch the boxes shrink around single noisy points. The chart shows accuracy on the training data and on 1 000 new applicants for every depth.
Overfitting और Pruning
अगर tree पर कोई रोक न हो, तो वह तब तक बढ़ता है जब तक हर leaf pure न हो जाए — यानी वह हर training sample को, noise समेत, रट लेता है। Play Tennis tree संयोग से पूरी तरह सही generalise कर गया, क्योंकि dataset साफ़ है। असली datasets में noise होता है, और गहरे trees बुरी तरह overfit करते हैं।
| Tree की सेटिंग | Train Accuracy | Test Accuracy | नतीजा |
|---|---|---|---|
| max_depth=2 (उथला) | 87% | 86% | थोड़ा underfitting |
| max_depth=4 (tuned) | 93% | 90% | अच्छा fit |
| max_depth=None (पूरा) | 100% | 82% | गंभीर overfitting |
असली दुनिया के noisy data पर, पूरा बढ़ा हुआ tree जो 100% training accuracy देता है, वह हमेशा overfitting कर रहा होता है। Train और test accuracy में 18 points का फ़र्क़ (जैसा ऊपर दिखा है) बताता है कि model ने असली pattern सीखने के बजाय noise रट लिया। हमेशा अलग रखे गए test set पर जाँचिए, सिर्फ़ training data पर कभी नहीं।
ख़ुद आज़माइए — The Overfitting Lab
200 training आवेदक हैं, पर कुछ labels जान-बूझकर ग़लत रखे गए हैं (noise — असली data की तरह)। Tree को और गहरा कीजिए और देखिए कैसे boxes अकेले noisy points के चारों ओर सिकुड़ जाते हैं। Chart हर depth के लिए training data पर और 1 000 नए आवेदकों पर accuracy दिखाता है।
Overfitting 和 pruning
如果不加限制,tree 会一直长,直到每个 leaf 都是纯的。这样它会记住每个 training 样本,连噪声也记住。Play Tennis 的 tree 刚好泛化得很好,因为这个 dataset 很干净。真实的 dataset 有噪声,很深的 tree 会严重 overfitting。
| tree 的设置 | Training accuracy | Test accuracy | 结论 |
|---|---|---|---|
| max_depth=2(浅) | 87% | 86% | 轻微 underfitting |
| max_depth=4(调好的) | 93% | 90% | 拟合良好 |
| max_depth=None(完全长开) | 100% | 82% | 严重 overfitting |
在真实的、有噪声的数据上,一棵完全长开、training accuracy 达到 100% 的 tree,一定是 overfitting。training 和 test accuracy 相差 18 个百分点(如上表),说明 model 记住的是噪声,而不是学到真正的规律。一定要在单独留出的 test 集上评估,不要只看 training 数据。
动手试试 — Overfitting Lab
有 200 个 training 申请人,但有些标签是故意标错的(噪声,就像真实数据一样)。让 tree 长得更深,看看 方框怎样缩小,去包住单个噪声点。图表显示了每个 depth 下,在 training 数据和 1 000 个新申请人上的 accuracy。
Key Hyperparameters
| Hyperparameter | Default | Effect | Too Low | Too High |
|---|---|---|---|---|
max_depth | None (full) | Max levels from root to leaf | Underfitting | Overfitting |
min_samples_split | 2 | Min samples needed to split a node | Splits tiny nodes | Stops too early |
min_samples_leaf | 1 | Min samples in any leaf node | 1-sample leaves | Forces large leaves |
criterion | 'gini' | Splitting criterion | Use 'gini' (fast) or 'entropy' (sensitive). 'squared_error' for regression. | |
ccp_alpha | 0.0 | Post-pruning strength | No pruning (default) | Prunes too aggressively |
Try It — Hyperparameter Playground
Turn the three most useful knobs from the table and see how they change the tree, its boxes and its accuracy. The table below the chart tells you which rule stopped each leaf.
ज़रूरी Hyperparameters
| Hyperparameter | Default | असर | बहुत कम हो तो | बहुत ज़्यादा हो तो |
|---|---|---|---|---|
max_depth | None (पूरा) | Root से leaf तक ज़्यादा से ज़्यादा levels | Underfitting | Overfitting |
min_samples_split | 2 | किसी node को split करने के लिए कम से कम samples | बहुत छोटे nodes भी split होते हैं | बहुत जल्दी रुक जाता है |
min_samples_leaf | 1 | किसी भी leaf node में कम से कम samples | 1-sample वाली leaves | बड़ी leaves बनाने पर मजबूर करता है |
criterion | 'gini' | Split करने का पैमाना | 'gini' (तेज़) या 'entropy' (संवेदनशील) इस्तेमाल कीजिए। Regression के लिए 'squared_error'। | |
ccp_alpha | 0.0 | Post-pruning की ताक़त | कोई pruning नहीं (default) | बहुत ज़्यादा pruning कर देता है |
ख़ुद आज़माइए — Hyperparameter Playground
Table के तीन सबसे काम के knobs घुमाइए और देखिए कि tree, उसके boxes और उसकी accuracy कैसे बदलते हैं। Chart के नीचे की table बताती है कि हर leaf को किस नियम ने रोका।
关键的 hyperparameter
| Hyperparameter | 默认值 | 作用 | 太小时 | 太大时 |
|---|---|---|---|---|
max_depth | None(完全长开) | 从 root 到 leaf 的最大层数 | Underfitting | Overfitting |
min_samples_split | 2 | 一个 node 要 split,至少需要多少样本 | 连很小的 node 也会 split | 停得太早 |
min_samples_leaf | 1 | 每个 leaf node 至少要有多少样本 | 出现只有 1 个样本的 leaf | 强迫 leaf 变得很大 |
criterion | 'gini' | split 的标准 | 用 'gini'(快)或 'entropy'(敏感)。regression 用 'squared_error'。 | |
ccp_alpha | 0.0 | post-pruning 的强度 | 不做 pruning(默认) | pruning 太狠 |
动手试试 — Hyperparameter Playground
调整表格里最有用的三个旋钮,看看它们怎样改变 tree、方框和 accuracy。 图表下面的表格会告诉你,每个 leaf 是被哪条规则停下来的。
Python — Replicating the Play Tennis Example
Python — Play Tennis उदाहरण को दोबारा बनाना
Python — 重现 Play Tennis 例子
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.preprocessing import OrdinalEncoder
# The Play Tennis dataset — exactly as in the lecture
data = pd.DataFrame({
'Outlook' : ['Sunny','Sunny','Overcast','Rain','Rain','Rain',
'Overcast','Sunny','Sunny','Rain','Sunny','Overcast',
'Overcast','Rain'],
'Temp' : ['Hot','Hot','Hot','Mild','Cool','Cool','Cool',
'Mild','Cool','Mild','Mild','Mild','Hot','Mild'],
'Humidity': ['High','High','High','High','Normal','Normal','Normal',
'High','Normal','Normal','Normal','High','Normal','High'],
'Wind' : ['Weak','Strong','Weak','Weak','Weak','Strong','Strong',
'Weak','Weak','Weak','Strong','Strong','Weak','Strong'],
'PlayTennis': ['No','No','Yes','Yes','Yes','No','Yes','No','Yes',
'Yes','Yes','Yes','Yes','No']
})
X_raw = data[['Outlook','Temp','Humidity','Wind']]
y = (data['PlayTennis'] == 'Yes').astype(int)
enc = OrdinalEncoder()
X = enc.fit_transform(X_raw)
# Use entropy to replicate ID3 behaviour
dt = DecisionTreeClassifier(criterion='entropy', random_state=42)
dt.fit(X, y)
# Print the learned rules
rules = export_text(dt, feature_names=['Outlook','Temp','Humidity','Wind'])
print(rules)
# Feature importances — matches our hand-calculated IG table
for feat, imp in zip(['Outlook','Temp','Humidity','Wind'], dt.feature_importances_):
print(f" {feat:<12} importance: {imp:.4f}")
The tree structure matches perfectly: Outlook at root, Humidity on Sunny branch, Wind on Rain branch. Overcast always Yes. Temp gets 0.000 importance — it was never used, confirming our information gain table that ranked it last with only 0.029 bits. The machine learned exactly what the algebra told us.
Classification Tree — Bank Loan Approval
Tree का structure पूरी तरह मेल खाता है: root पर Outlook, Sunny branch पर Humidity, Rain branch पर Wind। Overcast हमेशा Yes। Temp को 0.000 importance मिली — इसका कभी इस्तेमाल नहीं हुआ। इससे हमारी information gain table सही साबित होती है, जिसमें यह सिर्फ़ 0.029 bits के साथ आख़िरी था। Machine ने ठीक वही सीखा जो गणित ने हमें बताया था।
Classification Tree — Bank Loan Approval
tree 的结构完全一致:root 是 Outlook,Sunny branch 上是 Humidity,Rain branch 上是 Wind。Overcast 永远是 Yes。Temp 的 importance 是 0.000:它从没被用过。这也证实了我们的 Information Gain 表,它在表中排最后,只有 0.029 bits。机器学到的,正是代数告诉我们的。
Classification tree — 银行贷款审批
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import accuracy_score, classification_report
np.random.seed(42)
n = 500
data = pd.DataFrame({
'credit_score' : np.random.randint(500, 850, n),
'annual_income' : np.random.randint(20, 150, n),
'debt_ratio' : np.random.uniform(0.1, 0.8, n),
'employment_years': np.random.randint(0, 20, n),
'num_accounts' : np.random.randint(1, 10, n),
})
approved = (
(data['credit_score'] >= 700) &
(data['annual_income'] >= 50) &
(data['debt_ratio'] <= 0.4)
) | (
(data['credit_score'] >= 650) &
(data['employment_years'] >= 5) &
(data['debt_ratio'] <= 0.35)
)
data['approved'] = approved.astype(int)
noise_idx = np.random.choice(n, size=50, replace=False)
data.loc[noise_idx, 'approved'] = 1 - data.loc[noise_idx, 'approved']
X = data.drop('approved', axis=1)
y = data['approved']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
# Compare depths — shows bias-variance tradeoff
for depth in [2, 5, None]:
dt = DecisionTreeClassifier(criterion='gini', max_depth=depth, random_state=42)
dt.fit(X_train, y_train)
train_acc = accuracy_score(y_train, dt.predict(X_train))
test_acc = accuracy_score(y_test, dt.predict(X_test))
print(f"depth={str(depth):>4} train={train_acc:.3f} test={test_acc:.3f} gap={train_acc-test_acc:+.3f}")
# GridSearchCV to find optimal hyperparameters
param_grid = {
'max_depth' : [2, 3, 4, 5, 6],
'min_samples_split': [5, 10, 20],
'min_samples_leaf' : [2, 5, 10],
'criterion' : ['gini', 'entropy'],
}
grid = GridSearchCV(DecisionTreeClassifier(random_state=42),
param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid.fit(X_train, y_train)
print(f"
Best params : {grid.best_params_}")
print(f"Best CV acc : {grid.best_score_:.4f}")
print(f"Test acc : {accuracy_score(y_test, grid.predict(X_test)):.4f}")
Feature Importances and Prediction
Feature Importances और Prediction
Feature importance 和 prediction
best_dt = grid.best_estimator_
# Feature importances
importances = pd.Series(best_dt.feature_importances_, index=X.columns).sort_values(ascending=False)
print("Feature Importances (MDI):")
print(importances.round(4))
# Predict a new applicant
new_applicant = pd.DataFrame([{
'credit_score': 720, 'annual_income': 65, 'debt_ratio': 0.30,
'employment_years': 8, 'num_accounts': 3
}])
pred = best_dt.predict(new_applicant)[0]
proba = best_dt.predict_proba(new_applicant)[0]
print(f"New applicant: {'Approved' if pred==1 else 'Rejected'}")
print(f"Confidence : Rejected={proba[0]:.2f} Approved={proba[1]:.2f}")
Credit Score (58%) is by far the most important feature — exactly what Ramesh said first. Just like Temp was irrelevant in Play Tennis, num_accounts (1%) barely contributes here. Feature importance scores let you validate machine-learned decisions against domain expertise — and when they disagree, that disagreement is worth investigating.
Advantages and Disadvantages
| Advantage | Why It Matters |
|---|---|
| Fully interpretable | Rules can be printed, audited, and explained to regulators |
| No feature scaling | No StandardScaler or normalisation needed |
| Handles mixed types | Works with numeric and categorical features together |
| Non-linear boundaries | Captures complex relationships without feature engineering |
| Fast prediction | O(log n) — just follow decision rules |
| Feature importance | Automatic ranking of which features matter most |
| Disadvantage | Impact |
|---|---|
| High variance / overfitting | Small data change can produce completely different tree |
| Axis-aligned splits only | Cannot capture diagonal boundaries without feature engineering |
| Greedy (local optima) | Each split is locally optimal — not globally best |
| Biased toward many-value features | IG favours features with many unique values |
| Unstable | Sensitive to outliers and noisy rows |
A single Decision Tree is rarely deployed alone in production. Its real power is as the building block of ensemble methods: Random Forests and Gradient Boosting (XGBoost, LightGBM) both build on Decision Trees and fix the variance problem. Understanding trees deeply means understanding why these powerful ensembles work.
Try It — Weak Spots
Two disadvantages from the table, live. Unstable: replace a few applicants and compare the two trees. Straight edges only: ask a tree to learn a diagonal rule.
Credit Score (58%) सबसे ज़्यादा ज़रूरी feature है — ठीक वही जो रमेश ने सबसे पहले कहा था। जैसे Play Tennis में Temp बेकार था, वैसे ही यहाँ num_accounts (1%) का योगदान बहुत कम है। Feature importance scores से आप machine के सीखे फ़ैसलों को किसी जानकार की समझ से मिलाकर जाँच सकते हैं — और जब दोनों में मेल न हो, तो उस फ़र्क़ की जाँच करना फ़ायदेमंद है।
फ़ायदे और नुक़सान
| फ़ायदा | यह क्यों ज़रूरी है |
|---|---|
| पूरी तरह समझने लायक | Rules को print, audit और regulators को समझाया जा सकता है |
| Feature scaling नहीं चाहिए | StandardScaler या normalisation की ज़रूरत नहीं |
| अलग-अलग types संभालता है | Numeric और categorical features के साथ एक साथ काम करता है |
| Non-linear boundaries | Feature engineering के बिना मुश्किल रिश्ते पकड़ लेता है |
| तेज़ prediction | O(log n) — बस decision rules पर चलना है |
| Feature importance | अपने आप बताता है कि कौन से features सबसे ज़्यादा मायने रखते हैं |
| नुक़सान | असर |
|---|---|
| High variance / overfitting | Data में छोटा सा बदलाव बिल्कुल अलग tree बना सकता है |
| सिर्फ़ axis के सीधे splits | Feature engineering के बिना तिरछी boundaries नहीं पकड़ सकता |
| Greedy (local optima) | हर split उस जगह के हिसाब से सबसे अच्छा है — पूरे tree के हिसाब से नहीं |
| ज़्यादा values वाले features की ओर झुकाव | IG उन features को पसंद करता है जिनमें बहुत सारी अलग values हों |
| अस्थिर | Outliers और noisy rows से जल्दी प्रभावित होता है |
Production में अकेला Decision Tree बहुत कम लगाया जाता है। इसकी असली ताक़त है ensemble methods की ईंट (building block) होना: Random Forests और Gradient Boosting (XGBoost, LightGBM) दोनों Decision Trees पर बने हैं और variance की problem ठीक करते हैं। Trees को गहराई से समझने का मतलब है यह समझना कि ये ताक़तवर ensembles क्यों काम करते हैं।
ख़ुद आज़माइए — Weak Spots
Table के दो नुक़सान, live। अस्थिर: कुछ आवेदक बदलिए और दोनों trees की तुलना कीजिए। सिर्फ़ सीधे किनारे: एक tree से तिरछा (diagonal) rule सीखने को कहिए।
信用分(58%)是最重要的 feature,远远领先。这正是 Ramesh 最先说的。就像 Temp 在 Play Tennis 里没有用处一样,num_accounts(1%)在这里几乎没有贡献。feature importance 分数能让你用领域经验去检查机器学到的决策。如果两者不一致,这个分歧就值得好好研究。
优点和缺点
| 优点 | 为什么重要 |
|---|---|
| 完全可解释 | 规则可以打印出来、可以审查,也能解释给监管人员听 |
| 不需要 feature scaling | 不需要 StandardScaler 或归一化 |
| 能处理混合类型 | 数值型和类别型 feature 可以一起用 |
| 非线性边界 | 不用做特征工程,也能抓住复杂的关系 |
| prediction 很快 | O(log n),只要沿着决策规则走就行 |
| Feature importance | 自动排出哪些 feature 最重要 |
| 缺点 | 影响 |
|---|---|
| variance 高 / overfitting | 数据稍微一变,就可能得到完全不同的 tree |
| 只能做和坐标轴平行的 split | 不做特征工程,就抓不住斜线边界 |
| 贪心(局部最优) | 每个 split 只是局部最优,不是全局最好 |
| 偏爱取值多的 feature | IG 偏爱唯一值很多的 feature |
| 不稳定 | 对异常值和有噪声的行很敏感 |
在实际生产中,很少单独部署一棵 Decision Tree。它真正的力量在于,它是 ensemble 方法的基本积木:Random Forest 和 Gradient Boosting(XGBoost、LightGBM)都建立在 Decision Tree 之上,并解决了 variance 的问题。深入理解 tree,就能明白这些强大的 ensemble 为什么有效。
动手试试 — Weak Spots
表格里的两个缺点,现场演示。不稳定:换掉几个申请人,然后比较两棵 tree。 只有直边:让 tree 去学一条斜线规则。