Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Machine Learning for Finance & Accounting Level Two · Lesson 5 of 9

Module Four

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
5
Module 4: Tree-Based Models & Feature Importance for Young Coders
⭐ Module 4 · Level Two

Tree‑Based Models
& Feature Importance

🌲 Many small decisions beat one big rule

🎯 What you'll learn in this module

  • ✔ How random forests combine many trees into one strong model
  • ✔ How gradient boosting (XGBoost, LightGBM) learns from mistakes
  • ✔ Two kinds of feature importance: impurity and permutation
  • ✔ How to tune hyperparameters with cross‑validation
  • ✔ What overfitting looks like — and how to stop it
  • ✔ How tree models compare to linear models in finance
🌳
From One Tree to a Forest
The Big Idea

In the last module, we met the decision tree — a single chain of yes/no questions. A tree is easy to read but easy to overfit: it memorizes training data instead of learning patterns.

Random forests fix this by growing hundreds of different trees, each on a random slice of the data and features, then averaging their votes. One tree can be fooled, but 300 trees rarely are.

👥 One friend's guess might be wrong. Ask 300 friends and the average guess is usually close to the truth — that's a random forest.
🌲🌲
Random Forests: Wisdom of the Crowd
Model

A random forest works in three steps:

1. Bootstrap: each tree gets a random sample of the rows (with replacement).

2. Random features: at each split, only a random subset of features is considered.

3. Vote: for classification, take the majority vote; for regression, average the predictions.

This randomness makes trees diverse, and diversity is what kills overfitting. Random forests are great out‑of‑the‑box — barely any tuning needed.

🎲 Like a jury where each juror only sees part of the evidence: their individual opinions vary, but their consensus is usually strong.
🚀
Gradient Boosting: Learn From Every Mistake
Model

Gradient boosting builds trees one at a time. Each new tree is trained to fix the mistakes of all the previous ones. After 100 iterations, you have a strong model — each tree filling in gaps the others missed.

Popular libraries: XGBoost, LightGBM, and CatBoost. These dominate real‑world ML competitions and often beat everything else on tabular financial data.

The catch: they overfit if not tuned carefully, and they're harder to explain than a single tree or a linear model.

🎓 A student who reviews every mistake and studies it intensively: each session fixes one weakness, and after enough sessions, they ace the exam.
📊
Feature Importance: Which Features Matter?
Interpretability

After training a tree model, one of the most useful outputs is feature importance — a ranking of which inputs contributed most to predictions. Two main types:

Impurity‑based (built in): how much each feature reduces "impurity" across all splits. Fast, but can favour high‑cardinality features.

Permutation (external): shuffle one feature and see how much predictions worsen. Slower, but more honest. In finance, permutation is preferred because it reflects real impact.

Income
88%
Credit history
72%
Existing debt
55%
Age
22%
City
8%
🔍 Feature importance is like reading a sports team's stats: which players actually contribute to the wins?
🎛️
Hyperparameter Tuning with Cross‑Validation
Training

Every tree model has hyperparameters — settings you choose before training. Key examples:

Hyperparameter What It Does Typical Values
n_estimators Number of trees 100–1000
max_depth Maximum tree depth 3–20
learning_rate How much each tree contributes (boosting) 0.01–0.3
min_samples_leaf Min rows per leaf (prevents overfitting) 1–20

Tune with cross‑validation — split the training data multiple times and pick settings that perform consistently, not just on one lucky split.

🎚️ Hyperparameters are like tuning knobs on a stereo: small adjustments change the sound a lot. Find the sweet spot with practice, not guessing.
🎭
Overfitting: Memorizing vs. Learning
Warning

An overfit model looks fantastic on training data but fails on new data. It memorized the noise instead of learning the pattern.

How to spot it: training accuracy = 99%, validation accuracy = 70%. That gap is overfitting. Fixes: limit tree depth, require more samples per leaf, use regularization, and get more data.

Underfitting is the opposite: model too simple, poor on both training and validation. The goal is the sweet spot — a model that generalizes well.

📖 An overfit student memorized the exact answers to last year's exam. A new exam stumps them. A well‑trained student learned the underlying concepts and can handle new questions.
⚖️
Tree Models vs. Linear Models
Comparison
Property Linear Models Tree Models
Interpretability High (coefficients) Medium (importance rankings)
Accuracy on complex data Good Excellent
Handles non‑linearity Needs manual features Built‑in
Training speed Very fast Slower
Regulatory comfort Very high Medium (needs SHAP etc.)

In finance, both have their place: linear models for regulated credit scoring, tree models for fraud detection and complex predictions.

🔧 A hammer and a power drill both drive screws — pick the right tool for the job.
📊 Training data
→
🌲 Grow trees
→
🎛️ Tune hyperparameters
→
📊 Check importance
→
🎯 Final model
⚠️ The interpretability trap: Tree models often outperform linear ones, but that extra power comes at the cost of transparency. If your model will be used to deny a loan or reject an application, you need explainability — pair trees with SHAP, permutation importance, or switch back to logistic regression. Accuracy alone is not enough in finance.

🛠️ Hands-on activities (no boring stuff!)

1

Forest intuition: In one sentence each, explain why (a) 300 trees outperform 1 tree, and (b) random feature selection at each split matters. Focus on the word "diversity."

2

Boost by hand: Imagine predicting house prices with 3 boosting rounds. Round 1 predicts $200k (truth $250k, error $50k). Round 2 predicts $40k to fix the error. Round 3 predicts $8k more. Final prediction = $248k. Explain in 2 sentences how boosting chained those fixes.

3

Read the bar chart: Look at the feature importance chart above. Which feature mattered most? Which mattered least? Write one sentence about why this matters for a bank making credit decisions.

4

Permutation test: Explain in 2 sentences how you'd measure permutation importance for a single feature: what do you change, what do you observe, and how do you judge the result?

5

Overfitting detective: A model shows 98% accuracy on training data and 68% on validation. Is it overfit or underfit? What are 3 things you'd try next?

6

Model choice: For each scenario, pick linear, random forest, or gradient boosting and justify: (a) loan approvals with strict regulatory requirements, (b) fraud detection with complex patterns, (c) monthly expense forecasting.

🏆

By the end of this module, you'll be able to: explain random forests and gradient boosting, measure feature importance with two methods, tune hyperparameters with cross‑validation, spot overfitting, and choose between linear and tree models for real financial problems.

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→