Skip to content

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.

Experimental Python and R agree to 6 decimals Seeded Also called entity embeddings, category embeddings, embedding layer…

A real result

Example “Titanic binary”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Entity embeddings of Class, Sex, AgeRecorded · Python and R agreeRecorded 2026-11-17 · 76 values compared
R

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

Category levels on the first two principal components of their embeddingsWhich levels of a categorical variable does the model treat as alike?
View data
FeatureLevelRowsPC 1PC 2
Class1st325−0.5984−0.7162
Class2nd2851.4400.0837
Class3rd706−0.75740.7367
ClassCrew885−0.0847−0.1043
SexMale1,7310.86211.817e-18
SexFemale470−0.86215.369e-17
AgeChild1091.2388.360e-18
AgeAdult2,092−1.238−8.360e-18
Cosine similarity of the Class embeddingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
ClassClassCosine similarity
1st1st1
2nd1st−0.7241
3rd1st0.0873
Crew1st0.9739
1st2nd−0.7241
2nd2nd1
3rd2nd−0.7503
Crew2nd−0.8617
1st3rd0.0873
2nd3rd−0.7503
3rd3rd1
Crew3rd0.3111
1stCrew0.9739
2ndCrew−0.8617
3rdCrew0.3111
CrewCrew1
Training and validation loss by epochIs the network still learning, and when did it start to overfit?
View data
EpochTraining lossValidation loss
10.67340.6882
20.65620.6777
30.64360.6710
40.63530.6664
50.63000.6621
60.62590.6569
70.62190.6517
80.61810.6460
90.61420.6400
100.61020.6336
110.60600.6270
120.60200.6207
130.59830.6148
140.59500.6094
150.59200.6039
160.58890.5993
170.58640.5948
180.58400.5904
190.58120.5859
200.57840.5813
210.57540.5768
220.57240.5723
230.56930.5681
240.56640.5643
250.56390.5608
260.56140.5575
270.55890.5543
280.55640.5510
290.55370.5477
300.55080.5442
310.54770.5406
320.54460.5371
330.54150.5338
340.53860.5304
350.53590.5269
360.53310.5235
370.53050.5200
380.52790.5164
390.52550.5130
400.52320.5096
410.52110.5064
420.51920.5033
430.51750.5005
440.51600.4979
450.51480.4955
460.51370.4933
470.51290.4914
480.51220.4898
490.51150.4882
500.51090.4868
510.51030.4854
520.50940.4841
530.50820.4832
540.50710.4825
550.50610.4820
560.50490.4816
570.50380.4811
580.50280.4808
590.50180.4805
600.50080.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

FeatureLevelsDimensionsMean distanceRarest level n
Class421.560285
Sex221.724470
Age222.477109

Nearest level in embedding space

FeatureLevelNearestDistanceRows
Class1stCrew0.7990325
Class2ndCrew1.537285
Class3rdCrew1.077706
ClassCrew1st0.7990885
SexMaleFemale1.7241,731
SexFemaleMale1.724470
AgeChildAdult2.477109
AgeAdultChild2.4772,092

Embedding vectors

FeatureLevelRowsDim 1Dim 2
Class1st325−1.033−0.0349
Class2nd2850.9877−0.8792
Class3rd706−0.13631.119
ClassCrew885−0.23840.0471
SexMale1,7311.2970.4747
SexFemale4700.0542−0.7209
AgeChild1090.39361.653
AgeAdult2,0920.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.
Python

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

FeatureLevelsDimensionsMean distanceRarest level n
Class421.560285
Sex221.724470
Age222.477109

Nearest level in embedding space

FeatureLevelNearestDistanceRows
Class1stCrew0.7990325
Class2ndCrew1.537285
Class3rdCrew1.077706
ClassCrew1st0.7990885
SexMaleFemale1.7241,731
SexFemaleMale1.724470
AgeChildAdult2.477109
AgeAdultChild2.4772,092

Embedding vectors

FeatureLevelRowsDim 1Dim 2
Class1st325−1.033−0.0349
Class2nd2850.9877−0.8792
Class3rd706−0.13631.119
ClassCrew885−0.23840.0471
SexMale1,7311.2970.4747
SexFemale4700.0542−0.7209
AgeChild1090.39361.653
AgeAdult2,0920.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.
Python

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)
R

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.