Skip to content

CDiscover · discover.gplvm

GP latent variable map

Which smooth, low-dimensional positions explain all of these numeric variables at once?

A Gaussian process latent variable model (GPLVM) places every row at a point in two or more latent dimensions so that each standardized variable is a smooth Gaussian-process function of those points plus noise. Unlike PCA the map can bend (radial basis kernel); with the linear kernel it reduces to probabilistic PCA. The positions and kernel settings maximize the posterior under a standard normal prior, starting from the PCA scores, with the same optimizer in Python and R. Experimental.

Experimental Python and R agree to 6 decimals Also called GPLVM, Gaussian process latent variable model, probabilistic nonlinear PCA…

A real result

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

GP latent variable mapRecorded · Python and R agreeRecorded 2026-11-25 · 11 values compared · largest relative difference 1.9e-6
R

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

GP latent variable mapWhich rows group together, and how well separated are the groups?
View data
speciesLatent 1Latent 2
setosa0.4236−0.2583
setosa0.2566−0.0683
setosa0.3898−0.1345
setosa0.3679−0.0835
setosa0.4807−0.2671
setosa1.076−0.4128
setosa0.4941−0.1879
setosa0.4014−0.2272
setosa0.39890.1124
setosa0.2994−0.1154
setosa0.4395−0.3232
setosa0.4383−0.2068
setosa0.2706−0.0382
setosa0.42520.0085
setosa0.4874−0.3962
setosa0.9078−0.4414
setosa0.5164−0.3478
setosa0.4213−0.2589
setosa0.4137−0.3697
setosa0.5381−0.3086
setosa0.3333−0.2752
setosa0.4925−0.2937
setosa0.5894−0.2356
setosa0.3309−0.2230
setosa0.4285−0.2087
setosa0.2305−0.0886
setosa0.3935−0.2303
setosa0.4032−0.2697
setosa0.3721−0.2487
setosa0.3805−0.1376
setosa0.3163−0.1106
setosa0.3326−0.2762
setosa0.6906−0.3590
setosa0.6460−0.3898
setosa0.3006−0.1219
setosa0.3364−0.1688
setosa0.3669−0.3014
setosa0.5039−0.2579
setosa0.40110.0023
setosa0.3842−0.2383
setosa0.4436−0.2479
setosa1.3880.6133
setosa0.4683−0.1064
setosa0.4267−0.2517
setosa1.074−0.3861
setosa0.2826−0.0660
setosa0.5366−0.3089
setosa0.4108−0.1248
setosa0.4569−0.3129
setosa0.3677−0.2014
versicolor−0.1151−0.6400
versicolor−0.2574−0.8483
versicolor−0.1414−0.5931
versicolor0.70710.5030
versicolor−0.2122−0.3159
versicolor0.08800.7642
versicolor−0.2754−0.8553
versicolor0.68000.4047
versicolor−0.1239−0.4065
versicolor−0.60700.6845

First 60 of 150 rows.

Latent dimensions

DimensionSD of the positions
10.6208
20.5065
Python

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

DimensionSD of the positions
10.6208
20.5065

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Iris rbfml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Iris linear ppcaml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Usarrests cappedml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Iris one dimml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Degenerate infml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Degenerate n2ml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Degenerate all naml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Degenerate constantml_iris · features: sepal_length, sepal_width, petal_length, petal_width

In the guides

Where it sits in the decision guides

  • Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Variablesnumeric · 2–200 columns
Numbers to map (standardized; rows with a missing value are left out).
Color points bycategorical / boolean · 0–1 column
Optional: colors the map only.

Choices you make

model

Kerneldefault rbf

How the variables depend on the latent positions.

  • Radial basis (nonlinear)(default) — Each variable is a smooth curved function of the latent positions.
  • Linear (probabilistic PCA) — Each variable is a straight-line function: the map spans the principal-component plane.
Latent dimensionsdefault 2

Number of latent coordinates per row.

Advanced

Most rows to mapdefault 500

Larger tables are mapped on this many evenly spaced rows; a GPLVM can't place new rows without refitting, so the rest are left out.

Most optimizer stepsdefault 2000

Steps of the optimizer before it stops; it stops earlier once the gradient is flat.

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.

  • One start, one local optimumNot checked from data: state why it holds

    The fit starts from the PCA scores and finds a nearby optimum. A different start can give a different map; compare the log likelihood.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_fit
Log posterior of the fitted map, and the kernel's signal and noise SDs on the standardized variables.
n_variables
How many independent units the analysis used; it sets precision and power.
n_components
How many independent units the analysis used; it sets precision and power.
log_likelihood
Log posterior of the fitted map, and the kernel's signal and noise SDs on the standardized variables.
signal_sd
Log posterior of the fitted map, and the kernel's signal and noise SDs on the standardized variables.
noise_sd
Log posterior of the fitted map, and the kernel's signal and noise SDs on the standardized variables.

Per group, level or term: latent_sd[<k>], score_check[<k>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-5). Python uses numpy, scipy; R uses codesplashr.

Default traps between the two languages

  • Both engines run the same projected BFGS from the same PCA start on the same analytic gradient. The objective doesn't change when the map is rotated, so the result is rotated to its principal axes with canonical signs; the remaining differences come from LAPACK rounding along those flat directions and stay near 10⁻⁶.
Python

The exact script CodeSplash ran for example “Iris rbf” · 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"}],
})
R

The exact script CodeSplash ran for example “Iris rbf” · 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"))
))

Sources

  • Lawrence ND (2005). Probabilistic non-linear principal component analysis with Gaussian process latent variable models. Journal of Machine Learning Research 6, 1783–1816.
  • Rasmussen CE, Williams CKI (2006). Gaussian Processes for Machine Learning. MIT Press.

From the CodeSplash method registry · discover.gplvm v1.0.0.