svgdcr-histogram
Distance to closest record
Are synthetic rows suspiciously close to (copies of) real training rows?
How to read it
- Read one histogram as synthetic rows' distance to their nearest training row.
- Read the other as held-out real rows' distance to training.
- Synthetic should not be closer: closer suggests copying.
- Callout 1: Distances near zero would suggest copies.
- Callout 2: The median distances to compare.
Watch out
- Passing this check isn't a privacy guarantee: it tests only one kind of leak.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine or the host's scorecard); the chart computes nothing statistical.
- Both histograms share edges over the joint range; dashed lines are medians. Privacy rule of thumb: the synthetic→train distribution should not sit left of holdout→train (the 5th percentiles are in the scorecard), and exact copies (distance 0) should be absent.
# Distance to closest record — Codesplash Chart Lab (recipe "dcr-histogram")
# 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("dcr-histogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["pair"] = pd.Categorical(df["pair"].astype("string"), categories=["synthetic → train", "holdout → train"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
D = "Gower distance"
P = "pair"
pairs = levels_of(df[P])
edges = np.linspace(df[D].min(), df[D].max(), 31) # shared edges
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, p in enumerate(pairs):
v = df.loc[df[P].astype(str) == str(p), D].dropna()
ax.hist(v, bins=edges, weights=np.full(len(v), 1 / len(v)), histtype="stepfilled", alpha=0.28, color=PALETTE[i], edgecolor=PALETTE[i], linewidth=1.5, label=f"{p} · median {v.median():.3f}")
ax.axvline(v.median(), color=PALETTE[i], linestyle="--", linewidth=1)
ax.set_xlabel(D)
ax.set_ylabel("share of rows")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads dcr-histogram-demo.csv · app theme from the optional codesplash helper
# Distance to closest record — Codesplash Chart Lab (recipe "dcr-histogram")
# 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("dcr-histogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["pair"] = pd.Categorical(df["pair"].astype("string"), categories=["synthetic → train", "holdout → train"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
D = "Gower distance"
P = "pair"
fig = px.histogram(df, x=D, color=P, nbins=30, histnorm="probability", barmode="overlay", opacity=0.5, color_discrete_sequence=PALETTE, category_orders={P: levels_of(df[P])})
fig.update_layout(yaxis_title="share of rows", legend_title=None)
fig.show()Needs pandas, numpy, plotly · reads dcr-histogram-demo.csv · app theme from the optional codesplash helper
# Distance to closest record — Codesplash Chart Lab (recipe "dcr-histogram")
# 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("dcr-histogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["pair"]] <- factor(df[["pair"]], levels = c("synthetic → train", "holdout → train"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
d_col <- "Gower distance"
p_col <- "pair"
d <- data.frame(dist = df[[d_col]], pair = factor(as.character(df[[p_col]]), levels = levels_of(df[[p_col]])))
edges <- seq(min(d$dist, na.rm = TRUE), max(d$dist, na.rm = TRUE), length.out = 31)
med <- stats::aggregate(dist ~ pair, data = d, FUN = stats::median)
p <- ggplot(d, aes(dist, fill = pair, colour = pair)) +
geom_histogram(aes(y = after_stat(density * width)), breaks = edges, position = "identity", alpha = 0.28) +
geom_vline(data = med, aes(xintercept = dist, colour = pair), linetype = "dashed") +
scale_fill_manual(values = cs_cat) + scale_colour_manual(values = cs_cat) + labs(x = d_col, y = "share of rows", fill = NULL, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads dcr-histogram-demo.csv · app theme from the optional codesplashr helper