Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 4 of 10
Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
A decision tree plays 20 questions with your data. Compute gini by hand, read a depth-2 rain tree that scores 0.82, watch an unlimited tree hit 1.000 on train and 0.770 on test, and see humidity take 65% of the importance.
What you will learn
- Compute gini by hand and explain why the tree picks the question with the lowest gini
- Fit and read a depth-2 DecisionTreeClassifier on the rain data
- Watch train and test accuracy split apart as max_depth grows
- Read feature_importances_ and build a regression tree that splits by MSE
Before you start
- Train-Test Split and Data Leakage
- Polynomial Regression, Overfitting and Underfitting
Remember the game of 20 questions? I think of something, and you may only ask yes or no questions. A good first question splits everything into two big halves: is it an animal? Each answer opens the next question: can it fly? Is it food? After a few questions, the answer is clear.
A decision tree plays exactly this game with your data. It asks the question that splits the rows most cleanly, then asks a new question inside each answer, again and again.
Gini: how mixed is a group?
How does a tree know which question is good? It measures how mixed each group is. The score is gini:
gini = 1 - (rainy share)² - (dry share)²
def gini(rain, dry):
n = rain + dry
return 1 - (rain / n) ** 2 - (dry / n) ** 2
print("ten mixed days:", gini(5, 5))
print("humid group: ", round(gini(4, 1), 2))
print("dry-air group: ", round(gini(1, 4), 2))
ten mixed days: 0.5
humid group: 0.32
dry-air group: 0.32
Gini 0 means only one class is left. The lower the gini after a split, the better the question. The tree tries every column and every threshold, and keeps the one with the lowest (weighted) gini. Entropy, another option in scikit-learn, is just another score for the same idea.
The rain data, split first
Will it rain tomorrow? We use 10,000 days from Rain in Australia, keep the number columns and drop RISK_MM, because it holds tomorrow's rain (see Train-Test Split and Data Leakage).
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, plot_tree
df = pd.read_csv("weatherAUS.csv")
df = df.dropna(subset=["RainTomorrow"])
df = df.sample(10_000, random_state=42)
X = df.select_dtypes("number")
X = X.drop(columns=["RISK_MM"])
y = df["RainTomorrow"]
print(X.shape, y.value_counts().to_dict())
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(10000, 16) {'No': 7770, 'Yes': 2230}
(8000, 16) (2000, 16)
16 columns, 7,770 dry and 2,230 rainy days. 8,000 to learn from, 2,000 to test.
A tree with max_depth=2
max_depth=2 allows just two levels of questions. Notice what's missing: no scaling and no imputing. A tree only asks "above or below a number", so the scale of a column doesn't matter, and scikit-learn's trees accept missing values.
tree = DecisionTreeClassifier(
max_depth=2, random_state=42)
tree.fit(X_train, y_train)
print(round(tree.score(X_test, y_test), 3))
0.82
plt.figure(figsize=(11, 4.4))
plot_tree(tree, filled=True, fontsize=12,
feature_names=list(X.columns),
class_names=list(tree.classes_))
plt.show()
![plot_tree of the depth-2 rain tree. Root: Humidity3pm <= 68.5, gini 0.347, 8000 samples, value [6216, 1784], class No. True branch: Sunshine <= 7.55 with two No leaves. False branch: Humidity3pm <= 83.5 with a No leaf of 1037 samples and a Yes leaf of 559 samples, value [118, 441].](/media/articles/decision-trees-gini-and-max-depth/depth-2-rain-tree.png)
Read the tree
Each box shows the question, its gini, how many training days reach it, and the value counts as [No, Yes].
- Root: Humidity3pm <= 68.5? All 8,000 days start here, 1,784 of them rainy (gini 0.347).
- If yes (left): Sunshine <= 7.55? Both of its leaves say No.
- If no (right): Humidity3pm <= 83.5? Below that, still No (577 dry vs 460 rainy). Above 83.5, the only Yes leaf: 118 dry days against 441 rainy.
So this tree predicts rain only after a very humid afternoon. Let's check one test day it calls Yes:
day = X_test[tree.predict(X_test) == "Yes"].head(1)
print(day["Humidity3pm"].iloc[0], tree.predict(day))
92.0 ['Yes']
92 is above 68.5, then above 83.5. It lands in the rain leaf.
Grow it deeper: max_depth and overfitting
What if we let the tree ask more questions? Try several depths, and print train and test accuracy:
scores = []
print("depth train test")
for depth in [1, 2, 4, 8, 16, None]:
tree = DecisionTreeClassifier(
max_depth=depth, random_state=42)
tree.fit(X_train, y_train)
tr = tree.score(X_train, y_train)
te = tree.score(X_test, y_test)
scores.append((tr, te))
print(f"{depth!s:>5} {tr:>7.3f} {te:>6.3f}")
depth train test
1 0.803 0.798
2 0.817 0.820
4 0.837 0.822
8 0.887 0.820
16 0.979 0.781
None 1.000 0.770
names = ["1", "2", "4", "8", "16", "None"]
train_s, test_s = zip(*scores)
plt.figure(figsize=(7, 3.2))
plt.plot(names, train_s, marker="o", label="train")
plt.plot(names, test_s, marker="o", label="test")
plt.xlabel("max_depth"); plt.ylabel("accuracy")
plt.legend(); plt.show()

