Skip to content

CDiscover · discover.tsne

t-SNE map

Which rows are close to each other, shown as a two-dimensional map?

t-SNE embedding into two dimensions (scikit-learn ↔ Rtsne, Barnes–Hut). Both engines start from the same PCA layout with the same perplexity, learning rate, exaggeration and momentum schedule; their gradient approximations differ, so they are compared on neighborhood preservation (trustworthiness, kNN preservation), not coordinates.

Verified in Python and R Python and R use different algorithms; results agree in substance

A real result

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

t-SNE mapRecorded · Python and R agreeRecorded 2026-11-25 · 5 values compared · largest relative difference 7.5e-3
R

t-SNE map of 150 rows: trustworthiness 0.987, 80% of each row's 10 nearest neighbors kept.

Trustworthiness (k = 10)
0.9874
Neighbors kept
80.0%

Plots

t-SNE mapWhich rows group together, and how well separated are the groups?
View data
speciest-SNE 1t-SNE 2
setosa−17.4850.6277
setosa−14.1670.9543
setosa−15.0360.1135
setosa−14.4000.0318
setosa−17.9860.1561
setosa−19.5950.6255
setosa−16.058−0.4235
setosa−16.6170.5462
setosa−13.4610.2454
setosa−14.7420.8895
setosa−18.8091.042
setosa−16.3340.0119
setosa−14.0520.6368
setosa−13.740−0.2452
setosa−20.0661.079
setosa−20.5960.6642
setosa−19.6020.6767
setosa−17.4690.6009
setosa−19.4521.238
setosa−19.0350.1696
setosa−17.2921.572
setosa−18.5820.3315
setosa−17.436−0.8033
setosa−16.2291.292
setosa−16.319−0.0289
setosa−14.3041.205
setosa−16.6380.5695
setosa−17.6370.9233
setosa−16.9421.123
setosa−15.0770.1450
setosa−14.6600.5266
setosa−17.2621.586
setosa−20.0670.2069
setosa−20.3390.5875
setosa−14.7670.8968
setosa−15.3660.9621
setosa−17.9991.507
setosa−17.888−0.1899
setosa−13.822−0.0449
setosa−16.7810.8663
setosa−17.2930.2274
setosa−12.3530.4452
setosa−14.607−0.4924
setosa−17.300−0.0602
setosa−19.1300.0106
setosa−14.0540.6586
setosa−19.0350.1477
setosa−14.894−0.1504
setosa−18.7060.8493
setosa−15.9820.7493
versicolor10.220−2.409
versicolor9.667−1.459
versicolor10.306−2.145
versicolor2.346−0.8474
versicolor7.986−1.192
versicolor4.8480.1438
versicolor10.8541.761
versicolor1.6760.0775
versicolor8.255−1.806
versicolor3.2110.8110

First 60 of 150 rows.

Python

t-SNE map of 150 rows: trustworthiness 0.986, 79% of each row's 10 nearest neighbors kept.

Trustworthiness (k = 10)
0.9864
Neighbors kept
79.4%

To keep this page light, the plots are shown once, under the R tab.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Irisml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins mixedml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
  • Usarrests small perplexity capml_usarrests · features: Murder, Assault, UrbanPop, Rape

In the guides

Where it sits in the decision guides

  • Representation visualization (t-SNE, UMAP) · DS & ML Decision Guide · Describe — summarize and visualize

What you need

Featuresnumeric / categorical / boolean · 2–2000 columns
Columns used to describe each row. Numbers are standardized; categories become indicator columns.
Color points bycategorical / boolean · 0–1 column
Optional column used only to color the points; it does not affect the layout.

Choices you make

model

Perplexitydefault 30

Roughly the number of neighbors each point attends to (capped at (n − 1) / 3).

Iterationsdefault 1000

Optimization steps. Raise it if the map still looks unsettled.

Advanced

Barnes–Hut angledefault 0.5

Speed–accuracy trade-off of the Barnes–Hut approximation. 0 is exact but slow.

preprocess

Standardize featuresdefault on

Standardize numbers so each counts equally in the distances.

What it reports

n
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.
perplexity
Roughly how many neighbors each row attends to in t-SNE; small values show fine detail, and can invent it.
trustworthiness
A 0–1 score for whether rows that look close on a map are really close in the data.
knn_preservation
The share of each row's nearest neighbors that stay nearest after reducing dimensions.

Python and R

Python and R use different algorithms; results agree in substance (relative tolerance 1e-9). Python uses scikit-learn; R uses Rtsne.

Default traps between the two languages

  • Pinned in both: PCA start (SD 1e-4), perplexity, learning rate max(n / 48, 50), early exaggeration 12 for 250 iterations, momentum 0.5 → 0.8, angle, iterations. scikit-learn and Rtsne implement Barnes–Hut gradients and gains differently, so maps differ; trustworthiness (k = 10) and kNN preservation on the same ≤ 1,000 rows agree within 4% and 20%.
Python

The exact script CodeSplash ran for example “Iris” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# t-SNE map
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tsne 1.0.0 · spec a810565fc549888c
# 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
from sklearn.manifold import TSNE

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed

# %% Data
IMPUTE = "median"
SCALE = "standard"
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "sepal_length": "numeric",
        "sepal_width": "numeric",
        "petal_length": "numeric",
        "petal_width": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=[LABEL])[LABEL]

