How does t-SNE visualize high-dimensional data?

Authors
How does t-SNE visualize high-dimensional data?

t-SNE visualizes high-dimensional data by placing every item as a dot on a flat 2D map, so that similar items sit close together and different items sit far apart.

In this blog, we will learn about how t-SNE visualizes high-dimensional data. We will also see what high-dimensional data is, why we cannot see it directly, how t-SNE builds its map step by step, what perplexity does, how the t-distribution fixes the crowding problem, and when to use t-SNE.

We will cover the following:

  • What is high-dimensional data?
  • The problem: we cannot see beyond 3 dimensions
  • What is dimensionality reduction?
  • What is t-SNE?
  • How t-SNE works step by step
  • What is perplexity?
  • The crowding problem and how t-SNE fixes it
  • A simple example
  • When to use t-SNE

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

What is high-dimensional data?

A dimension is one number that describes something.

Let's say we are describing a person. We can note down the person's height. That is 1 number, so that is 1 dimension.

Now, we also note down the person's weight. That is a second number, so now we have 2 dimensions.

Now, we also add age, income, and number of steps walked today. Now we have 5 numbers for that person. So, this person is described by 5 dimensions.

So, high-dimensional data is data where each item is described by many numbers.

In the real world, data often has hundreds or thousands of dimensions. A single photo can be described by thousands of numbers, one for each pixel. A single customer can be described by hundreds of numbers.

We have a detailed blog on What are Embeddings? that explains how text and images are turned into such long lists of numbers.

The problem: we cannot see beyond 3 dimensions

We can only see up to 3 dimensions. We can draw on paper in 2 dimensions. We can imagine a room in 3 dimensions. But we cannot see or imagine 100 dimensions.

So, if each customer is described by 100 numbers, how do we look at all our customers together and spot patterns? How do we see which customers are similar to each other?

Let's picture the problem as below:

   Data with 100 numbers per item        What our eyes can handle
   +-------------------------------+      +----------------------+
   | item 1: 0.2 0.9 ... (100 num) |      |                      |
   | item 2: 0.7 0.1 ... (100 num) |  ->  |   only 2 or 3        |
   | item 3: 0.4 0.5 ... (100 num) |      |   dimensions         |
   | ...                           |      |                      |
   +-------------------------------+      +----------------------+

Here, we can see that on the left side each item has 100 numbers. On the right side, our eyes can only handle 2 or 3 numbers at a time.

So, we need a way to squeeze those 100 numbers down to just 2 numbers, so that we can plot every item on a flat sheet of paper and see it.

What is dimensionality reduction?

Dimensionality reduction is the process of taking data that has many numbers per item and turning it into data with only a few numbers per item, while keeping the important relationships.

After reduction, items that were similar in the original high-dimensional data must still be close together in the new 2-dimensional picture. Items that were different must still be far apart.

If we keep that relationship, we can plot the data and trust what we see.

What is t-SNE?

t-SNE is a popular method for dimensionality reduction that is built to create easy-to-read 2-dimensional pictures of high-dimensional data.

The full name is t-Distributed Stochastic Neighbor Embedding. t-SNE places every item as a dot on a flat map, such that similar items sit close together and different items sit far apart.

t-SNE is a nonlinear method. Let's understand what that means.

A linear method is like looking at a shadow. It flattens the data in a simple, straight way. Sometimes a straight flattening loses important shape.

We have a detailed blog on Principal Component Analysis (PCA) that explains this popular linear method step by step.

A nonlinear method like t-SNE can bend and stretch as needed to keep neighbors together. This is why t-SNE is so good at showing groups and clusters that a simple linear method would miss.

So, t-SNE cares most about one thing. It tries to keep neighbors as neighbors.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

How t-SNE works step by step

Let's understand how t-SNE works, one step at a time.

Step 1: Measure similarity in the original high-dimensional space.

For every pair of items, t-SNE asks a simple question. How similar are these two items? Items that are close together in the original data get a high similarity. Items that are far apart get a low similarity.

t-SNE turns these similarities into probabilities. We can read it like this. If we picked one item, what is the chance that another item is its neighbor? Close items get a high chance. Far items get a low chance.

Step 2: Place all items randomly on a 2-dimensional map.

At the start, t-SNE scatters every item as a dot on a flat sheet, usually at random. This map is a mess right now. Nothing is in the right place yet.

Step 3: Measure similarity on the 2-dimensional map too.

Now t-SNE measures similarities again, but this time using the positions of the dots on the flat map.

Step 4: Compare the two sets of similarities and fix the map.

t-SNE compares the original similarities from Step 1 with the map similarities from Step 3. Wherever they do not match, t-SNE moves the dots. If two items should be close but their dots are far, it pulls them closer. If two items should be far but their dots are close, it pushes them apart.

Step 5: Repeat many times.

t-SNE repeats this pull-and-push again and again. Slowly, the map settles. Similar items end up in tight groups. Different items end up far away.

Let's picture the pull-and-push as below:

   Should be neighbors, but far apart

   (A)                      (B)
           -> pull <-
               ↓
            (A) (B)

   Should be far apart, but close together

            (C) (D)
           <- push ->
               ↓
   (C)                      (D)

Here, we can see that in the first case, dots A and B belong together, so t-SNE pulls them closer. In the second case, dots C and D do not belong together, so t-SNE pushes them apart. After many rounds of this, every dot lands in a sensible spot.

This is how t-SNE turns a random mess of dots into a clean map with clear groups.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

What is perplexity?

Now, there is one important setting we must understand. It is called perplexity.

Perplexity is a number we choose that tells t-SNE roughly how many close neighbors each item should pay attention to.

Perplexity controls the size of the neighborhood. It decides whether each item looks at a small circle of nearby items, or a wider crowd.

If perplexity is small, like 5, each item cares about roughly its 5 closest neighbors. This shows very fine, local detail, but it can break the big picture into too many tiny pieces.

If perplexity is large, like 50, each item cares about a wider group. This shows the bigger structure, but it can blur small details.

Let's compare the effect as below:

   Small perplexity (5)              Large perplexity (50)
   +----------------------+          +----------------------+
   |  ..   ..   ..   ..   |          |   .....     .....    |
   |  ..   ..   ..   ..   |          |   .....     .....    |
   |  many tiny groups    |          |   fewer big groups   |
   +----------------------+          +----------------------+

Here, we can see that a small perplexity breaks the data into many tiny groups, focusing on close neighbors. A large perplexity forms fewer, bigger blobs, focusing on the overall shape.

A common range is between 5 and 50. We try a few values and pick the one that gives the clearest picture, based on our use case.

The crowding problem and how t-SNE fixes it

Now, let's understand the crowding problem.

When we squeeze data from a high-dimensional space into just 2 dimensions, there is not enough room.

In a high-dimensional space, one item can have many neighbors, all sitting at a comfortable distance around it. But on a flat 2-dimensional sheet, there is not enough space to place all those neighbors around it without them piling on top of each other.

So, everything gets crowded into the center and squished together. This is the crowding problem.

Let's picture it as below:

   High-dimensional space            Naive squeeze into 2D
   (lots of room around A)           (everyone crowds onto A)

         B   C
          \ /                               BC
       D - A - E                            DAE
          / \                               FG
         F   G

Here, we can see that in the original space, item A has plenty of room for all its neighbors. But when we naively squeeze it into 2 dimensions, all those neighbors crush together near the center. The picture becomes one blob.

So, how does t-SNE fix this?

t-SNE uses two different rulers to measure similarity. It uses one ruler for the original high-dimensional space, and a different, more forgiving ruler for the 2-dimensional map.

For the 2-dimensional map, t-SNE uses a special ruler called the t-distribution. This is the letter t in the name t-SNE.

