AI & Machine Learning Master Course — 087. Nonlinear embeddings and visualization traps
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 087: Nonlinear embeddings and visualization traps
Prerequisites: Lesson 086. Learning outcome: Use neighborhood visualizations without overclaiming distances or clusters.
A map can preserve one relationship and distort another
Nonlinear embeddings place high-dimensional observations in two or three dimensions for exploration. They can reveal local neighborhoods that a linear projection misses. They cannot generally preserve every distance, density, direction, and global relationship at once. A compelling plot therefore needs an explicit account of what the method tries to preserve.
Think of flattening a curved sheet. Nearby points on the sheet may be placed near each other, while distances between faraway regions change. A two-dimensional map of observations is a constructed representation, not a photograph of their intrinsic categories. Empty spaces and apparent islands can arise from the method's objective and settings.
PCA offers a useful linear reference. If a nonlinear method produces a more separated picture, ask whether the improvement concerns neighborhood preservation, reconstruction, or simply visual contrast. Color can aid inspection but can also make weak boundaries appear categorical. Keep the uncolored geometry and the feature definitions available for review.
What t-SNE emphasizes
t-SNE builds similarity relationships from high-dimensional distances and seeks a low-dimensional arrangement with corresponding local neighborhoods. Its asymmetric objective compares pairwise similarity distributions rather than preserving all Euclidean distances. The resulting coordinate axes do not usually have direct feature interpretations like temperature or age.
Perplexity controls a neighborhood-scale aspect of the similarity construction; it is not the requested number of clusters. Different values can emphasize different scales. Initialization, learning rate, iteration budget, and random seed also affect optimization. A single plot without these settings is incomplete experimental evidence.
A rotation, reflection, or translation of an embedding need not change its neighborhood story. Conversely, comparing exact coordinate positions between independent runs is usually meaningless. Compare neighborhood relationships or use a justified alignment when necessary. Apparent cluster sizes and distances between remote islands should not be treated as faithfully preserved quantities.
Use numerical diagnostics alongside pictures
Trustworthiness examines whether neighbors in the embedding were also neighbors in the original representation, penalizing intrusions according to their original ranks. Its value lies between zero and one, with larger values indicating fewer such local distortions for the chosen neighborhood size.
It checks one aspect of fidelity. A high score does not guarantee that all original neighbors remain together, that global distances are meaningful, or that the representation supports a useful clustering. Record the neighborhood size and original distance metric. Changing either changes the diagnostic question.
Sensitivity checks should vary reasonable settings rather than hunt only for the prettiest picture. Compare multiple seeds, a few neighborhood scales, and a linear reference. When annotations or known outcomes guide the choice of embedding settings, report that selection. A visually clean separation after extensive tuning is selected evidence, not an independent test.

