Decision Tree Classifier: How Does a Machine Learn to Make Decisions?
Machine Learning Series | Classification Algorithms | Article 06/10
Have you ever played a game where someone asks you a few questions, and based on your answers, they try to guess what you're thinking?
For example:
- Is it an animal?
- Does it live in water?
- Is it very big?
- Does it have four legs?
With every answer, the possibilities become smaller until the person finally guesses the correct answer.
Now imagine teaching a computer to play this game.
Sounds interesting, right?
That's almost exactly how a Decision Tree works!
In this article, we'll understand Decision Trees from the beginning. We'll explore how they make decisions, how they choose the best questions, what Entropy and Information Gain mean, how the ID3 algorithm works, and how we can build our own Decision Tree using Python.
Don't worry if you're new to Machine Learning. We'll take it one step at a time.
1. First, What Is a Decision Tree?
Let's forget computers for a moment.
Imagine your mother asks you:
"Should we go outside and play today?"
You might think about a few things:
- Is it raining?
- Is the weather sunny?
- Is it too hot?
- Is it safe to play outside?
Based on these answers, you make a decision.
A Decision Tree teaches a computer to make decisions in a similar way.
A Decision Tree is a supervised Machine Learning algorithm that learns a series of questions from data and uses their answers to make predictions.
In simple words:
It asks questions, follows the answers and reaches a final decision.
For example, imagine we want a computer to predict whether a student will play cricket.
It might learn these rules:
- Is it raining? If yes, don't play.
- If not, is it sunny?
- Is the temperature comfortable?
- Finally, decide whether to play or not.
The computer learns these rules by studying examples from the past.
That's the interesting part: we don't have to manually write every decision rule. The algorithm learns them from the training data.
2. Understanding a Decision Tree Through a Simple Example
Let's imagine we have a small dataset about playing cricket.
| Weather | Temperature | Play Cricket? |
|---|---|---|
| Sunny | Comfortable | Yes |
| Rainy | Cold | No |
| Sunny | Hot | Yes |
| Rainy | Comfortable | No |
| Cloudy | Comfortable | Yes |
| Cloudy | Hot | Yes |
We want to teach a computer to predict whether someone will play cricket based on the weather.
The computer looks at these examples and tries to discover patterns.
It might learn:
- If the weather is Rainy → No.
- If the weather is Sunny → Yes.
- If the weather is Cloudy → Yes.
Now, if we give it a new example:
Weather = Sunny
It predicts:
Play Cricket = Yes.
This is the basic idea behind a Decision Tree.
3. Understanding the Parts of a Decision Tree
A Decision Tree has different parts. Let's understand them using a simple family tree analogy.
1. Root Node
This is where everything begins.
Think of it as the first question in a quiz.
Example: "What is the weather?"
2. Decision Node
This is a point where the computer asks another question.
Example: "Is it raining?"
3. Branch
A branch represents an answer to a question.
Example: Yes or No.
4. Leaf Node
This is the final answer.
Example: Play or Don't Play.
5. Splitting
Splitting means dividing a big group of data into smaller groups based on a question.
6. Parent and Child Nodes
The original node is called the parent. The new nodes created from it are called children.
7. Depth
Depth tells us how many decision levels we travel from the root to a leaf.
Here is a simple example:
Is it raining?
/ \
Yes No
/ \
Don't Play Is it sunny?
/ \
Yes No
/ \
Play Play
Notice something?
The computer doesn't make one random guess. It follows a sequence of questions until it reaches an answer.
4. Types of Decision Trees
Decision Trees are mainly used for two kinds of predictions.
A. Classification Tree
Imagine you want to identify whether an email is:
- Spam
- Not Spam
The answer belongs to a category.
A Classification Tree predicts categories or classes.
Other examples:
- Fraud or Genuine transaction.
- Pass or Fail.
- Sick or Healthy.
- Will Buy or Won't Buy.
B. Regression Tree
Now imagine you want to predict the price of a house.
The answer isn't simply Yes or No. It is a number.
For example:
₹25 lakh, ₹40 lakh or ₹75 lakh.
A Regression Tree predicts numerical values.
Other examples:
- House prices.
- Monthly sales.
- Temperature.
- Product demand.
Remember:
Classification predicts a category.
Regression predicts a number.
5. How Does a Decision Tree Know Which Question to Ask First?
Now comes the most interesting part!
Imagine you have 100 students.
You want to divide them into two groups:
- Students who passed.
- Students who failed.
You could ask different questions:
- Did they attend classes regularly?
- Did they complete their homework?
- Did they study for the examination?
But which question should you ask first?
You would probably choose the question that separates the students most effectively.
A Decision Tree does something similar.
It tries to find the feature that creates the best separation between classes.
To understand how it does this, we need two important concepts:
- Entropy
- Information Gain
Let's understand them using everyday examples.
6. Entropy: How Mixed Is Our Data?
Imagine you have a box containing 10 balls.
Box A:
- 10 red balls.
- 0 blue balls.
If I ask you to pick a ball, you already know it will be red.
There is no uncertainty.
Box B:
- 5 red balls.
- 5 blue balls.
Now you don't know which color you'll get.
There is more uncertainty.
This is the basic idea of Entropy.
Entropy measures how mixed or uncertain the classes are in a dataset.
In Machine Learning, Entropy helps a Decision Tree understand how pure or mixed a group of examples is.
The Entropy formula
H(S) = -Σ pᵢ log₂(pᵢ)
Don't get scared by this formula!
Let's understand every part.
- H(S): Entropy of the dataset.
- S: Our collection of data.
- pᵢ: The fraction of examples belonging to a particular class.
- log₂: Logarithm with base 2.
- Σ: Add the results for all classes.
For two classes, Yes and No:
H(S) = -[p(Yes) log₂ p(Yes) + p(No) log₂ p(No)]
Understanding Entropy with numbers
Imagine our dataset contains 10 students.
- 8 passed.
- 2 failed.
Therefore:
p(Pass) = 8/10 = 0.8
p(Fail) = 2/10 = 0.2
Our formula becomes:
H(S) = -[0.8 log₂(0.8) + 0.2 log₂(0.2)]
After calculating:
Entropy ≈ 0.722
What does this tell us?
Our dataset contains both classes, so there is some uncertainty.
Let's compare:
| Data distribution | Entropy |
|---|---|
| 10 Pass, 0 Fail | 0 |
| 8 Pass, 2 Fail | 0.722 |
| 5 Pass, 5 Fail | 1 |
For binary classification:
- Entropy = 0 means all examples belong to one class.
- Entropy = 1 means the classes are equally mixed.
- Between 0 and 1 means different levels of uncertainty.
The important thing to remember:
A Decision Tree generally wants to create groups where most examples belong to the same class.
That's why lower Entropy is preferred.
7. Information Gain: Which Question Is More Useful?
Now we understand Entropy.
But how does the computer decide which question is better?
This is where Information Gain comes in.
Imagine you have 10 students.
Initially:
- 8 passed.
- 2 failed.
You want to divide them based on whether they completed their homework.
After asking this question, you get two groups.
Group A: Completed Homework
- 6 passed.
- 0 failed.
Group B: Did Not Complete Homework
- 2 passed.
- 2 failed.
Look at Group A.
Everyone passed!
It is a completely pure group.
Group B is still mixed.
The question about homework has helped us separate the students.
But how much has uncertainty actually reduced?
Information Gain measures exactly that.
Information Gain tells us how much uncertainty is reduced after splitting data using a particular feature.
The Information Gain formula
IG(S, A) = H(S) - Σᵥ (|Sᵥ| / |S|) × H(Sᵥ)
Let's understand the symbols:
- IG(S, A): Information Gain from feature A.
- H(S): Entropy before splitting.
- S: Original dataset.
- Sᵥ: A group created after splitting.
- |Sᵥ|: Number of examples in that group.
- |S|: Total number of examples.
The second part calculates the average Entropy of the new groups, giving larger groups more weight.
Let's calculate our example
Initial Entropy:
H(S) = 0.722
After splitting:
Group A:
- 6 passed.
- 0 failed.
- Entropy = 0.
Group B:
- 2 passed.
- 2 failed.
- Entropy = 1.
Weighted Entropy:
= (6/10 × 0) + (4/10 × 1)
= 0 + 0.4
= 0.4
Now:
Information Gain = 0.722 - 0.4
Information Gain = 0.322
This means the question about homework reduced uncertainty by 0.322 bits.
Why is Information Gain important?
Imagine we have three possible questions:
| Feature | Information Gain |
|---|---|
| Homework completed? | 0.322 |
| Favorite color? | 0.020 |
| Favorite movie? | 0.005 |
Which question should the Decision Tree choose?
Obviously, Homework!
Because it provides the highest Information Gain.
Remember this simple rule:
Higher Information Gain = Better split, according to this criterion.
8. What Is the ID3 Algorithm?
Now that we understand Entropy and Information Gain, we can finally understand how a Decision Tree is built.
One of the earliest and most important Decision Tree algorithms is called ID3 (Iterative Dichotomiser 3).
It was developed by Ross Quinlan.
ID3 uses Entropy and Information Gain to decide which feature should be selected at each step.
Let's understand how it works.
How ID3 builds a Decision Tree
Imagine you are organizing students into groups based on their examination results.
ID3 follows a similar process.
Step 1: Start with all the data
The entire dataset becomes the root node.
Step 2: Calculate Entropy
The algorithm checks how mixed the classes are.
Step 3: Examine every available feature
It calculates Information Gain for each feature.
For example:
- Attendance.
- Homework.
- Study Hours.
- Previous Results.
Step 4: Select the feature with the highest Information Gain
The best feature becomes the decision node.
Step 5: Divide the dataset
The data is separated according to the selected feature's values.
Step 6: Repeat the process
The algorithm checks each new group and continues selecting useful features.
Step 7: Stop when a stopping condition is reached
For example:
- All examples in a group belong to the same class.
- No unused features remain.
- Another stopping condition is reached.
If a group still contains different classes but no features remain, ID3 can use the majority class as its prediction.
That's how the complete tree is created!
ID3 in simple pseudocode
Start with the complete dataset.
If all examples belong to one class:
Return that class.
If no features remain:
Return the majority class.
Calculate Entropy.
Calculate Information Gain for every feature.
Select the feature with the highest Information Gain.
Create a decision node.
Divide the dataset using that feature.
Repeat the process for every new group.
Return the completed tree.
One important point: ID3 is a greedy algorithm. It chooses the best available feature at the current step. It doesn't test every possible tree to guarantee a globally perfect solution.
9. Other Important Decision Tree Algorithms
ID3 is not the only algorithm used to build Decision Trees.
Let's understand some other important ones.
A. ID3
- Uses Entropy.
- Selects features using Information Gain.
- Originally designed for categorical features.
- Does not have built-in pruning in its original form.
B. C4.5
C4.5 is an extension of ID3.
It introduces improvements such as:
- Gain Ratio.
- Handling continuous features.
- Handling missing values.
- Tree pruning.
C. CART
CART stands for Classification and Regression Trees.
It can solve both classification and regression problems.
It generally creates binary splits, meaning every decision divides the data into two groups.
It commonly uses:
- Gini Impurity for classification.
- Squared-error-based criteria for regression.
D. CHAID
CHAID stands for Chi-square Automatic Interaction Detection.
It uses statistical tests to identify useful relationships between features and the target.
It can create multiple branches from a decision node.
Quick comparison
| Algorithm | Main splitting approach |
|---|---|
| ID3 | Information Gain |
| C4.5 | Gain Ratio |
| CART | Gini / Squared Error |
| CHAID | Chi-square statistical tests |
10. What Is Gini Impurity?
We've learned that ID3 uses Entropy.
But some Decision Tree algorithms use another measurement called Gini Impurity.
Think about our box of colored balls again.
If every ball is red, the box is pure.
If the box contains different colors, it is less pure.
Gini Impurity measures how likely it is that a randomly selected example would be incorrectly classified if we assigned its label according to the class proportions in that group.
Formula
Gini(S) = 1 - Σ pᵢ²
For two classes:
Gini(S) = 1 - [p(Yes)² + p(No)²]
Suppose we have:
- 8 Yes.
- 2 No.
Gini = 1 - [(0.8)² + (0.2)²]
Gini = 1 - [0.64 + 0.04]
Gini = 0.32
Lower Gini means a purer group.
Entropy vs Gini
| Entropy | Gini Impurity |
|---|---|
| Measures uncertainty | Measures impurity |
| Uses logarithms | Uses squared probabilities |
| Used by ID3 | Commonly used by CART |
| Lower is better | Lower is better |
Both help Decision Trees choose useful splits.
11. How Does a Decision Tree Handle Numbers?
So far, we've used categories such as Sunny, Rainy, Yes and No.
But real-world datasets also contain numerical values.
For example:
| Age | Salary | Purchased? |
|---|---|---|
| 18 | 15000 | No |
| 25 | 30000 | Yes |
| 35 | 50000 | Yes |
| 45 | 25000 | No |
| 50 | 70000 | Yes |
How does a Decision Tree decide where to split numerical data?
It can test possible threshold values.
For example:
Age ≤ 30?
- Yes → One group.
- No → Another group.
The algorithm evaluates candidate thresholds and chooses a useful split based on its splitting criterion.
This is how modern Decision Tree implementations work with numerical features.
12. Let's Build a Decision Tree Using Python!
Enough theory. Now let's see how we can build one ourselves.
We'll use the famous Iris dataset.
Imagine we want to identify which type of flower we are looking at.
The Iris dataset contains three flower species:
- Setosa.
- Versicolor.
- Virginica.
It provides four measurements:
- Sepal length.
- Sepal width.
- Petal length.
- Petal width.
Our goal is to teach a computer to identify the flower species using these measurements.
Step 1: Import the libraries
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import (
DecisionTreeClassifier,
plot_tree
)
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix
)
What are these libraries for?
- Matplotlib helps us create graphs.
- Scikit-learn provides Machine Learning tools.
- load_iris loads our flower dataset.
- train_test_split divides the data.
- DecisionTreeClassifier creates our model.
- plot_tree displays the learned tree.
Step 2: Load the dataset
iris = load_iris()
X = iris.data
y = iris.target
print("Features:", iris.feature_names)
print("Classes:", iris.target_names)
print("Dataset shape:", X.shape)
Here:
- X contains the input features.
- y contains the correct flower labels.
The dataset has 150 observations and four features.
Step 3: Divide the dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
Why do we divide the data?
Imagine teaching a student using 80 questions and then giving them 20 new questions to test their understanding.
We do something similar here.
- 80% is used for training.
- 20% is used for testing.
Step 4: Create the Decision Tree
model = DecisionTreeClassifier(
criterion="entropy",
max_depth=3,
random_state=42
)
model.fit(X_train, y_train)
Let's understand the parameters:
- criterion="entropy": Uses Entropy to evaluate splits.
- max_depth=3: Limits the tree to three decision levels.
- random_state=42: Makes the randomized behavior reproducible.
The fit() method trains the model using our training data.
A technical detail: Scikit-learn uses CART-style binary splitting. Setting criterion="entropy" uses information gain based on entropy, but does not make this implementation the original ID3 algorithm.
Step 5: Make predictions
y_pred = model.predict(X_test)
print("Predictions:", y_pred)
The model now uses its learned decision rules to predict the flower species.
Step 6: Check the performance
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print(
classification_report(
y_test,
y_pred,
target_names=iris.target_names
)
)
print(confusion_matrix(y_test, y_pred))
Here we check:
- Accuracy: How many predictions were correct?
- Precision: When the model predicts a class, how often is it correct?
- Recall: How many actual examples of a class did the model identify?
- F1-score: A combined measure of precision and recall.
Step 7: Visualize the Decision Tree
This is one of my favorite parts!
plt.figure(figsize=(18, 10))
plot_tree(
model,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True,
rounded=True,
fontsize=10
)
plt.title("Decision Tree Classifier")
plt.show()
Now we can actually see how the computer makes decisions.
Instead of treating the model like a black box, we can inspect the questions it learned.
13. What Is Overfitting in a Decision Tree?
Imagine a student memorizes every question and answer in a textbook.
They may perform very well when asked the same questions.
But when they receive a completely new question, they struggle.
This is similar to overfitting in Machine Learning.
A Decision Tree can grow very deep and memorize details from the training dataset.
As a result:
- Training performance can become very high.
- Testing performance may become poor.
- The model may fail to generalize to new data.
This is why controlling the size of a tree is important.
14. What Is Pruning?
Imagine a tree in your garden.
If too many unnecessary branches grow, you trim some of them to keep the tree healthy and manageable.
Pruning in Decision Trees works in a similar way.
It means removing unnecessary branches to reduce the complexity of the model.
There are two common types.
1. Pre-pruning
We stop the tree from growing too much.
For example:
- max_depth
- min_samples_split
- min_samples_leaf
2. Post-pruning
We first grow the tree and then remove branches that do not provide enough value.
One commonly used method in CART is Cost-Complexity Pruning.
The goal is to create a model that works well on new data, not just training data.
15. Advantages of Decision Trees
Why do developers and data scientists use Decision Trees?
- Easy to understand: Their decisions can be represented as simple questions.
- Easy to visualize: We can draw the complete tree.
- Works with nonlinear patterns: It can learn relationships that are not simple straight lines.
- Supports different tasks: It can handle classification and regression.
- Less preprocessing: Feature scaling is generally not necessary.
- Useful for explanations: Small trees can help people understand why a prediction was made.
16. Disadvantages of Decision Trees
Like every Machine Learning algorithm, Decision Trees also have limitations.
- Overfitting: A very deep tree may memorize the training data.
- Unstable: Small changes in training data can produce a different tree.
- Greedy learning: It does not guarantee the globally best tree.
- Complex trees: Very large trees can become difficult to understand.
- Feature selection bias: Some impurity-based splitting methods can favor features with many possible values.
That's why we need proper training, testing and model evaluation.
17. Where Are Decision Trees Used in Real Life?
Let's connect what we've learned to actual industries.
Banking
A bank can use classification models to help assess whether a loan application represents a high or low credit risk.
Healthcare
A Decision Tree can help classify medical records based on symptoms and test results.
Cybersecurity
A model can help classify network activity as normal or suspicious.
E-commerce
An online store can predict whether a customer is likely to purchase a product.
Manufacturing
Decision Trees can help classify products as defective or non-defective.
These are examples of potential applications. Real-world systems require careful validation, data quality checks and domain expertise.
18. Decision Tree vs K-Nearest Neighbors
In our previous article, we explored K-Nearest Neighbors (KNN).
Both algorithms can solve classification problems, but they work differently.
| Decision Tree | KNN |
|---|---|
| Learns decision rules | Uses nearby training examples |
| Follows branches | Calculates distances |
| Generally fast at prediction | Prediction can be slower on large datasets |
| Usually less sensitive to feature scaling | Often sensitive to feature scaling |
| Can be visualized as a tree | Uses the neighborhood of each observation |
The interesting thing is that both algorithms can learn from the same dataset but make predictions using completely different approaches.
19. What Have We Learned?
Let's quickly revise everything:
- A Decision Tree learns decisions from examples.
- It contains root nodes, decision nodes, branches and leaf nodes.
- Classification Trees predict categories.
- Regression Trees predict numerical values.
- Entropy measures uncertainty or impurity.
- Information Gain measures how much uncertainty is reduced.
- ID3 selects features using Information Gain.
- C4.5 improves on ID3.
- CART supports classification and regression.
- Gini Impurity is another splitting criterion.
- Pruning helps reduce unnecessary complexity.
- Python's Scikit-learn makes implementation straightforward.
The most important thing to remember:
A Decision Tree learns which questions to ask, in what order to ask them, and how to reach a prediction using the answers.
What's Next?
We've now explored three algorithms in our Machine Learning Classification series:
- Logistic Regression
- K-Nearest Neighbors (KNN)
- Decision Tree Classifier
And our next topic is:
Random Forest Classifier — How Can a Group of Decision Trees Make Better Predictions?
We'll discover how multiple Decision Trees work together, how they combine their predictions, and why this approach can be more powerful than using a single tree.
If you're learning Machine Learning with me, let's continue this journey together.
My goal with this series is simple:
I don't just want to learn an algorithm. I want to understand it well enough to explain it to someone who is learning it for the very first time.
Learn it. Understand it. Build it. Teach it.
Happy Learning! 🚀
Top comments (0)