|
Última actualización: 2026-12-02
DAY 009 OF 1600 · 2026-09-19 Day 009 — Teaching a tree to choose its own questionsA student's private learning log · one concept at a time. Date: 2026-09-19 · Day: 9 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #9 — Decision trees: how a model picks the right question to askThe last three days were about fitting (gradient descent, k-means) and checking (overfitting). Today is about a model that does neither the way I expected: a decision tree . It does not compute a line or a centroid. It just asks questions — weather? wind? — and splits the data one question at a time. What I did not understand until today is *how it decides which question to ask first*. That choice is not random, and it is not the programmer's; the model makes it itself. The tool is impurity , measured with the Gini index : Gini = 1 - Σ p_k² where p_k is the fraction of the node's rows belonging to class k . A node that is all one class has Gini 0 (pure). A 50/50 node has Gini 0.5 (as mixed as it gets for two classes). The tree tries every possible split and keeps the one that lowers impurity the most — the largest gain . That is the entire learning step, repeated down the tree. What I tried today: a 10-row toy dataset ( weather , wind → play? ), computing the Gini of the root, scoring both candidate splits, and growing a one-level tree (a stump ) from the winner. Pure stdlib — Counter and eval -free arithmetic — so I can see every number. #!/usr/bin/env python3 # decision_tree.py — learn the best split of a decision tree by Gini impurity. # MA01 (Machine Learning), decision-trees block. Pure stdlib, no libraries. from collections import Counter # 10 rows: weather, wind -> play? (small toy dataset, features are categorical) DATA = [ ("sunny", "weak", "yes"), ("sunny", "strong", "no"), ("rainy", "weak", "yes"), ("rainy", "strong", "no"), ("sunny", "weak", "yes"), ("rainy", "weak", "yes"), ("sunny", "strong", "yes"), ("rainy", "strong", "no"), ("sunny", "weak", "no"), ("rainy", "weak", "yes"), ] FEATURES = ["weather", "wind"] def gini(labels): """Gini impurity: 0 = perfectly pure, higher = more mixed.""" n = len(labels) if n == 0: return 0.0 counts = Counter(labels) return 1.0 - sum((c / n) ** 2 for c in counts.values()) def split_score(rows, index): """Weighted Gini of the two sides produced by splitting on feature `index`.""" groups = {} for r in rows: groups.setdefault(r[index], []).append(r[-1]) total = len(rows) score = 0.0 for labels in groups.values(): score += (len(labels) / total) * gini(labels) return score, groups def best_split(rows): base = gini([r[-1] for r in rows]) best = None for i, name in enumerate(FEATURES): score, groups = split_score(rows, i) gain = base - score sides = {k: dict(Counter(v)) for k, v in groups.items()} print(f" split on {name:<8} weighted Gini = {score:.4f} gain = {gain:.4f} {sides}") if best is None or score < best[2]: best = (i, name, score, gain) return best print("Root Gini impurity:", round(gini([r[-1] for r in DATA]), 4)) print("Candidate splits:") best = best_split(DATA) print(f"\nBest split -> {best[1]} (Gini {best[2]:.4f}, gain {best[3]:.4f})") # Grow a depth-1 stump from the winning feature and grade it on the same 10 rows. idx = best[0] groups = {} for r in DATA: groups.setdefault(r[idx], []).append(r[-1]) rules = {k: Counter(v).most_common(1)[0][0] for k, v in groups.items()} print("Stump rules:", rules) correct = sum(1 for r in DATA if rules[r[idx]] == r[-1]) print(f"Stump accuracy on the 10 training rows: {correct}/10 = {correct/10:.2f}") Real output ( python3 decision_tree.py , Python 3.11.15): Root Gini impurity: 0.48 Candidate splits: split on weather weighted Gini = 0.4800 gain = 0.0000 {'sunny': {'yes': 3, 'no': 2}, 'rainy': {'yes': 3, 'no': 2}} split on wind weighted Gini = 0.3167 gain = 0.1633 {'weak': {'yes': 5, 'no': 1}, 'strong': {'no': 3, 'yes': 1}} Best split -> wind (Gini 0.3167, gain 0.1633) Stump rules: {'weak': 'yes', 'strong': 'no'} Stump accuracy on the 10 training rows: 8/10 = 0.80 What I understood from it: the tree did not get told to look at wind . It measured both questions and the numbers made the decision for it. Splitting on weather changed nothing — Gini stayed at 0.4800 because the heads and tails of each side were the exact same 3-yes/2-no mix, a gain of zero : a question that tells you nothing. Splitting on wind dropped the weighted Gini to 0.3167, a gain of 0.1633, so the tree asked about wind first. That is the whole learning step: ask the question that removes the most uncertainty. And the honest ending — on its own 10 training rows the stump is only 8/10, because one windy row is a "yes" hiding in a "strong" wind. The last two days taught me to distrust a model that looks perfect on the data it trained on; day 9 taught me a tree can choose its own questions , but it still can't choose a question its data doesn't support. --- Security #9 — Server-Side Template Injection (SSTI, CWE-1336)What I learned about this topic — contained, sandbox only, no live targets: A template engine takes text with placeholders — Hello {user} — and fills them in. That is normal and fine. The bug is in how the placeholder gets resolved. The safe way is a lookup : the engine sees {user} , looks it up in a dictionary, prints the value. The dangerous way is evaluation : the engine sees {user} and runs it as if it were code. The moment a placeholder is executed instead of looked up , and the user controls that placeholder, you have CWE-1336, server-side template injection — and template injection that reaches eval is code execution. It is the same family as the injection classes I studied earlier (command injection, SQLi), with the same root cause: **user input is being interpreted as instructions instead of treated as data.** The subtlety here is that the input doesn't look like code — {user} looks like a harmless label — so it slips past everyone who assumes "it's just a template". I reproduced it in my own sandbox (/tmp) with two hand-written toy renderers on the same attacker-supplied template: one that evaluates placeholders, one that only looks them up. The payload is benign — it computes a value and proves the code path is reachable — no damage, no network, no target. The pattern I studied: # VULNERABLE: the value inside { } is passed to eval() def render_vulnerable(template, ctx): def repl(m): return str(eval(m.group(1), {"__builtins__": __builtins__}, dict(ctx))) return re.sub(r"\{([^{}]+)\}", repl, template) # "{user}" -> "alice" (normal use) # "{2 + 3}" -> 5 (already suspicious) # "{__import__(...)}" -> arbitrary code (game over) What I understood about preventing it: # SAFE: placeholders are dictionary keys, never code def render_safe(template, ctx): def repl(m): name = m.group(1).strip() return str(ctx[name]) if name in ctx else "{" + name + "}" return re.sub(r"\{([^{}]+)\}", repl, template) # anything not in ctx is printed back verbatim — nothing is ever executed Sandbox check (local only, /tmp, benign payload, no network): $ python3 ssti.py --- normal use --- Hello alice, your role is student. Sum: 5 Hello alice, your role is student. Sum: {2 + 3} --- attacker template (sandbox payload) --- vulnerable engine executed it -> /x42 safe engine on the same payload -> {__import__('os').getcwd()[:1] + 'x' + str(6*7)} What I understood: look at the two engines on the exact same input. The safe one printed the attacker's template back, untouched, because __import__(...) is not a key in the context — it was never code, only text. The vulnerable one ran it : the {2 + 3} that produced 5 in the first test is the warning sign I would have dismissed as a feature. The lesson is the same one from every injection class: **the fix is not to sanitise the syntax, it is to refuse to interpret input as instructions at all.** A safe template does lookups; the day it starts evaluating, every field a user can fill becomes a remote code execution bug. --- Day 9 notesConcept #9: decision-tree split by Gini — weather gave gain 0.0000, wind gave 0.1633 and won the root. ✔ Security #9: SSTI (CWE-1336) understood, sandbox only (/tmp), benign payload, no live targets. ✔ 1591 days left. One at a time. Written by my own daily machine, checked by me. · Day 009 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |