Tree based algorithms are a core part of machine learning because they simulate human like decision making in a structured way. They build models in the form of decision trees, where data is split step by step based on feature values until a final prediction is reached. This recursive partitioning of the feature space makes the model both logical and easy to interpret. In tree based algorithms:
- Each internal node represents a decision based on a feature.
- Each branch represents the outcome of that decision.
- Each leaf node gives the final prediction (classification or regression).
- The model selects the best feature at every step to split the data effectively.
- They are transparent, easy to understand and widely used in practical applications.

How do Tree based algorithm work?
The workflow generally follows these steps:
- Feature Splitting: Select the most informative feature using criteria like Gini or Entropy.
- Recursive Partitioning: Split the dataset into subsets and repeat the process.
- Stopping Criteria: Stop splitting when maximum depth or minimum samples are reached.
- Prediction: Assign class (classification) or average value (regression) at leaf nodes.
1. Decision Tree
A Decision Tree is the core engine behind most tree based algorithms. It builds a structured flow of decisions by splitting data into smaller subsets using a mathematical criterion. Models like Random Forest and Gradient Boosting are simply advanced ensembles built on this foundation. The Structural Elements of Decision Tree includes:

- Root Node: Starting point of the tree. It contains the full dataset before any split.
- Decision Node: A feature based rule (e.g., Age > 30?) that splits data into smaller groups.
- Leaf Node: Final node that gives the prediction class label (classification) or average value (regression).
- Splitting Criterion: Mathematical rule used to choose the best feature for splitting.
Decision Tree Implementation
Here we implement Decision tree using sklearn. We can also switch between Gini and Entropy using the criterion parameter.
- Loads the Breast Cancer dataset using load_breast_cancer() to get features (X) and labels (y).
- Creates a DecisionTreeClassifier using Gini impurity, with max_depth=2 for simplicity and random_state=42 for consistent results.
- Trains the model using clf.fit(X, y).
- Visualizes the learned decision rules using tree.plot_tree(..., filled=True) with color-coded nodes.
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
import matplotlib.pyplot as plt
data = load_breast_cancer()
X, y = data.data, data.target
clf = DecisionTreeClassifier(criterion='gini', random_state=42,max_depth=2)
clf.fit(X, y)
plt.figure(figsize=(12,8))
tree.plot_tree(clf, feature_names=data.feature_names, filled=True)
plt.show()
Output:

Each box shows the split rule, Gini value (impurity), number of samples and class distribution [class0, class1]. The tree first splits on worst radius, then further divides the data. Low Gini values in leaf nodes indicate confident predictions. Since max_depth=2, the tree is small and easy to interpret.
2. Random Forest
Random Forest is an Ensemble Learning Technique which enhances a single Decision Tree by building multiple trees and combining their outputs. Instead of depending on one model, it aggregates predictions from many trees to produce a more stable and accurate result. It performs better by :
- Reduces overfitting compared to a single tree
- Improves overall prediction accuracy
- Handles noisy and large datasets effectively
- Introduces randomness for stronger generalization

