svgh-statistic
Friedman's H interactions
Which features does the model combine, rather than use one at a time?
How to read it
- Read each cell as how much of a pair's joint effect is interaction: 0 means the pair adds up.
- Read the outlined diagonal as each feature against all the others.
- Look at the partial dependence of any high pair to see what the interaction does.
Watch out
- H is noisy with few rows and can be large for pairs whose total effect is tiny, so check their importance too.
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.
- H is the square root of H², the share of the joint partial dependence's variance that the separate effects do not explain.
- The colour scale runs from 0 to the largest H in the chart; a large H can still describe a small effect, so read it next to the partial dependence.
# Friedman's H interactions — Codesplash Chart Lab (recipe "h-statistic")
# 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("h-statistic-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree"])
df["with"] = pd.Categorical(df["with"].astype("string"), categories=["glucose", "BMI", "age", "pedigree"])
_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")
A = "feature"
B = "with"
H = "H"
feats = list(dict.fromkeys(list(df[A].astype(str)) + list(df[B].astype(str))))
m = pd.DataFrame(np.nan, index=feats, columns=feats)
for a, b, h in zip(df[A].astype(str), df[B].astype(str), df[H]):
m.loc[a, b] = h; m.loc[b, a] = h # the diagonal: each feature against all the others
fig, ax = plt.subplots(figsize=(5.5, 5))
im = ax.imshow(m.to_numpy(dtype=float), cmap="Blues", vmin=0)
ax.set_xticks(range(len(feats)), feats, rotation=45, ha="right")
ax.set_yticks(range(len(feats)), feats)
for i in range(len(feats)):
for j in range(len(feats)):
if pd.notna(m.iat[i, j]):
ax.text(j, i, f"{m.iat[i, j]:.2f}", ha="center", va="center", fontsize=8)
fig.colorbar(im, label="Friedman's H")
plt.show()Needs pandas, numpy, matplotlib · reads h-statistic-demo.csv · app theme from the optional codesplash helper
# Friedman's H interactions — Codesplash Chart Lab (recipe "h-statistic")
# 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("h-statistic-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree"])
df["with"] = pd.Categorical(df["with"].astype("string"), categories=["glucose", "BMI", "age", "pedigree"])
_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")
A = "feature"
B = "with"
H = "H"
feats = list(dict.fromkeys(list(df[A].astype(str)) + list(df[B].astype(str))))
m = pd.DataFrame(np.nan, index=feats, columns=feats)
for a, b, h in zip(df[A].astype(str), df[B].astype(str), df[H]):
m.loc[a, b] = h; m.loc[b, a] = h # the diagonal: each feature against all the others
fig = go.Figure(go.Heatmap(z=m.to_numpy(dtype=float), x=feats, y=feats, colorscale="Blues", zmin=0, colorbar=dict(title="Friedman's H"), texttemplate="%{z:.2f}"))
fig.update_yaxes(autorange="reversed")
fig.show()Needs pandas, numpy, plotly · reads h-statistic-demo.csv · app theme from the optional codesplash helper
# Friedman's H interactions — Codesplash Chart Lab (recipe "h-statistic")
# 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("h-statistic-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["feature"]] <- factor(df[["feature"]], levels = c("glucose", "BMI", "age", "pedigree"))
df[["with"]] <- factor(df[["with"]], levels = c("glucose", "BMI", "age", "pedigree"))
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
a_col <- "feature"
b_col <- "with"
h_col <- "H"
a <- as.character(df[[a_col]]); b <- as.character(df[[b_col]])
feats <- unique(c(a, b))
cells <- rbind(data.frame(x = b, y = a, h = df[[h_col]]), data.frame(x = a, y = b, h = df[[h_col]]))
cells <- cells[!duplicated(cells[c("x", "y")]), ] # the diagonal: each feature against all the others
cells$x <- factor(cells$x, levels = feats); cells$y <- factor(cells$y, levels = rev(feats))
p <- ggplot(cells, aes(x, y, fill = h)) + geom_tile(colour = "white") + geom_text(aes(label = sprintf("%.2f", h)), size = 3) +
scale_fill_gradient(low = "#eef3fb", high = "#2f6db5", limits = c(0, NA), name = "Friedman's H") +
labs(x = NULL, y = NULL) + theme_cs
print(p)Needs ggplot2 · reads h-statistic-demo.csv · app theme from the optional codesplashr helper