The t-distribution has heavy tails, which means it still gives a reasonable similarity to items that are far apart. So, items that are only somewhat different can be placed much farther apart on the map, and their map similarity still matches the original similarity.

This extra room solves the crowding. Items that are not close neighbors get pushed farther away, so groups spread out instead of piling into one blob.

Let's picture the fix as below:

   Without the t-distribution        With the t-distribution
   (crowded blob)                    (groups spread out)

        BCDEFG                          B  C
          A                ->         D  A  E
                                        F  G

Here, we can see that without the t-distribution, everything squishes into a crowded blob. With the t-distribution, the extra room in the tails lets the groups spread out and become clearly visible.

This is why t-SNE produces clean and readable maps.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

A simple example

Let's see t-SNE in action with a short piece of code, just for the sake of understanding.

We can write the code as below:

from sklearn.manifold import TSNE
from sklearn.datasets import load_digits

# load images of handwritten digits, each has 64 numbers
digits = load_digits()
data = digits.data      # high-dimensional data (64 dimensions)
labels = digits.target  # the actual digit 0 to 9

# reduce 64 dimensions down to 2 dimensions
model = TSNE(n_components=2, perplexity=30, random_state=42)
points_2d = model.fit_transform(data)

print(points_2d.shape)  # (1797, 2)

Here, we have done the following:

We load a set of small images of handwritten digits. Each image is described by 64 numbers, so this is 64-dimensional data.

We create a TSNE model. We set n_components=2 because we want a 2-dimensional map. We set perplexity=30, which is the neighborhood size we discussed earlier.

We call fit_transform, and t-SNE gives us back just 2 numbers for each image. The output shape (1797, 2) means we have 1797 images, and each now has only 2 numbers instead of 64.

Now we can plot these 2 numbers as dots on a flat sheet. When we do, most of the images of the digit 0 form one group, most of the images of the digit 1 form another group, and so on. We see ten groups on the map, one for each digit, with only a few dots in the wrong group.

We took data with 64 dimensions and made a picture we can see and understand.

To master Data Analysis and Visualization along with the Machine Learning Fundamentals in depth, check out our AI and Machine Learning Program at Outcome School.

When to use t-SNE

Now we know what t-SNE does, let's understand when to use it.

We use t-SNE when we want to explore data and see if it forms natural groups. It is useful for making a picture and spotting clusters.

But there are a few points we must keep in mind.

t-SNE is mainly a tool for looking, not for measuring exact distances. On a t-SNE map, we can trust which dots are grouped together. But we must not read too much into the size of the gaps between groups, or the exact distances. Those can change with different settings.

Also, t-SNE can be slow on very large datasets, and it can give a slightly different picture on different runs, because of the randomness in where the dots start.

Now we must have understood how t-SNE visualizes high-dimensional data.

Frequently Asked Questions

What does the t in t-SNE stand for?

The t in t-SNE stands for the t-distribution. t-SNE uses it to measure similarity on the 2-dimensional map. The t-distribution has heavy tails, so it still gives a reasonable similarity to items that are far apart, which gives the map extra room and fixes the crowding problem.

Can we trust the distances between groups on a t-SNE map?

No. We can trust which dots are grouped together on a t-SNE map, but we must not read too much into the size of the gaps between groups or the exact distances. Those can change with different settings, because t-SNE is mainly a tool for looking, not for measuring exact distances.

Why does t-SNE give a different picture on different runs?

t-SNE starts by scattering every item as a dot on the map, usually at random. Because of this randomness in where the dots start, it can give a slightly different picture on different runs, even on the same data.

What perplexity value should we use for t-SNE?

A common range for perplexity is between 5 and 50. A small value shows fine, local detail but can break the data into many tiny groups, while a large value shows the bigger structure but can blur small details. We try a few values and pick the one that gives the clearest picture.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.