DRegression models · explain.entity_embeddings
Entity embeddings of categories
Which levels of a categorical variable act alike on the outcome, learned as vectors by a small neural network?
Learns one dense vector per category level while a small neural network predicts the target (entity embeddings): every categorical feature gets an embedding table whose vectors are concatenated with the standardized numbers and fed through hidden layers. Levels that affect the outcome alike end up close together, so the map, the nearest neighbors and the spread of each feature's levels show how the model groups the categories, and the vectors (saved as a table) can replace one-hot columns in other models. Torch in both engines, from the same initial weights on the shared random stream, with Adam written out.
A real result
Example “Titanic binary”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Learned 8 level vectors for 3 categorical features from 2201 rows (validation accuracy 0.784); Age's levels are spread out the most, so the model separates them most.
- Validation accuracy
- 0.7841
- Mean distance between Age levels
- 2.477
- Best epoch
- 120
Plots
View data
| Feature | Level | Rows | PC 1 | PC 2 |
|---|---|---|---|---|
| Class | 1st | 325 | −0.5984 | −0.7162 |
| Class | 2nd | 285 | 1.440 | 0.0837 |
| Class | 3rd | 706 | −0.7574 | 0.7367 |
| Class | Crew | 885 | −0.0847 | −0.1043 |
| Sex | Male | 1,731 | 0.8621 | 1.817e-18 |
| Sex | Female | 470 | −0.8621 | 5.369e-17 |
| Age | Child | 109 | 1.238 | 8.360e-18 |
| Age | Adult | 2,092 | −1.238 | −8.360e-18 |
View data
| Class | Class | Cosine similarity |
|---|---|---|
| 1st | 1st | 1 |
| 2nd | 1st | −0.7241 |
| 3rd | 1st | 0.0873 |
| Crew | 1st | 0.9739 |
| 1st | 2nd | −0.7241 |
| 2nd | 2nd | 1 |
| 3rd | 2nd | −0.7503 |
| Crew | 2nd | −0.8617 |
| 1st | 3rd | 0.0873 |
| 2nd | 3rd | −0.7503 |
| 3rd | 3rd | 1 |
| Crew | 3rd | 0.3111 |
| 1st | Crew | 0.9739 |
| 2nd | Crew | −0.8617 |
| 3rd | Crew | 0.3111 |
| Crew | Crew | 1 |
View data
| Epoch | Training loss | Validation loss |
|---|---|---|
| 1 | 0.6734 | 0.6882 |
| 2 | 0.6562 | 0.6777 |
| 3 | 0.6436 | 0.6710 |
| 4 | 0.6353 | 0.6664 |
| 5 | 0.6300 | 0.6621 |
| 6 | 0.6259 | 0.6569 |
| 7 | 0.6219 | 0.6517 |
| 8 | 0.6181 | 0.6460 |
| 9 | 0.6142 | 0.6400 |
| 10 | 0.6102 | 0.6336 |
| 11 | 0.6060 | 0.6270 |
| 12 | 0.6020 | 0.6207 |
| 13 | 0.5983 | 0.6148 |
| 14 | 0.5950 | 0.6094 |
| 15 | 0.5920 | 0.6039 |
| 16 | 0.5889 | 0.5993 |
| 17 | 0.5864 | 0.5948 |
| 18 | 0.5840 | 0.5904 |
| 19 | 0.5812 | 0.5859 |
| 20 | 0.5784 | 0.5813 |
| 21 | 0.5754 | 0.5768 |
| 22 | 0.5724 | 0.5723 |
| 23 | 0.5693 | 0.5681 |
| 24 | 0.5664 | 0.5643 |
| 25 | 0.5639 | 0.5608 |
| 26 | 0.5614 | 0.5575 |
| 27 | 0.5589 | 0.5543 |
| 28 | 0.5564 | 0.5510 |
| 29 | 0.5537 | 0.5477 |
| 30 | 0.5508 | 0.5442 |
| 31 | 0.5477 | 0.5406 |
| 32 | 0.5446 | 0.5371 |
| 33 | 0.5415 | 0.5338 |
| 34 | 0.5386 | 0.5304 |
| 35 | 0.5359 | 0.5269 |
| 36 | 0.5331 | 0.5235 |
| 37 | 0.5305 | 0.5200 |
| 38 | 0.5279 | 0.5164 |
| 39 | 0.5255 | 0.5130 |
| 40 | 0.5232 | 0.5096 |
| 41 | 0.5211 | 0.5064 |
| 42 | 0.5192 | 0.5033 |
| 43 | 0.5175 | 0.5005 |
| 44 | 0.5160 | 0.4979 |
| 45 | 0.5148 | 0.4955 |
| 46 | 0.5137 | 0.4933 |
| 47 | 0.5129 | 0.4914 |
| 48 | 0.5122 | 0.4898 |
| 49 | 0.5115 | 0.4882 |
| 50 | 0.5109 | 0.4868 |
| 51 | 0.5103 | 0.4854 |
| 52 | 0.5094 | 0.4841 |
| 53 | 0.5082 | 0.4832 |
| 54 | 0.5071 | 0.4825 |
| 55 | 0.5061 | 0.4820 |
| 56 | 0.5049 | 0.4816 |
| 57 | 0.5038 | 0.4811 |
| 58 | 0.5028 | 0.4808 |
| 59 | 0.5018 | 0.4805 |
| 60 | 0.5008 | 0.4805 |
First 60 of 120 rows.
Assumptions
- Enough rows per level — The rarest level has 109 rows.
- The fit holds on held-out rows — Validation loss 0.465 vs training 0.486.
- Read distances, not axes — Any rotation of an embedding fits equally well, so only distances, neighbors and the map's layout carry meaning.
Embedded features
| Feature | Levels | Dimensions | Mean distance | Rarest level n |
|---|---|---|---|---|
| Class | 4 | 2 | 1.560 | 285 |
| Sex | 2 | 2 | 1.724 | 470 |
| Age | 2 | 2 | 2.477 | 109 |
Nearest level in embedding space
| Feature | Level | Nearest | Distance | Rows |
|---|---|---|---|---|
| Class | 1st | Crew | 0.7990 | 325 |
| Class | 2nd | Crew | 1.537 | 285 |
| Class | 3rd | Crew | 1.077 | 706 |
| Class | Crew | 1st | 0.7990 | 885 |
| Sex | Male | Female | 1.724 | 1,731 |
| Sex | Female | Male | 1.724 | 470 |
| Age | Child | Adult | 2.477 | 109 |
| Age | Adult | Child | 2.477 | 2,092 |
Embedding vectors
| Feature | Level | Rows | Dim 1 | Dim 2 |
|---|---|---|---|---|
| Class | 1st | 325 | −1.033 | −0.0349 |
| Class | 2nd | 285 | 0.9877 | −0.8792 |
| Class | 3rd | 706 | −0.1363 | 1.119 |
| Class | Crew | 885 | −0.2384 | 0.0471 |
| Sex | Male | 1,731 | 1.297 | 0.4747 |
| Sex | Female | 470 | 0.0542 | −0.7209 |
| Age | Child | 109 | 0.3936 | 1.653 |
| Age | Adult | 2,092 | 0.6798 | −0.8069 |
- Each level's vector is learned while predicting the target, so levels that act alike on it sit close together; the coordinates themselves have no meaning.
- Network: Class (2-d) + Sex (2-d) + Age (2-d) → 8 relu units → output; Adam, 120 epochs.
Learned 8 level vectors for 3 categorical features from 2201 rows (validation accuracy 0.784); Age's levels are spread out the most, so the model separates them most.
- Validation accuracy
- 0.7841
- Mean distance between Age levels
- 2.477
- Best epoch
- 120
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough rows per level — The rarest level has 109 rows.
- The fit holds on held-out rows — Validation loss 0.465 vs training 0.486.
- Read distances, not axes — Any rotation of an embedding fits equally well, so only distances, neighbors and the map's layout carry meaning.
Embedded features
| Feature | Levels | Dimensions | Mean distance | Rarest level n |
|---|---|---|---|---|
| Class | 4 | 2 | 1.560 | 285 |
| Sex | 2 | 2 | 1.724 | 470 |
| Age | 2 | 2 | 2.477 | 109 |
Nearest level in embedding space
| Feature | Level | Nearest | Distance | Rows |
|---|---|---|---|---|
| Class | 1st | Crew | 0.7990 | 325 |
| Class | 2nd | Crew | 1.537 | 285 |
| Class | 3rd | Crew | 1.077 | 706 |
| Class | Crew | 1st | 0.7990 | 885 |
| Sex | Male | Female | 1.724 | 1,731 |
| Sex | Female | Male | 1.724 | 470 |
| Age | Child | Adult | 2.477 | 109 |
| Age | Adult | Child | 2.477 | 2,092 |
Embedding vectors
| Feature | Level | Rows | Dim 1 | Dim 2 |
|---|---|---|---|---|
| Class | 1st | 325 | −1.033 | −0.0349 |
| Class | 2nd | 285 | 0.9877 | −0.8792 |
| Class | 3rd | 706 | −0.1363 | 1.119 |
| Class | Crew | 885 | −0.2384 | 0.0471 |
| Sex | Male | 1,731 | 1.297 | 0.4747 |
| Sex | Female | 470 | 0.0542 | −0.7209 |
| Age | Child | 109 | 0.3936 | 1.653 |
| Age | Adult | 2,092 | 0.6798 | −0.8069 |
- Each level's vector is learned while predicting the target, so levels that act alike on it sit close together; the coordinates themselves have no meaning.
- Network: Class (2-d) + Sex (2-d) + Age (2-d) → 8 relu units → output; Adam, 120 epochs.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Chickweight chicksml_chickweight · categories: Chick, Diet · covariates: Time · target: weight
- Titanic binaryml_titanic · categories: Class, Sex, Age · target: Survived
- Penguins multiclass nostopml_penguins · categories: island, sex · covariates: bill_len, flipper_len · target: species
- Degenerate n3ml_chickweight · categories: Chick, Diet · covariates: Time · target: weight
- Degenerate infml_chickweight · categories: Chick, Diet · covariates: Time · target: weight
In the guides
Where it sits in the decision guides
- Representation learning for explanation · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric / categorical / boolean · 1 column
- What the network predicts: a number (regression) or classes. The embeddings are shaped by it.
- Categorical featurescategorical / boolean · 1–10 columns
- Each gets an embedding table: one learned vector per level.
- Numeric features (optional)numeric · 0–50 columns
- Standardized and fed beside the embeddings, so the vectors capture what the numbers do not.
Choices you make
model
- Embedding dimensionsdefault —
Vector length per level. Automatic grows with the number of levels, from 2 to 10.
- Hidden layers (units)default 32
Units in each dense layer after the embeddings, input side first. Empty = one layer of 32.
- Activationdefault relu
Nonlinearity in the hidden layers. ReLU is the usual default.
- ReLU(default) — Passes positive signals and zeroes the rest; trains fast and suits most networks.
- tanh — An S-shaped unit with outputs from −1 to 1; a steady choice for small networks.
- Epochsdefault 300
Passes over the training rows (fewer when early stopping ends training).
- Learning ratedefault 0.01
Adam's step size.
- Batch sizedefault —
Rows per gradient step; batches follow a seeded shuffle each epoch, the same in Python and R.
- L2 penalty (λ)default 0.0001
Shrinks weights and embeddings toward zero; raise it when the validation loss climbs.
- Early-stopping patiencedefault 20
Epochs without a better validation loss before stopping; 0 trains on every row for all epochs.
- Validation sharedefault 0.2
Rows held out (shared random stream) to choose the epoch and check the fit.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Enough rows per level
A level with few rows keeps a vector near its random start, so its position means little.
- If violated → Shorter vectors — Two dimensions per level need fewer rows to place each level.
The fit holds on held-out rows
A validation loss far above the training loss means the network memorizes the rows.
- If violated → Stronger L2 penalty — A larger penalty pulls weights and vectors toward zero, so the network memorizes less.
Read distances, not axes
Any rotation of an embedding fits equally well; only distances and neighbors carry meaning.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_dropped
- How many independent units the analysis used; it sets precision and power.
- n_train
- How many independent units the analysis used; it sets precision and power.
- n_valid
- How many independent units the analysis used; it sets precision and power.
- n_features
- How many independent units the analysis used; it sets precision and power.
- n_levels_total
- How many independent units the analysis used; it sets precision and power.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- epochs_run
- Stopping training when a score on held-back rows has stopped improving for a set number of rounds.
- best_epoch
- The network's loss on the rows it learns from and on held-out rows, by epoch; early stopping keeps the epoch of lowest validation loss.
- loss_train
- The network's loss on the rows it learns from and on held-out rows, by epoch; early stopping keeps the epoch of lowest validation loss.
- loss_valid
- The network's loss on the rows it learns from and on held-out rows, by epoch; early stopping keeps the epoch of lowest validation loss.
- fit_train
- How well the embedding network predicts the target on training and held-out rows: R² for numbers, accuracy for classes.
- fit_valid
- How well the embedding network predicts the target on training and held-out rows: R² for numbers, accuracy for classes.
- fit_metric
- How well the embedding network predicts the target on training and held-out rows: R² for numbers, accuracy for classes.
- task
- How well the embedding network predicts the target on training and held-out rows: R² for numbers, accuracy for classes.
- top_feature
- The feature with the largest summary in this explanation: mean |SHAP|, average local effect, score drop or range of the average curve.
- top_spread
- The mean distance between a feature's level vectors: how strongly the network tells its levels apart.
- min_level_n
- A learned vector for each level of a categorical variable, shaped while a network predicts the target; similar levels end up close.
Per group, level or term: emb[<feature>|<level>|<k>], pc1[<feature>|<level>], pc2[<feature>|<level>], count[<feature>|<level>], nearest[<feature>|<level>], dim[<feature>], levels[<feature>], spread[<feature>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses torch, numpy, pandas, codesplash; R uses torch, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same network on LibTorch in double precision on one thread: embedding tables and dense layers start from the same weights on the shared Wichmann–Hill stream, Adam is written out in the helpers, and batches and validation rows come from the same stream. Python's torch and R's torch ship different LibTorch builds, so a kernel can differ by one ulp; over training that stays near 1e-10 relative on the fixtures. Coordinates are only defined up to rotation, but both engines reach the same ones because they take the same steps.
- A network built from torch.nn.Embedding and torch.nn.Linear with the same weights gives the same outputs and gradients (checked in tests/crosscheck/w3ds2c_explain.py); torch.optim.Adam's CPU path uses lerp, so it differs in the last bits from the written-out update.
The exact script CodeSplash ran for example “Titanic binary” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Entity embeddings of categories
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.entity_embeddings 1.0.1 · spec 2022d2568638e1ad
# Dataset: ml_titanic (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import pandas as pd
import codesplash as cs
from codesplash.deep import embeddings as ee # twin of codesplashr::cs_embed_* (shared start, Adam written out)
from codesplash.ml import out_dir
# %% Data
TARGET = "Survived"
CATEGORIES = ["Class", "Sex", "Age"]
COVARIATES = []
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ml_titanic.parquet", columns=list(dict.fromkeys([TARGET] + CATEGORIES + COVARIATES)))
KINDS = {
"Survived": "categorical",
"Class": "categorical",
"Sex": "categorical",
"Age": "categorical",
}
LEVELS = {
"Survived": ["No", "Yes"],
"Class": ["1st", "2nd", "3rd", "Crew"],
"Sex": ["Male", "Female"],
"Age": ["Child", "Adult"],
}
# %% Entity embeddings (one vector per category level, learned while predicting the target)
OPTIONS = {
"dim": 2,
"hidden": [8],
"activation": "relu",
"epochs": 120,
"learning_rate": 0.01,
"batch_size": None,
"weight_decay": 0.0001,
"early_stopping": 20,
"validation_fraction": 0.2,
}
result = ee.analyze(
df, TARGET, CATEGORIES, COVARIATES, KINDS, LEVELS, OPTIONS, SEED, out_dir("target/academy-parity/run-72273/explain.entity_embeddings/titanic_binary/out-python"),
title="Entity embeddings of " + ", ".join(CATEGORIES),
engine=cs.engine_info("torch", "numpy", "pandas"),
)
# %% Result
cs.publish(result)
The exact script CodeSplash ran for example “Titanic binary” · R version 4.5.1 (2025-06-13)
# Entity embeddings of categories
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.entity_embeddings 1.0.1 · spec 2022d2568638e1ad
# Dataset: ml_titanic (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
TARGET <- "Survived"
CATEGORIES <- c("Class", "Sex", "Age")
COVARIATES <- c()
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_titanic.parquet", col_select = unique(c(TARGET, CATEGORIES, COVARIATES))))
KINDS <- list(
"Survived" = "categorical",
"Class" = "categorical",
"Sex" = "categorical",
"Age" = "categorical"
)
LEVELS <- list(
"Survived" = c("No", "Yes"),
"Class" = c("1st", "2nd", "3rd", "Crew"),
"Sex" = c("Male", "Female"),
"Age" = c("Child", "Adult")
)
# %% Entity embeddings (one vector per category level, learned while predicting the target)
OPTIONS <- list(
dim = 2,
hidden = c(8),
activation = "relu",
epochs = 120,
learning_rate = 0.01,
batch_size = NULL,
weight_decay = 0.0001,
early_stopping = 20,
validation_fraction = 0.2
)
out <- "target/academy-parity/run-72273/explain.entity_embeddings/titanic_binary/out-r"
dir.create(out, showWarnings = FALSE, recursive = TRUE)
result <- cs_embed_analyze(
df, TARGET, CATEGORIES, COVARIATES, KINDS, LEVELS, OPTIONS, SEED, out,
title = paste0("Entity embeddings of ", paste(CATEGORIES, collapse = ", ")),
engine = cs_engine_info("torch", "nanoparquet")
)
# %% Result
cs_publish(result)
Sources
- Guo, C., & Berkhahn, F. (2016). Entity embeddings of categorical variables. arXiv:1604.06737.
- Mikolov, T., Sutskever, I., Chen, K., Corrado, G., & Dean, J. (2013). Distributed representations of words and phrases and their compositionality. NeurIPS 26.
- Kingma, D. P., & Ba, J. (2015). Adam: A method for stochastic optimization. ICLR.
- Howard, J., & Gugger, S. (2020). Deep Learning for Coders with fastai and PyTorch, ch. 9 (embedding sizes).
From the CodeSplash method registry · explain.entity_embeddings v1.0.1.