The margin
After two weeks in the store, can you already say whether a garment will hold its full price or end up in the sales? For the 752 garments of Ordito’s 2023 and 2024 seasons the answer lies almost entirely in one number: how many pieces it sold in the first fourteen days.
The widest road
If two clouds of points can be separated by a line, the possible lines are infinite. The Support Vector Machine chooses the one that passes farthest from both: it imagines a road around the line, wide enough to touch the first points of each class, and looks for the widest road. The width is 2/‖w‖.
In real data the clouds overlap, and some garments end up inside the road or on the wrong side. The parameter C says how much it costs: with a large C every violation is expensive, with a small C the SVM prefers a wide road. The points on the edge of the road or inside it are the support vectors: they are the ones that decide where the boundary passes.
In the lab, move C and watch the road widen and narrow. The circled garments are the support vectors.
Three experiments
The widest road. With C = 0.133, as in the chapter, the SVM finds w ≈ (1.94, −0.16): almost only the garment’s start counts. There are 299 support vectors, and on the garments of spring-summer 2025 the SVM is right in 91% of cases.
Small C. With C = 0.001 violations cost almost nothing. The road becomes extremely wide, contains 598 garments, and the model ends up always saying “regge” (holds): 75% on 2025, the same as the most frequent class.
Large C. With C = 100 the road narrows, the support vectors go down to 268, but accuracy stays at 91%. With an almost straight boundary there is not much to overfit.
The same experiment in Python
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
URL = "https://raw.githubusercontent.com/mid079/machine-learning-teoria-pratica/main/dati/"
articoli = pd.read_parquet(URL + "articoli.parquet")
negozi = pd.read_parquet(URL + "negozi.parquet")
scontrini = pd.read_parquet(URL + "scontrini.parquet", columns=["id_scontrino", "data_ora", "id_negozio"])
righe = pd.read_parquet(URL + "righe_scontrino.parquet", columns=["id_scontrino", "id_modello", "quantita", "sconto_pct"])
capi = articoli[articoli["collezione"].isin(["PE23", "AI23", "PE24", "AI24", "PE25"])].set_index("id_modello")
outlet = negozi.loc[negozi["tipo"] == "outlet", "id_negozio"]
v = righe.merge(scontrini, on="id_scontrino")
v = v[v["id_modello"].isin(capi.index) & ~v["id_negozio"].isin(outlet)]
v["giorno"] = (v["data_ora"] - v["id_modello"].map(v.groupby("id_modello")["data_ora"].min())).dt.days
capi["log_prime"] = np.log(v[v["giorno"] < 14].groupby("id_modello")["quantita"].sum()) # the first two weeks
pieno = v[v["sconto_pct"] == 0].groupby("id_modello")["quantita"].sum() / v.groupby("id_modello")["quantita"].sum()
capi["regge"] = (pieno >= 0.5).astype(int)
train, test = capi[capi["collezione"] != "PE25"], capi[capi["collezione"] == "PE25"]
scala = StandardScaler().fit(train[["log_prime", "prezzo_listino"]])
for C in [0.001, 0.133, 100]:
svm = SVC(kernel="linear", C=C).fit(scala.transform(train[["log_prime", "prezzo_listino"]]), train["regge"])
acc = svm.score(scala.transform(test[["log_prime", "prezzo_listino"]]), test["regge"])
print(f"C = {C:7}: {svm.n_support_.sum()} support vectors, accuracy on 2025 {acc:.3f}")
In the book
This lab accompanies chapter 9, “Support Vector Machines”: the margin and its formula, the soft margin, the hinge loss and the SVM written from scratch with the subgradient, the kernel trick and the RBF kernel, tried on churning customers, where the boundary really does bend.
The “Inside Ordito” series
- Chapter 1 The line of the five stores
- Chapter 2 A simulated store
- Chapter 3 Where the leak hides
- Chapter 4 The valley of the five stores
- Chapter 5 The threshold
- Chapter 6 Why was it returned?
- Chapter 7 Build a tree
- Chapter 8 Boosting step by step
- Chapter 9 The margin
- Workshop A Price is place
- Chapter 10 Shapley by hand
- Chapter 11 Rotate the cloud
- Chapter 12 Groups and dense areas
- Chapter 13 Isolating a point
- Chapter 14 Naive forecasts
- Workshop B A year in production
- Chapter 15 The ink stain
- Chapter 16 Backpropagation