Random Forest Implementation
This code trains a Random Forest Classifier on the Breast Cancer dataset and evaluates its performance.
1. RandomForestClassifier(n_estimators=100, random_state=42):
- Builds 100 decision trees.
- random_state=42 ensures reproducible results.
2. rf.fit(X_train, y_train): trains the model on training data.
3. rf.predict(X_test): generates predictions on test data.
4. accuracy_score(...): calculates how many predictions were correct.
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
predictions = rf.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
Output:
Accuracy: 0.96
3. Gradient Boosting
Gradient Boosting is an ensemble method where trees are built one after another and each new tree learns from the mistakes (residual errors) of the previous trees. Instead of averaging independent trees like Random Forest, it improves the model step by step using gradient descent optimization. Main points to consider are:
- Uses small, shallow trees (weak learners).
- Each tree minimizes the previous modelâs errors.
- Learns slowly using a learning rate parameter.
- Delivers high accuracy but requires tuning to avoid overfitting.
Gradient Boosting Implementation
Important Parameters
- n_estimators : number of boosting stages (more trees = more learning).
- learning_rate : controls how much each tree contributes.
- max_depth : controls complexity of individual trees.
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
gb = GradientBoostingClassifier(
n_estimators=100,
learning_rate=0.1,
max_depth=3,
random_state=42
)
gb.fit(X_train, y_train)
predictions = gb.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
Output:
Accuracy: 0.956
You can download code for all algorithms from here
4. XGBoost
XGBoost (Extreme Gradient Boosting) is an advanced and optimized implementation of Gradient Boosting designed for speed, scalability and high performance. It improves the standard boosting approach by adding system level optimizations and regularization techniques.
- Uses both L1 and L2 regularization to reduce overfitting.
- Supports parallel processing, making it faster than traditional Gradient Boosting.
- Handles missing values automatically.
- Includes built in tree pruning to control model complexity.
- Widely used in real world applications and ML competitions due to strong accuracy.
5. AdaBoost
AdaBoost (Adaptive Boosting) is an ensemble technique that converts multiple weak learners into a strong learner by training models sequentially and adjusting focus toward difficult samples at every step. Instead of correcting residual errors like Gradient Boosting, it modifies the weights of training data to emphasize previously misclassified points.
- Starts by assigning equal weights to all training samples.
- After each model, incorrectly classified samples receive higher weights, forcing the next learner to focus on them.
- Each weak learner (often a decision stump, which is a decison tree with depth=1 tree) is assigned a model weight based on its accuracy.
- Final prediction is made using weighted voting (classification) or weighted sum (regression).
- Works best when weak learners perform slightly better than random guessing.
- Sensitive to noisy data and outliers because difficult samples keep gaining weight.
6. LightGBM
LightGBM (Light Gradient Boosting Machine) is a high performance boosting framework built to handle large scale and high dimensional data efficiently. It improves traditional Gradient Boosting by optimizing both speed and memory usage while maintaining strong predictive power.
- Uses histogram based learning, which groups continuous feature values into bins to significantly speed up training.
- Grows trees leaf wise (best first) instead of level wise, allowing it to reduce loss more effectively and often achieve higher accuracy.
- Designed for low memory consumption, making it suitable for large datasets.
- Supports parallel and GPU learning for faster computation.
- Performs exceptionally well when dealing with large datasets and many features.
- Because of aggressive leaf wise growth, it may overfit if parameters like max_depth or num_leaves are not properly tuned.
7. CatBoost
CatBoost (Categorical Boosting) is a Gradient Boosting algorithm designed to efficiently handle datasets with categorical features. It reduces the need for complex preprocessing while maintaining strong predictive performance.
- Automatically processes categorical variables without requiring manual encoding like one hot encoding.
- Uses ordered boosting, which helps reduce prediction shift and target leakage during training.
- Implements efficient encoding techniques that improve stability and accuracy.
- Requires minimal hyperparameter tuning compared to other boosting algorithms.
- Works especially well on structured and tabular data common in business and real world applications.
- Provides consistent performance even with complex categorical relationships.
Advantages of Tree Based Algorithms
Tree based algorithms are widely used because they are simple, powerful and practical for many real world problems.
- Easy to Understand: Decision trees follow a step by step structure, just like human decision making. Each split is clear and logical, making the model easy to interpret and explain.
- Versatile : They can be used for both classification and regression tasks. From predicting categories to estimating numerical values, tree based models adapt well to different types of problems.
- Strong at Pattern Detection: These algorithms automatically identify important features and relationships in the data. They can capture complex, non linear patterns without requiring heavy data transformation.
- Transparent Decision Making: Unlike many black box models, tree based algorithms clearly show how decisions are made. This transparency builds trust and makes debugging or analysis easier.
Limitations of Tree Based Algorithms
Some of the disadvantages of Tree-Based algorithms are discussed below:
- Overfitting : Decision trees can easily memorize training data, especially when they grow too deep. This leads to overfitting, where the model performs well on training data but poorly on unseen data. Proper tuning and pruning are required to control this issue.
- Sensitivity to small changes: A small change in the dataset can sometimes result in a completely different tree structure. This makes individual decision trees unstable, particularly when dealing with noisy or highly variable data.
- High complexity: While a single decision tree is simple to understand, ensemble methods like Random Forest or Gradient Boosting combine many trees. This increases computational cost and reduces interpretability, making the overall model harder to manage and explain.

