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.
A real result
Example “Iris”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| species | t-SNE 1 | t-SNE 2 |
|---|---|---|
| setosa | −17.485 | 0.6277 |
| setosa | −14.167 | 0.9543 |
| setosa | −15.036 | 0.1135 |
| setosa | −14.400 | 0.0318 |
| setosa | −17.986 | 0.1561 |
| setosa | −19.595 | 0.6255 |
| setosa | −16.058 | −0.4235 |
| setosa | −16.617 | 0.5462 |
| setosa | −13.461 | 0.2454 |
| setosa | −14.742 | 0.8895 |
| setosa | −18.809 | 1.042 |
| setosa | −16.334 | 0.0119 |
| setosa | −14.052 | 0.6368 |
| setosa | −13.740 | −0.2452 |
| setosa | −20.066 | 1.079 |
| setosa | −20.596 | 0.6642 |
| setosa | −19.602 | 0.6767 |
| setosa | −17.469 | 0.6009 |
| setosa | −19.452 | 1.238 |
| setosa | −19.035 | 0.1696 |
| setosa | −17.292 | 1.572 |
| setosa | −18.582 | 0.3315 |
| setosa | −17.436 | −0.8033 |
| setosa | −16.229 | 1.292 |
| setosa | −16.319 | −0.0289 |
| setosa | −14.304 | 1.205 |
| setosa | −16.638 | 0.5695 |
| setosa | −17.637 | 0.9233 |
| setosa | −16.942 | 1.123 |
| setosa | −15.077 | 0.1450 |
| setosa | −14.660 | 0.5266 |
| setosa | −17.262 | 1.586 |
| setosa | −20.067 | 0.2069 |
| setosa | −20.339 | 0.5875 |
| setosa | −14.767 | 0.8968 |
| setosa | −15.366 | 0.9621 |
| setosa | −17.999 | 1.507 |
| setosa | −17.888 | −0.1899 |
| setosa | −13.822 | −0.0449 |
| setosa | −16.781 | 0.8663 |
| setosa | −17.293 | 0.2274 |
| setosa | −12.353 | 0.4452 |
| setosa | −14.607 | −0.4924 |
| setosa | −17.300 | −0.0602 |
| setosa | −19.130 | 0.0106 |
| setosa | −14.054 | 0.6586 |
| setosa | −19.035 | 0.1477 |
| setosa | −14.894 | −0.1504 |
| setosa | −18.706 | 0.8493 |
| setosa | −15.982 | 0.7493 |
| versicolor | 10.220 | −2.409 |
| versicolor | 9.667 | −1.459 |
| versicolor | 10.306 | −2.145 |
| versicolor | 2.346 | −0.8474 |
| versicolor | 7.986 | −1.192 |
| versicolor | 4.848 | 0.1438 |
| versicolor | 10.854 | 1.761 |
| versicolor | 1.676 | 0.0775 |
| versicolor | 8.255 | −1.806 |
| versicolor | 3.211 | 0.8110 |
First 60 of 150 rows.
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%.
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"}],
})
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.