With no limit (None), the tree keeps splitting until every training day is right: train 1.000. But test drops to 0.770. It learned the practice answers by heart and fails the new paper. That's overfitting: a big gap between train and test. The test line peaks around depth 4 (0.822). In practice you pick max_depth with cross-validation, not by looking at the test set.
Which questions mattered?
A fitted tree tells you how much each column lowered the gini, as feature_importances_. They add up to 1.
tree = DecisionTreeClassifier(
max_depth=4, random_state=42)
tree.fit(X_train, y_train)
imp = pd.Series(
tree.feature_importances_, index=X.columns)
imp = imp.sort_values(ascending=False)
print(imp.head(4).round(2))
Humidity3pm 0.65
Rainfall 0.09
Sunshine 0.09
Pressure3pm 0.08
dtype: float64
This depth-4 tree gets 65% of its gini drop from afternoon humidity alone.
A regression tree: average in each leaf
Trees predict numbers too. Six kids, from Emma (2 years, 12 kg) to Jack (9 years, 30 kg). For numbers, the tree picks the question with the lowest MSE (see Regression Metrics) instead of gini, and each leaf predicts the average of its rows.
kids = pd.read_csv("kids_age_weight.csv")
reg = DecisionTreeRegressor(
max_depth=1, random_state=42)
reg.fit(kids[["age"]], kids["weight"])
print("question: age <=", reg.tree_.threshold[0])
new = pd.DataFrame({"age": [3, 8]})
print(reg.predict(new).round(2))
question: age <= 5.5
[15. 25.67]
One question: age <= 5.5. The younger kids weigh 12, 15 and 18, average 15. The older ones weigh 22, 25 and 30, average 25.67. So a 3-year-old gets 15 and an 8-year-old gets 25.67.
Common mistakes
- No depth limit. Train 1.000, test 0.770. Always limit the tree (
max_depth,min_samples_leaf) and tune it with cross-validation. - Scaling for a tree. It does no harm, but a tree doesn't need it.
- Reading importances as cause. They show what this tree used, not what causes rain. Correlated columns can share or steal importance.
- Trusting one tree too much. A small change in the rows can change the whole tree. The fix is many trees: Bagging and Random Forest.
Quick recap
| Idea | What it means | In this example |
|---|---|---|
| Gini | How mixed a group is; 0 is pure | 5/5 is 0.5, 4/1 is 0.32 |
| Best question | Lowest gini (classes) or MSE (numbers) | Humidity3pm <= 68.5 |
| max_depth | How many levels of questions | Depth 2 test 0.82 |
| Overfitting | Train up, test down | No limit: 1.000 train, 0.770 test |
| Importances | Share of the gini drop per column | Humidity3pm 0.65 |
| Regression tree | Each leaf predicts its average | age <= 5.5: 15 and 25.67 |
Try it yourself
Use cross_val_score on the train rows to pick max_depth from 1 to 10. Do you also land on a small tree?
The notebook and the datasets are in the StudyEasy AI Community, free to join. Before this: Support Vector Machines.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
Next →Bagging and Random Forest: Many Shaky Trees, One Steady Answer
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.