cat /en/build-a-tree/
MDN-119:22
SERIES Inside Ordito · Chapter 7

Build a tree

· Artificial Intelligence · 5 min read

A decision tree is a series of questions: does the order contain two sizes of the same garment? Is the total above 160 euros? With each answer you go down a branch, and in the end a leaf says how many orders like that one were returned. It reads like a set of rules, and that is why it appeals to people who have to explain decisions.

How a question is chosen

A group of orders is the more “impure” the more it mixes returned and non-returned orders. The Gini impurity of a group with a share p of returns is 2p(1 − p): zero if the group is all of one class, 0.5 if it is half and half. A split divides the group in two, and it is measured by the average of the two impurities, weighted by the number of orders.

The algorithm tries all the variables and all the possible thresholds, and keeps the split with the lowest impurity. Then it repeats in each of the two branches.

In the lab you choose the question of each node yourself, on 4,000 orders from 2023 and 2024. On the right, the Gini curve for each threshold: the white dot is the best split.

DEMO Build a tree · about this demo · full screen ↗

Three experiments

The first question. Try by hand: the total, the number of items, the first order. Then press “Taglio migliore” (best split). At the root the double size wins: those who order the same garment in two sizes almost always return one of them, three orders out of four.

The Gini curve. With the total, the curve is irregular, with many local minima. The algorithm knows nothing about stores or sizes: it looks at the curve and keeps the lowest point.

Different questions in the branches. Press “Albero di Gini completo” (complete Gini tree): in the two branches the best question changes. This is the strength of trees, because interactions come by themselves: each branch asks its question only to its own orders.

The same experiment in Python

A two-level tree on all the orders of 2023 and 2024. With all the data, in the double-size branch the best question becomes the total, with a threshold of 161.65 euros.

import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text

URL = "https://raw.githubusercontent.com/mid079/machine-learning-teoria-pratica/main/dati/"
ordini = pd.read_parquet(URL + "ordini_online.parquet")
righe = pd.read_parquet(URL + "righe_scontrino.parquet", columns=["id_scontrino", "id_modello", "sconto_pct"])
righe = righe[righe["id_scontrino"].isin(ordini["id_scontrino"])].copy()
righe["ripetuto"] = righe.duplicated(["id_scontrino", "id_modello"])     # same model twice: two sizes
per_ordine = righe.groupby("id_scontrino").agg(due_taglie=("ripetuto", "any"), sconto_medio=("sconto_pct", "mean"))
ordini = ordini.join(per_ordine, on="id_scontrino")

variabili = ["due_taglie", "totale", "n_articoli", "primo_ordine", "sconto_medio"]
passato = ordini[ordini["data_ordine"].dt.year < 2025]
albero = DecisionTreeClassifier(max_depth=2, random_state=0).fit(passato[variabili], passato["reso"])
print(export_text(albero, feature_names=variabili, show_weights=True))

In the book

This lab accompanies chapter 7, “Decision trees”: Gini and entropy, the tree written from scratch, depth and overfitting, pruning with ccp_alpha, variable importance and regression trees, which cannot predict beyond the values already seen.

COVER COMING SOON
mltp · 2026

Machine Learning. Teoria, matematica e pratica degli algoritmi

Michele di Nuzzo · in Italian

Every algorithm in two steps: first derive it, with the mathematics it needs and an example worked by hand, then write it from scratch in NumPy. Only at the end use it with scikit-learn.

[the book’s page] [shop links coming soon]

The “Inside Ordito” series