CPU lab: a curved synthetic surface
The example generates 180 points on a Swiss-roll surface, standardizes the three coordinates, and constructs a two-dimensional PCA projection plus two t-SNE embeddings. All observations are used descriptively; there is no claim of held-out prediction. We measure trustworthiness with ten neighbors.
Observed scores are 0.8699 for PCA, 0.9884 for t-SNE seed 87, and 0.9872 for seed 88. These demonstrate improved local-neighbor fidelity on this particular synthetic representation. They do not quantify cluster validity or prove global distance preservation. The code ran on CPU with scikit-learn 1.8.0. The max_iter parameter spelling requires scikit-learn 1.5 or later; older releases used a different name.
import os
os.environ.setdefault('LOKY_MAX_CPU_COUNT', '1')
import numpy as np
from sklearn.datasets import make_swiss_roll
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
from threadpoolctl import threadpool_limits
X, position = make_swiss_roll(n_samples=180, noise=.05, random_state=87)
X = StandardScaler().fit_transform(X)
with threadpool_limits(limits=1):
P = PCA(n_components=2).fit_transform(X)
print('PCA trustworthiness k10', round(trustworthiness(X, P, n_neighbors=10), 4))
for seed in [87, 88]:
Z = TSNE(n_components=2, perplexity=20, init='random', learning_rate='auto',
max_iter=500, random_state=seed).fit_transform(X)
print('tSNE seed', seed, 'trustworthiness k10',
round(trustworthiness(X, Z, n_neighbors=10), 4))
assert np.isfinite(Z).all()
print('samples', len(position))
Distinguish a visualizer from a deployed transformer
The standard scikit-learn TSNE estimator fits an embedding of the supplied collection and does not expose an ordinary transform method for arbitrary new cases. Adding observations and refitting can move existing points. A dashboard that compares separate embeddings over time must therefore avoid interpreting coordinate movement as behavioral movement without alignment and stability checks.
Other embedding implementations may provide out-of-sample transforms, but that capability must be verified for the exact library and version. It does not automatically make the representation suitable for predictive modeling. Fit any learned transformation within the evaluation protocol and compare downstream performance against simpler alternatives.
For a high-dimensional input, preliminary reduction can lower computation and suppress some noise, but it also discards information before nonlinear embedding begins. Record that step. Large datasets may need approximation or sampling; sample composition can change the apparent neighborhoods. A small successful CPU run says little about the memory requirements of millions of observations.
Write a figure caption that constrains interpretation
A responsible caption identifies the method, input representation, sample count, important parameters, and whether the display is descriptive or evaluated for transfer. State what colors represent and whether they were used in selecting the settings. Explain that axes are embedding coordinates rather than measured quantities.
Follow promising visual patterns back to the original features. Inspect representative and boundary cases, not only cluster centers. If an island corresponds to one file format, collection device, or missing-value pattern, the plot may have exposed a data pipeline issue rather than a scientific discovery. Such findings are valuable when named accurately.
Four practice questions with worked answers
Practice 1
Does perplexity 20 request twenty clusters?
Answer: No. It controls a neighborhood-scale aspect of t-SNE’s similarities. The method does not accept perplexity as a prescribed cluster count, and visible islands require separate interpretation.
Practice 2
Two embeddings are mirror images. Must one be wrong?
Answer: No. Reflection can preserve pairwise distances and neighborhood relationships. Coordinate orientation is generally arbitrary, so compare the relationships relevant to the objective rather than the left-right direction alone.
Practice 3
Trustworthiness is 0.99 with ten neighbors. What is still unproven?
Answer: Global distance fidelity, preservation of every original neighbor, semantic cluster validity, and downstream usefulness remain unproven. The score assesses a particular local-neighborhood distortion criterion.
Practice 4
Can the demonstrated estimator directly transform a new row with a standard transform call?
Answer: No. Scikit-learn TSNE is a collection-level embedding estimator without that ordinary interface. A separate supported method or a carefully documented refitting procedure is required for new observations.
Five multiple-choice questions
Question 1
What is a t-SNE axis usually?
- A. A calibrated class probability
- B. A measured original feature in its original units
- C. An embedding coordinate without direct feature units
Correct: C. The optimized coordinates are representational, not directly measured quantities.
Question 2
What can create apparent islands?
- A. The objective, settings, and actual input structure together
- B. Only a failed optimizer
- C. Only verified ground-truth classes
Correct: A. Visual separation must be investigated rather than automatically accepted or dismissed.
Question 3
What does trustworthiness emphasize?
- A. Exact preservation of all global distances
- B. Whether embedded neighbors were plausible original neighbors
- C. Causal separation between groups
Correct: B. It is a local rank-based fidelity diagnostic.
Question 4
Why record multiple seeds?
- A. To inspect sensitivity to initialization and optimization
- B. To remove the need to state preprocessing
- C. To prove a natural cluster count by averaging coordinates
Correct: A. Repeated runs reveal one source of variability.
Question 5
What is the right next step after spotting an island?
- A. Use its screen area as population density
- B. Inspect original features and representative cases
- C. Name it as a permanent natural category immediately
Correct: B. Original-space evidence can distinguish substantive patterns from artifacts.
Common pitfalls
Do not infer causal or semantic categories from a colorful map. Avoid treating distances between islands or their plotted areas as preserved statistics. Do not compare unaligned coordinates across refits as if the coordinate system were fixed. Keep descriptive visual exploration separate from validated deployment.
Summary
Nonlinear embeddings can reveal local structure while distorting other relationships. Use settings, sensitivity checks, local fidelity diagnostics, and original-feature inspection to make a plot informative without making it overconfident.