# %% t-SNE (same start and schedule as Rtsne)
n = len(rows)
perplexity = min(30, (n - 1) / 3 - 1e-6)  # Rtsne requires 3 · perplexity < n − 1
learning_rate = max(n / 12 / 4, 50.0)  # scikit-learn's "auto", pinned for both engines
init = csembed.pca_init(X, -1e-4)  # PCA start, first column SD 1e-4
tsne = TSNE(
    n_components=2,
    perplexity=perplexity,
    early_exaggeration=12.0,
    learning_rate=learning_rate,
    max_iter=1000,
    angle=0.5,
    method="barnes_hut",
    init=init,
    random_state=42,
    n_jobs=1,
)
Y = tsne.fit_transform(X)
METHOD_LABEL = "t-SNE"
ENGINE_PACKAGES = ("scikit-learn", "numpy", "pandas")
extra_values = {"perplexity": perplexity}

# %% Neighborhood preservation (same rows in both engines)
K_EVAL = 10
sample = csembed.sample_rows(len(rows))
k_eval = min(K_EVAL, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Y[sample], k_eval)
keep = csembed.knn_preservation(X[sample], Y[sample], k_eval)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.tsne/iris/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), "dim_1": Y[:, 0], "dim_2": Y[:, 1]})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Result
values = {"n": len(rows), "n_features": len(FEATURES), "trustworthiness": trust, "knn_preservation": keep}
values.update(extra_values)
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
cs.publish({
    "title": "t-SNE map",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{METHOD_LABEL} map of {len(rows)} rows: trustworthiness {trust:.3f}, {keep:.0%} of each row's {k_eval} nearest neighbors kept.",
    "statistics": [
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "knn_preservation", "label": "Neighbors kept", "value": keep, "format": "percent"},
    ],
    "charts": [cs.chart("map", "cluster-scatter", f"{METHOD_LABEL} map", {
        "x": cs.col(f"{METHOD_LABEL} 1", Y[pick, 0], "numeric"),
        "y": cs.col(f"{METHOD_LABEL} 2", Y[pick, 1], "numeric"),
        "cluster": cs.col(LABEL or "Group", groups, "categorical"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")],
    "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” · R version 4.5.1 (2025-06-13)

# t-SNE map
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tsne 1.0.0 · spec a810565fc549888c
# 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)
suppressPackageStartupMessages(library(Rtsne))

# %% Data
IMPUTE <- "median"
SCALE <- "standard"
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    sepal_length = "numeric",
    sepal_width = "numeric",
    petal_length = "numeric",
    petal_width = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = LABEL))[[LABEL]]

# %% t-SNE (same start and schedule as scikit-learn)
n <- length(rows)
perplexity <- min(30, (n - 1) / 3 - 1e-6)
learning_rate <- max(n / 12 / 4, 50)
init <- cs_ml_pca_init(X, -1e-4)  # PCA start, first column SD 1e-4
set.seed(42)
fit <- Rtsne::Rtsne(
  X,
  dims = 2,
  perplexity = perplexity,
  theta = 0.5,
  max_iter = 1000,
  pca = FALSE,
  check_duplicates = FALSE,
  Y_init = init,
  stop_lying_iter = 250L,  # keep early exaggeration with a given start (as scikit-learn)
  mom_switch_iter = 250L,
  momentum = 0.5,
  final_momentum = 0.8,
  eta = learning_rate,
  exaggeration_factor = 12,
  num_threads = 1
)
Y <- fit$Y
METHOD_LABEL <- "t-SNE"
ENGINE_PACKAGES <- c("Rtsne", "nanoparquet")
extra_values <- list(perplexity = perplexity)

# %% Neighborhood preservation (same rows in both engines)
K_EVAL <- 10L
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(K_EVAL, length(sample) - 2L)
trust <- cs_ml_trustworthiness(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval)
keep <- cs_ml_knn_preservation(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.tsne/iris/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), dim_1 = Y[, 1], dim_2 = Y[, 2]), file.path(out, "embedding.parquet"))

# %% Result
values <- c(list(n = length(rows), n_features = length(FEATURES), trustworthiness = trust, knn_preservation = keep), extra_values)
pick <- cs_ml_sample_rows(length(rows), 5000)
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
}
cs_publish(list(
  title = "t-SNE map",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = sprintf("%s map of %d rows: trustworthiness %.3f, %.0f%% of each row's %d nearest neighbors kept.",
                    METHOD_LABEL, length(rows), trust, 100 * keep, k_eval),
  statistics = list(list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
                    list(key = "knn_preservation", label = "Neighbors kept", value = keep, format = "percent")),
  charts = list(cs_chart("map", "cluster-scatter", paste(METHOD_LABEL, "map"), list(
    x = cs_col(paste(METHOD_LABEL, 1), Y[pick, 1], "numeric"),
    y = cs_col(paste(METHOD_LABEL, 2), Y[pick, 2], "numeric"),
    cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%d of %d rows shown.", length(pick), length(rows)))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))

Sources

  • van der Maaten L, Hinton G (2008). Visualizing data using t-SNE. JMLR 9:2579–2605.
  • van der Maaten L (2014). Accelerating t-SNE using tree-based algorithms. JMLR 15:3221–3245.

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