The GP latent variable model: a map learned by asking what could have generated the data
The GPLVM finds low-dimensional coordinates whose GP mapping best explains every column. Its link to probabilistic PCA, what its likelihood rewards, and how to check a map that has no ground truth.
What runs in CodeSplash
- UNC007Gaussian process latent variable model (GPLVM) Runs in CodeSplash (Experimental)
- GP latent variable map Experimental
You will be able to
- Write the GPLVM likelihood and explain how a linear kernel gives probabilistic PCA
- Explain why a higher likelihood can come with a distorted map
- Check a GPLVM map with held-out reconstruction, restarts and alignment
- Place new rows on a fitted map the right way
Turning regression around
ReadA GP regression knows the inputs and learns a smooth function to the outputs. The GPLVMGP latent variable model (GPLVM)A map that places rows so every variable is a smooth Gaussian-process function of the positions; linear kernel = probabilistic PCA. knows only the outputs, your columns, and asks: which low-dimensional coordinates , pushed through a smooth GP mapping, would most plausibly have produced them?
Each of the columns is a GP over the same latent coordinates. For centered data and ,
maximized over the coordinates, the kernel settings and the noise.
A linear kernel is PCA
ReadWith a linear kernel , the GPLVM's best coordinates are those of probabilistic PCA: the map can only stretch and rotate. An RBF kernel lets the map bend, so rows can sit on a curved surface.
GPLVM (rbf kernel) of 4 variables in 2 latent dimensions: noise SD 0.084 on the standardized variables.
- Log likelihood
- 280.53
- Noise SD
- 0.0840
Plots
View data
| species | Latent 1 | Latent 2 |
|---|---|---|
| setosa | 0.4236 | −0.2583 |
| setosa | 0.2566 | −0.0683 |
| setosa | 0.3898 | −0.1345 |
| setosa | 0.3679 | −0.0835 |
| setosa | 0.4807 | −0.2671 |
| setosa | 1.076 | −0.4128 |
| setosa | 0.4941 | −0.1879 |
| setosa | 0.4014 | −0.2272 |
| setosa | 0.3989 | 0.1124 |
| setosa | 0.2994 | −0.1154 |
| setosa | 0.4395 | −0.3232 |
| setosa | 0.4383 | −0.2068 |
| setosa | 0.2706 | −0.0382 |
| setosa | 0.4252 | 0.0085 |
| setosa | 0.4874 | −0.3962 |
| setosa | 0.9078 | −0.4414 |
| setosa | 0.5164 | −0.3478 |
| setosa | 0.4213 | −0.2589 |
| setosa | 0.4137 | −0.3697 |
| setosa | 0.5381 | −0.3086 |
| setosa | 0.3333 | −0.2752 |
| setosa | 0.4925 | −0.2937 |
| setosa | 0.5894 | −0.2356 |
| setosa | 0.3309 | −0.2230 |
| setosa | 0.4285 | −0.2087 |
| setosa | 0.2305 | −0.0886 |
| setosa | 0.3935 | −0.2303 |
| setosa | 0.4032 | −0.2697 |
| setosa | 0.3721 | −0.2487 |
| setosa | 0.3805 | −0.1376 |
| setosa | 0.3163 | −0.1106 |
| setosa | 0.3326 | −0.2762 |
| setosa | 0.6906 | −0.3590 |
| setosa | 0.6460 | −0.3898 |
| setosa | 0.3006 | −0.1219 |
| setosa | 0.3364 | −0.1688 |
| setosa | 0.3669 | −0.3014 |
| setosa | 0.5039 | −0.2579 |
| setosa | 0.4011 | 0.0023 |
| setosa | 0.3842 | −0.2383 |
| setosa | 0.4436 | −0.2479 |
| setosa | 1.388 | 0.6133 |
| setosa | 0.4683 | −0.1064 |
| setosa | 0.4267 | −0.2517 |
| setosa | 1.074 | −0.3861 |
| setosa | 0.2826 | −0.0660 |
| setosa | 0.5366 | −0.3089 |
| setosa | 0.4108 | −0.1248 |
| setosa | 0.4569 | −0.3129 |
| setosa | 0.3677 | −0.2014 |
| versicolor | −0.1151 | −0.6400 |
| versicolor | −0.2574 | −0.8483 |
| versicolor | −0.1414 | −0.5931 |
| versicolor | 0.7071 | 0.5030 |
| versicolor | −0.2122 | −0.3159 |
| versicolor | 0.0880 | 0.7642 |
| versicolor | −0.2754 | −0.8553 |
| versicolor | 0.6800 | 0.4047 |
| versicolor | −0.1239 | −0.4065 |
| versicolor | −0.6070 | 0.6845 |
First 60 of 150 rows.
Latent dimensions
| Dimension | SD of the positions |
|---|---|
| 1 | 0.6208 |
| 2 | 0.5065 |
The exact R script · R R version 4.5.1 (2025-06-13)
# GP latent variable map
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.gplvm 1.0.0 · spec 5ba980d3907bc45d
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))
# %% Data
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
cs_check_finite_columns(df, FEATURES)
rows <- cs_ml_complete_rows(df, FEATURES)
if (length(rows) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
}
# %% GPLVM (<= max rows, evenly spaced; a GPLVM has no projection for rows it wasn't fitted on)
fit_rows <- cs_ml_even_sample(length(rows), 500)
if (length(fit_rows) < length(rows)) {
warnings <- c(warnings, sprintf("The map was fitted on %s evenly spaced rows of %s; the others are left out (a GPLVM can't place new rows without refitting).",
format(length(fit_rows), big.mark = ","), format(length(rows), big.mark = ",")))
}
n_complete <- length(rows)
rows <- rows[fit_rows + 1L]
K <- as.integer(2)
if (length(rows) < K + 2L) {
cs_error("CS_E_TOO_FEW_ROWS", what = "A GP latent variable map", min = K + 2L, n = length(rows))
}
Y <- cs_ml_numeric_matrix(df, FEATURES, rows)
constant <- apply(Y, 2, max) == apply(Y, 2, min) # exact test (a rounded SD can be 1e-16 instead of 0)
if (all(constant)) cs_error("CS_E_CONSTANT", column = FEATURES[1])
s <- apply(Y, 2, stats::sd)
s[constant] <- 1
Y <- sweep(sweep(Y, 2, colMeans(Y)), 2, s, "/")
Y[, constant] <- 0 # constant columns carry nothing
if (K >= ncol(Y)) {
cs_error("CS_E_INVALID_OPTION", option = "Latent dimensions", allowed = sprintf("fewer than the %d variables", ncol(Y)), value = K)
}
KERNEL <- "rbf"
fit <- cs_ml_gplvm_fit(Y, K, KERNEL, 2000)
Z <- fit$X
if (isTRUE(fit$at_bound)) {
warnings <- c(warnings, "The map fits the variables almost exactly (noise at its floor or signal at its ceiling): use fewer latent dimensions or more rows; maps like this differ more between runs.")
}
if (!isTRUE(fit$converged)) {
warnings <- c(warnings, "The optimizer stopped before the gradient was flat; raise the most optimizer steps or treat the map with care.")
}
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.gplvm/iris_rbf/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Result
values <- list(n = n_complete, n_fit = length(rows), n_variables = length(FEATURES), n_components = K,
log_likelihood = fit$log_likelihood, signal_sd = fit$signal_sd, noise_sd = fit$noise_sd)
for (j in seq_len(K)) {
values[[sprintf("latent_sd[%d]", j)]] <- fit$latent_sd[j]
values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
}
charts <- list()
if (K >= 2) {
pick <- chart_rows(length(rows))
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- as.character(df[[LABEL]][rows[pick] + 1L]); g[is.na(g)] <- "(missing)"; g
}
charts <- list(cs_chart("map", "cluster-scatter", "GP latent variable map", list(
x = cs_col("Latent 1", Z[pick, 1], "numeric"),
y = cs_col("Latent 2", Z[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
)))
}
cs_publish(list(
title = "GP latent variable map",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("GPLVM (%s kernel) of %d variables in %d latent dimensions: noise SD %.3f on the standardized variables.",
KERNEL, length(FEATURES), K, fit$noise_sd),
statistics = list(list(key = "log_likelihood", label = "Log likelihood", value = fit$log_likelihood),
list(key = "noise_sd", label = "Noise SD", value = fit$noise_sd)),
tables = list(list(key = "latent", title = "Latent dimensions",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
list(key = "sd", label = "SD of the positions", type = "number")),
rows = lapply(seq_len(K), function(j) list(dimension = j, sd = fit$latent_sd[j])))),
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
GPLVM (rbf kernel) of 4 variables in 2 latent dimensions: noise SD 0.084 on the standardized variables.
- Log likelihood
- 280.53
- Noise SD
- 0.0840
To keep this page light, the plots are shown once, under the R tab.
Latent dimensions
| Dimension | SD of the positions |
|---|---|
| 1 | 0.6208 |
| 2 | 0.5065 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# GP latent variable map
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.gplvm 1.0.0 · spec 5ba980d3907bc45d
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import embed as csembed
from codesplash.ml import gplvm as csgplvm
def chart_rows(n, cap=2000):
return np.arange(n) if n <= cap else np.unique(np.linspace(0, n - 1, cap).round().astype(int))
# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species"
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
cs.check_finite_columns(df, FEATURES)
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
# %% GPLVM (≤ max rows, evenly spaced; a GPLVM has no projection for rows it wasn't fitted on)
fit_rows = csc.even_sample(len(rows), 500)
if len(fit_rows) < len(rows):
warnings.append(f"The map was fitted on {len(fit_rows):,} evenly spaced rows of {len(rows):,}; the others are left out (a GPLVM can't place new rows without refitting).")
n_complete = len(rows)
rows = rows[fit_rows]
K = 2
if len(rows) < K + 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A GP latent variable map", min=K + 2, n=len(rows))
raw = csembed.numeric_matrix(df, FEATURES, rows)
constant = raw.max(axis=0) == raw.min(axis=0) # exact test (a rounded SD can be 1e-16 instead of 0)
if bool(np.all(constant)):
cs.cs_error("CS_E_CONSTANT", column=FEATURES[0])
sd = raw.std(axis=0, ddof=1)
sd[constant] = 1.0
Y = (raw - raw.mean(axis=0)) / sd
Y[:, constant] = 0.0 # constant columns carry nothing
if K >= Y.shape[1]:
cs.cs_error("CS_E_INVALID_OPTION", option="Latent dimensions", allowed=f"fewer than the {Y.shape[1]} variables", value=K)
KERNEL = "rbf"
fit = csgplvm.fit(Y, K, KERNEL, 2000)
Z = fit["X"]
if fit["at_bound"]:
warnings.append("The map fits the variables almost exactly (noise at its floor or signal at its ceiling): use fewer latent dimensions or more rows; maps like this differ more between runs.")
if not fit["converged"]:
warnings.append("The optimizer stopped before the gradient was flat; raise the most optimizer steps or treat the map with care.")
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.gplvm/iris_rbf/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
emb[f"dim_{j + 1}"] = Z[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Result
values = {
"n": n_complete, "n_fit": len(rows), "n_variables": len(FEATURES), "n_components": K,
"log_likelihood": fit["log_likelihood"], "signal_sd": fit["signal_sd"], "noise_sd": fit["noise_sd"],
}
for j in range(K):
values[f"latent_sd[{j + 1}]"] = fit["latent_sd"][j]
values[f"score_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
charts = []
if K >= 2:
pick = chart_rows(len(rows))
groups = ["All rows"] * len(pick) if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL].iloc[rows[pick]]]
charts.append(cs.chart("map", "cluster-scatter", "GP latent variable map", {
"x": cs.col("Latent 1", Z[pick, 0], "numeric"),
"y": cs.col("Latent 2", Z[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}))
cs.publish({
"title": "GP latent variable map",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": len(rows),
"summary": f"GPLVM ({KERNEL} kernel) of {len(FEATURES)} variables in {K} latent dimensions: noise SD {fit['noise_sd']:.3f} on the standardized variables.",
"statistics": [
{"key": "log_likelihood", "label": "Log likelihood", "value": fit["log_likelihood"]},
{"key": "noise_sd", "label": "Noise SD", "value": fit["noise_sd"]},
],
"tables": [{
"key": "latent",
"title": "Latent dimensions",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "sd", "label": "SD of the positions", "type": "number"}],
"rows": [{"dimension": j + 1, "sd": fit["latent_sd"][j]} for j in range(K)],
}],
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
On iris the RBF map's log likelihood was 281, against 46.7 for the linear one, and the noise SD fell from 0.205 to 0.0840.
Does the bigger likelihood mean a better map?
PredictPredict first
The bending map explains the columns with much less noise. Is its picture of how rows relate more trustworthy?
Reveal
Not by itself. A flexible mapping can explain the data while placing rows in a distorted geometry, and coordinates can be rotated or flipped without changing the fit. Check held-out reconstruction, compare restarts after aligning them, and see whether neighbors on the map are neighbors in the data.
Checking a map with no ground truth
Read- Start from PCA and from a few other starts; the likelihood surface has local optima.
- Hold out entries (some cells of some rows), refit, and score how well the map predicts them.
- Align before comparing. Rotation, reflection and other transforms leave the likelihood unchanged, so two good fits can look different until aligned.
- Vary and the scaling; dense exact inference costs grow with the cube of the row count, so large tables need sparse approximations that change the inference.
Point estimates of understate their uncertainty. A Bayesian GPLVM adds a variational posterior over , which helps, with its own approximation error.
New rows
ReadFor a genuinely new row, infer its latent coordinates from its observed columns using the fitted mapping, holding the global settings fixed. Refitting everything with the new row moves the old coordinates too, so align before you compare old and new maps.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| GPLVM (UNC007) | Runs in CodeSplash (Experimental): GP latent variable map, linear or RBF kernel, with a row cap for large tables |
Check your understanding
CheckpointCheck yourself
A GPLVM with a linear kernel gives which familiar method?
Show the answer
Answer: b
With the mapping is linear, and the best coordinates match probabilistic PCA's.
Check yourself
Two GPLVM fits on the same data look like mirror images. Is one wrong?
Show the answer
Answer: b
Latent coordinates are identified only up to such transforms. Alignment comes before interpretation.
Check yourself
Which check best shows whether a GPLVM map generalizes?
Show the answer
Answer: a
Held-out reconstruction is scored on data the fit never saw. The training likelihood rewards flexibility.
Check yourself
How do you place a new row on a fitted GPLVM map?
Show the answer
Answer: b
Refitting moves every old coordinate. Inference with fixed global settings keeps the old map in place.
Do it on your own data
In the appUnder Map the data, open GP latent variable map, fit a linear and an RBF map on the same columns, and compare their noise SD and how the rows sit. The app reports the fit, not a held-out check: for held-out reconstruction, open the run's code as a notebook and mask some cells.
Concepts in this lesson