Machine Learning from Scratch – Day 8: Understanding Decision Trees
Understanding Decision Trees
Series: Machine Learning From Scratch (18 articles)
- …
- 8Machine Learning from Scratch – Day 8: Understanding Decision Trees This article
Introduction
Welcome to Day 8 of our Machine Learning from Scratch series!
In Day 7, we explored Logistic Regression and learned how machines classify data into categories using probabilities.
Today, we're going to learn about another interesting Machine Learning algorithm: Decision Trees.
Have you ever made a decision by asking yourself a series of questions?
For example:
- Is it raining?
- Do I have an umbrella?
- Should I go outside?
Based on the answers, you make a final decision.
Decision Trees work in a similar way. They make predictions by asking a sequence of questions about the input data.
Let's understand how they work!
1. What is a Decision Tree?
A Decision Tree is a Supervised Machine Learning algorithm used for both classification and regression problems.
It works by splitting a dataset into smaller groups based on conditions applied to different features.
Each decision helps the model move toward a final prediction.
Real-world applications:
- Loan approval prediction.
- Customer churn prediction.
- Medical diagnosis support.
- Fraud detection.
- Student performance prediction.
The biggest advantage is that Decision Trees are relatively easy to understand and interpret.
2. Understanding the Structure of a Decision Tree
A Decision Tree consists of three important components.
A. Root Node
The starting point of the tree.
It represents the entire dataset and contains the first decision.
B. Decision Node
A node where the dataset is divided based on a particular condition.
For example: Is the person's age greater than 18?
C. Leaf Node
The final node that provides the prediction or output.
For example: Approved or Rejected.
3. How Does a Decision Tree Work?
Let's understand using a simple example.
Imagine a bank wants to predict whether a customer is eligible for a loan.
The model considers features such as:
- Age.
- Monthly income.
- Credit score.
- Existing debt.
The model creates decision rules based on patterns in historical data.
For example:
- Is the credit score above a certain threshold?
- Is the monthly income sufficient?
- Is the existing debt manageable?
Based on the answers, the model reaches a final prediction.
Important: These conditions are learned from training data. They are not necessarily manually programmed by developers.
4. How Does a Decision Tree Choose the Best Split?
This is one of the most important concepts in Decision Trees.
A Decision Tree needs to determine which feature should be used to split the dataset at each step.
It uses mathematical measures to identify useful splits.
Two commonly used measures are:
A. Gini Impurity
Gini Impurity measures how mixed the classes are within a group.
\[ Gini = 1-\sum_{i=1}^{n}p_i^2 \]
Where:
- \(p_i\) = Proportion of samples belonging to class \(i\).
- \(n\) = Number of classes.
A Gini value of 0 indicates a pure group containing only one class.
Lower impurity generally indicates a better split.
B. Entropy and Information Gain
Entropy measures the uncertainty or disorder in a dataset.
\[ Entropy=-\sum_{i=1}^{n}p_i\log_2(p_i) \]
Information Gain measures how much uncertainty is reduced after splitting the data.
\[ Information\ Gain = Entropy(parent)-Weighted\ Entropy(children) \]
A Decision Tree generally prefers splits that provide greater information gain.
5. Types of Decision Trees
Decision Trees are commonly used for two types of problems.
A. Classification Trees
Used to predict categories or class labels.
Examples:
- Spam or Not Spam.
- Pass or Fail.
- Fraudulent or Genuine.
B. Regression Trees
Used to predict continuous numerical values.
Examples:
- House prices.
- Sales revenue.
- Product demand.
The main difference is the type of output they predict.
6. Practical Implementation Using Python
Now let's build our first Decision Tree model using Scikit-learn.
We'll use the Iris dataset to classify flowers.
Step 1: Import the required libraries
from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scoreStep 2: Load the dataset
iris = load_iris()X = iris.datay = iris.targetStep 3: Split the dataset
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)Step 4: Create and train the model
model = DecisionTreeClassifier( criterion="gini", max_depth=3, random_state=42)model.fit(X_train, y_train)Step 5: Make predictions
predictions = model.predict(X_test)print("Predictions:", predictions)Step 6: Evaluate the model
accuracy = accuracy_score(y_test, predictions)print("Model Accuracy:", accuracy)Step 7: Visualize the Decision Tree
import matplotlib.pyplot as pltfrom sklearn.tree import plot_treeplt.figure(figsize=(14, 8))plot_tree( model, feature_names=iris.feature_names, class_names=iris.target_names, filled=True)plt.show()What did we accomplish?
- Loaded a real-world dataset.
- Divided the dataset into training and testing sets.
- Created a Decision Tree classifier.
- Trained the model.
- Predicted flower categories.
- Evaluated the model's performance.
- Visualized the decision-making process.
We have successfully implemented another Machine Learning algorithm!
7. Advantages and Limitations
Advantages | Limitations |
|---|---|
Easy to understand | Can easily overfit |
Handles numerical and categorical features with suitable preprocessing | Small data changes can produce different trees |
Requires little feature scaling | Can become complex |
Supports classification and regression | May generalize poorly without proper tuning |
One important parameter is .
max_depth It controls how deep the tree can grow.
Limiting the depth can help reduce overfitting, although the best value depends on the dataset.
8. Real-World Applications
Decision Trees are used in several industries:
- Banking: Assessing loan eligibility and credit risk.
- Healthcare: Supporting medical classification tasks.
- E-commerce: Understanding customer purchasing behavior.
- Education: Predicting student performance.
- Cybersecurity: Classifying potentially malicious activities.
Conclusion
Today, we explored Decision Trees and learned how machines make predictions through a sequence of data-driven decisions.
Let's revise the important concepts:
- Decision Trees are Supervised Learning algorithms.
- They support classification and regression.
- Root nodes, decision nodes, and leaf nodes form their structure.
- Gini Impurity and Entropy help determine useful splits.
- Information Gain measures the reduction in uncertainty.
-
max_depthhelps control model complexity.
The interesting part is that Decision Trees make Machine Learning decisions easier to visualize and interpret.
However, deeper trees are not always better. A highly complex tree can memorize training data and suffer from overfitting.
Coming Next – Day 9: Understanding Random Forest – Combining Multiple Decision Trees.
We'll explore how multiple decision trees work together to make more reliable predictions.
Series: Machine Learning From Scratch (18 articles)
- …
- 8Machine Learning from Scratch – Day 8: Understanding Decision Trees This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article