Skip to content
svgsurrogate-tree

Surrogate decision tree

Can a small, readable tree imitate what this complicated model does?

Demo data · seed 20261101 · 9 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read from the top: each split sends rows left or right.
  2. Read each leaf as the model's average prediction for the rows that reach it.
  3. Check how well the tree imitates the model before trusting its story.

Watch out

  • The tree explains an imitation of the model, not the model itself or the world. A low fidelity score makes it misleading.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the explanation the Python or R engine computed; the chart computes nothing statistical.
  • Nodes arrive depth-first with the left (yes) child first. Leaves are evenly spaced and each split is centred over its children.
  • The tree explains the model, not the world: read it together with its fidelity, the R² between the tree's and the model's predictions.
# Surrogate decision tree — Codesplash Chart Lab (recipe "surrogate-tree")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("surrogate-tree-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
NODE = "node"
PARENT = "parent"
LABEL = "split"
N = "rows"
VALUE = "P(diabetic)"
d = df.sort_values(NODE)
kids, order = {}, list(d[NODE])
for node, parent in zip(d[NODE], d[PARENT]):
    if parent >= 0:
        kids.setdefault(parent, []).append(node)
pos, depth, leaves = {}, {}, [0]
def place(n, level):  # leaves evenly spaced; a split centred over its children
    depth[n] = level
    if n not in kids:
        pos[n] = leaves[0]; leaves[0] += 1
    else:
        xs = [place(k, level + 1) for k in kids[n]]
        pos[n] = (xs[0] + xs[-1]) / 2
    return pos[n]
place(order[0], 0)
fig, ax = plt.subplots(figsize=(9, 4.5))
rows = d.set_index(NODE)
for parent, children in kids.items():
    for i, k in enumerate(children):
        ax.plot([pos[parent], pos[k]], [-depth[parent], -depth[k]], color="grey", linewidth=0.8, zorder=1)
        ax.text((pos[parent] + pos[k]) / 2, -(depth[parent] + depth[k]) / 2, "yes" if i == 0 else "no", fontsize=7, color="grey", ha="center")
for n in order:
    leaf = n not in kids
    text = f"{rows.loc[n, VALUE]:.3g}\nn = {rows.loc[n, N]:.0f}" if leaf else f"{rows.loc[n, LABEL]}\nn = {rows.loc[n, N]:.0f}"
    ax.text(pos[n], -depth[n], text, ha="center", va="center", fontsize=8, bbox=dict(boxstyle="round", facecolor="white", edgecolor="grey"), zorder=2)
ax.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads surrogate-tree-demo.csv · app theme from the optional codesplash helper