0Pricing
Python Academy · Lesson

Tree-Based Models: Decision Trees and Random Forests

Build and tune decision tree and ensemble forest models.

Tree-Based Models: Decision Trees and Random Forests is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Decision Tree Concepts

A decision tree splits data into subsets by asking a sequence of binary questions. Each internal node is a feature threshold; each leaf is a prediction.

from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X, y)
print("Depth:", model.get_depth())
print("Leaves:", model.get_n_leaves())

DecisionTreeClassifier

Key hyperparameters: max_depth, min_samples_split, min_samples_leaf. Deeper trees overfit; shallower trees underfit.

from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)

model = DecisionTreeClassifier(max_depth=5, min_samples_leaf=5)
model.fit(X_tr, y_tr)
print("Test acc:", model.score(X_te, y_te))

DecisionTreeRegressor

Decision trees also handle regression by predicting the mean target value in each leaf.

from sklearn.tree import DecisionTreeRegressor
from sklearn.datasets import make_regression
from sklearn.metrics import mean_squared_error

X, y = make_regression(noise=15, random_state=0)
model = DecisionTreeRegressor(max_depth=4).fit(X, y)
print("RMSE:", mean_squared_error(y, model.predict(X))**0.5)

Feature Importance

model.feature_importances_ gives the relative importance of each feature, based on impurity reduction.

from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
import numpy as np

X, y = load_iris(return_X_y=True)
feature_names = load_iris().feature_names
model = DecisionTreeClassifier().fit(X, y)
for name, imp in sorted(zip(feature_names, model.feature_importances_), key=lambda x: -x[1]):
    print(f"{name}: {imp:.3f}")

Random Forest Overview

A Random Forest trains many decorrelated decision trees on bootstrap samples and averages their predictions — reducing variance without increasing bias.

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)

model = RandomForestClassifier(n_estimators=100, random_state=0)
model.fit(X_tr, y_tr)
print("Test acc:", model.score(X_te, y_te))

RandomForestRegressor

Random forests work equally well for regression.

from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
from sklearn.metrics import r2_score

X, y = make_regression(noise=10, random_state=0)
model = RandomForestRegressor(n_estimators=100, random_state=0).fit(X, y)
print("R²:", r2_score(y, model.predict(X)))

Out-of-Bag Score

Set oob_score=True to get a free validation score using samples not in each tree's bootstrap (no separate test set needed).

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification

X, y = make_classification(random_state=0)
model = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=0).fit(X, y)
print("OOB score:", model.oob_score_)

Gradient Boosting

Gradient boosting (GBM) trains trees sequentially, each correcting the errors of the previous. Often more accurate than Random Forests but slower to train.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = GradientBoostingClassifier(n_estimators=100).fit(X_tr, y_tr)
print("Test acc:", model.score(X_te, y_te))

XGBoost / LightGBM

XGBoost and LightGBM are optimised gradient boosting libraries — faster, more scalable, and often more accurate than sklearn's GBM.

# pip install xgboost lightgbm
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)

xgb = XGBClassifier(n_estimators=100, eval_metric="logloss").fit(X_tr, y_tr)
print("XGB acc:", xgb.score(X_te, y_te))

Tuning n_estimators

More trees in a Random Forest reduce variance (up to a point) without overfitting. Use validation curve to find the optimal count.

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_classification
import numpy as np

X, y = make_classification(random_state=0)
for n in [10, 50, 100, 200]:
    scores = cross_val_score(RandomForestClassifier(n_estimators=n, random_state=0), X, y, cv=5)
    print(f"n={n}: {scores.mean():.3f}")

Visualising a Decision Tree

Use sklearn.tree.plot_tree or export_text to inspect what the tree learned.

from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)
model = DecisionTreeClassifier(max_depth=2).fit(X, y)
print(export_text(model, feature_names=load_iris().feature_names.tolist()))

Quick Check

How does a Random Forest reduce overfitting compared to a single decision tree?

Recap

Decision trees split data by feature thresholds and predict with leaf values. Tune max_depth to control overfitting. Random Forests average many trees for lower variance. Gradient boosting trains trees sequentially for high accuracy. For production, prefer XGBoost or LightGBM.

Frequently asked questions

Is the “Tree-Based Models: Decision Trees and Random Forests” lesson free?

Yes — the full text of “Tree-Based Models: Decision Trees and Random Forests” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Tree-Based Models: Decision Trees and Random Forests”?

Build and tune decision tree and ensemble forest models. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Tree-Based Models: Decision Trees and Random Forests” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The scikit-learn API: fit, transform, predict
  2. Linear Models: Regression and Classification
  3. Tree-Based Models: Decision Trees and Random Forests
  4. Model Evaluation and Cross-Validation
← Back to Python Academy