svgsurrogate-tree
Surrogate decision tree
Can a small, readable tree imitate what this complicated model does?
How to read it
- Read from the top: each split sends rows left or right.
- Read each leaf as the model's average prediction for the rows that reach it.
- 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
# Surrogate decision tree — Codesplash Chart Lab (recipe "surrogate-tree")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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)
rows = d.set_index(NODE)
fig = go.Figure()
for parent, children in kids.items():
for k in children:
fig.add_scatter(x=[pos[parent], pos[k]], y=[-depth[parent], -depth[k]], mode="lines", line=dict(color="grey", width=1), showlegend=False)
text = [f"{rows.loc[n, VALUE]:.3g}<br>n = {rows.loc[n, N]:.0f}" if n not in kids else f"{rows.loc[n, LABEL]}<br>n = {rows.loc[n, N]:.0f}" for n in order]
fig.add_scatter(x=[pos[n] for n in order], y=[-depth[n] for n in order], mode="text", text=text, showlegend=False)
fig.update_layout(xaxis_visible=False, yaxis_visible=False)
fig.show()Needs pandas, numpy, plotly · reads surrogate-tree-demo.csv · app theme from the optional codesplash helper
# Surrogate decision tree — Codesplash Chart Lab (recipe "surrogate-tree")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("surrogate-tree-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["split"]] <- factor(df[["split"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
node_col <- "node"
parent_col <- "parent"
label_col <- "split"
n_col <- "rows"
value_col <- "P(diabetic)"
d <- df[order(df[[node_col]]), ]
id <- as.character(d[[node_col]]); parent <- as.character(d[[parent_col]])
pos <- setNames(numeric(length(id)), id); depth <- pos; nxt <- 0
place <- function(n, level) { # leaves evenly spaced; a split centred over its children
depth[[n]] <<- level
children <- id[parent == n]
if (!length(children)) { pos[[n]] <<- nxt; nxt <<- nxt + 1; return(pos[[n]]) }
xs <- vapply(children, place, numeric(1), level + 1)
pos[[n]] <<- (xs[1] + xs[length(xs)]) / 2
pos[[n]]
}
invisible(place(id[1], 0))
nodes <- data.frame(x = pos[id], y = -depth[id], leaf = !(id %in% parent))
nodes$text <- ifelse(nodes$leaf, sprintf("%.3g\nn = %.0f", d[[value_col]], d[[n_col]]), sprintf("%s\nn = %.0f", d[[label_col]], d[[n_col]]))
keep <- as.numeric(parent) >= 0
edges <- data.frame(x = pos[parent[keep]], y = -depth[parent[keep]], xend = pos[id[keep]], yend = -depth[id[keep]])
p <- ggplot() + geom_segment(data = edges, aes(x = x, y = y, xend = xend, yend = yend), colour = "grey60") +
geom_label(data = nodes, aes(x = x, y = y, label = text), size = 2.8) +
theme_void()
print(p)Needs ggplot2 · reads surrogate-tree-demo.csv · app theme from the optional codesplashr helper