Skip to content
svgembedding-map

Category embedding map

Which levels of a categorical variable does the model treat as alike?

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

How to read it

  1. Read each dot as one level of a categorical feature, placed by the vector the network learned for it.
  2. Levels close together act alike on the target; a level far from the rest gets treated differently.
  3. Compare levels within one colour (one feature): distances between features' levels are not comparable.
  1. Callout 1: Two levels the model treats alike: close together.
  2. Callout 2: A level set apart from the rest.
  3. Callout 3: The dashed zero lines: the centre of each feature's levels.

Watch out

  • The axes have no meaning: any rotation of an embedding fits equally well, so read distances and neighbours only.
  • A small dot (a rare level) keeps a vector near its random start; its position says little.
  • Two principal components show only part of the distances when the vectors have more dimensions; check the nearest-level table.

Defaults

Label levels
On
Names next to the dots; labels that would overlap are left out (hover shows every level).
Equal axis units
On
One unit has the same length on both axes, so distances on the map are comparable in every direction.

Pinned in the code

  • Draws the coordinates the Python or R engine computed; the chart computes nothing statistical.
  • Coordinates are each feature's level vectors projected on their first two principal components (centred; each component's sign fixed so its largest loading is positive). Two components show only part of the distances when vectors have more dimensions.
  • Read distances and neighbours, not axes: any rotation of an embedding fits the data equally well.
  • Dot area grows with the level's row count (√ scaling, 3–9 px); rare levels keep vectors near their random start, so their positions mean little.
# Category embedding map — Codesplash Chart Lab (recipe "embedding-map")
# controls: labels=true, equal=true
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("embedding-map-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=["weekday", "store type"])

_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")
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)))


def dot_px(sizes):
    """Dot radius as in the app: 3 + 6·√(rows / max rows) px, 4 px without rows."""
    s = np.asarray(sizes, dtype=float)
    top = np.nanmax(s) if np.isfinite(s).any() and np.nanmax(s) > 0 else 0
    return np.where(np.isfinite(s) & (s > 0) & (top > 0), 3 + 6 * np.sqrt(np.clip(s, 0, None) / (top or 1)), 4.0)
X = "PC 1"
Y = "PC 2"
LABEL = "level"
G = "feature"
SIZE = "rows"
LABELS, EQUAL = True, True
d = df.dropna(subset=[X, Y]).reset_index(drop=True)
groups = levels_of(d[G]) if G else [None]
r = dot_px(d[SIZE] if SIZE else np.full(len(d), np.nan))
fig, ax = plt.subplots(figsize=(7, 6))
ax.axhline(0, color=REF, alpha=0.35, linestyle="--", linewidth=0.8)
ax.axvline(0, color=REF, alpha=0.35, linestyle="--", linewidth=0.8)
for i, k in enumerate(groups):
    m = (d[G].astype(str) == str(k)).to_numpy() if G else np.ones(len(d), bool)
    ax.scatter(d.loc[m, X], d.loc[m, Y], s=(r[m] * 1.4) ** 2, color=PALETTE[i % len(PALETTE)], alpha=0.72, edgecolors="white", linewidths=0.8, label=k)
if LABELS and LABEL:
    for _, row in d.iterrows():  # every level is labelled; the app skips labels that would overlap
        ax.annotate(str(row[LABEL]), (row[X], row[Y]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=8)
if EQUAL:
    ax.set_aspect("equal", adjustable="datalim")  # equal units: distances read the same both ways
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
    ax.legend(title=G, fontsize=8)
ax.set_title("Learned category embeddings: close levels act alike on the target")
plt.show()

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

  • Every level is labelled here; the app leaves out labels that would overlap (hover shows them all).