Python Tutorial
Decision Tree
A flowchart-like model that splits data on feature thresholds to make transparent, rule-based predictions.
How a Decision Tree Works
A decision tree asks a sequence of yes/no questions about the features. Each internal node tests one feature against a threshold; each leaf holds a prediction. The algorithm greedily chooses the split that best separates the classes, measured by Gini impurity or entropy (information gain).
Trees handle numeric and categorical data, need no feature scaling, and are easy to interpret — you can read the exact rules that led to a prediction.
Building a Classifier
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
data = {
"Age": [36, 42, 23, 52, 43, 44, 66, 35, 52, 35],
"Experience":[10, 12, 4, 4, 21, 14, 3, 14, 13, 5],
"Rank": [9, 4, 6, 4, 8, 5, 7, 9, 7, 9],
"Go": [1, 0, 0, 0, 1, 0, 1, 1, 1, 1],
}
df = pd.DataFrame(data)
X = df[["Age", "Experience", "Rank"]]
y = df["Go"]
tree = DecisionTreeClassifier(criterion="gini", random_state=0)
tree.fit(X, y)
print(tree.predict([[40, 10, 7]])) # 1 = go, 0 = don't goReading the Rules
Export the learned rules as text or a diagram to explain the model.
from sklearn.tree import export_text, plot_tree
import matplotlib.pyplot as plt
print(export_text(tree, feature_names=list(X.columns)))
plt.figure(figsize=(10, 6))
plot_tree(tree, feature_names=X.columns, class_names=["No", "Go"], filled=True)
plt.show()Controlling Overfitting
An unrestricted tree grows until every leaf is pure, memorizing noise. Prune it with hyperparameters:
| Parameter | Effect |
|---|---|
max_depth | Limit how many questions deep the tree can go |
min_samples_leaf | Require a minimum number of samples in each leaf |
min_samples_split | Only split nodes with enough samples |
ccp_alpha | Cost-complexity pruning strength |
tree = DecisionTreeClassifier(max_depth=3, min_samples_leaf=2, random_state=0)
tree.fit(X, y)Feature Importance
importances = pd.Series(tree.feature_importances_, index=X.columns)
print(importances.sort_values(ascending=False))Higher values mean the feature contributed more to reducing impurity across the tree.
Advanced: From Trees to Forests
A single tree is high-variance — small data changes reshape it. Averaging many trees trained on bootstrapped samples (a Random Forest) dramatically improves accuracy and stability. Gradient boosting builds trees sequentially to correct prior errors.
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=200, random_state=0)
forest.fit(X, y)
print(forest.predict([[40, 10, 7]]))Best Practices
- Limit depth or leaf size to prevent overfitting on small datasets.
- Use
DecisionTreeRegressorfor continuous targets. - Prefer ensembles (Random Forest, Gradient Boosting) when accuracy matters more than a single readable rule set.
- Evaluate on a held-out test set, not the training data.
Try It Yourself
Exercise 1: Train a depth-2 decision tree on the iris dataset and print its test accuracy.
Show solution
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, random_state=0)
tree = DecisionTreeClassifier(max_depth=2).fit(Xtr, ytr)
print(round(tree.score(Xte, yte), 3))Exercise 2: Which hyperparameter most directly limits overfitting in a tree?
Show solution
max_depth (also min_samples_leaf) — shallower trees can't memorize noise.
📘 Real-World Deep Dive
Knowing <strong>ML Decision Tree (scikit-learn)</strong> well is what turns scikit-learn from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of ML Decision Tree that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
clf = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X, y)
print("train score:", round(clf.score(X, y), 3))Expected Output
(see source)Common mistakes
fitexpects numeric arrays;OneHotEncoder/LabelEncoderare easy to forget for categorical features.- Calling
predicton a model trained on unscaled data and then scaling inputs at inference time silently degrades accuracy. train_test_split(X, y)requires both arrays;train_test_split(X)for unsupervised learning slips past static checkers.- Treating ML Decision Tree as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Wrap preprocessing + estimator in a
Pipelinesofit/predictstay reproducible. - Use
joblib/picklefor serialising models, not the entire Python state. - For > 100 k rows, switch to
HistGradientBoostingClassifierorcuML. - When working with scikit-learn, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.