🤖 AI/ML

t-SNE

t-Distributed Stochastic Neighbor Embedding

A high-dimensional data visualization technique. Effectively visualizes data clusters through nonlinear dimensionality reduction.

📖 Detailed Explanation

t-SNE (t-Distributed Stochastic Neighbor Embedding) is a nonlinear dimensionality reduction technique for visualizing high-dimensional data in 2D or 3D. It preserves the local structure of the original data (the relationships between nearby points) as much as possible in the low-dimensional space, allowing you to intuitively grasp the cluster structure of the data.

t-SNE was proposed in 2008 by Laurens van der Maaten and Geoffrey Hinton as an improvement on the existing SNE algorithm. The core idea is to model similarities in the high-dimensional space with a Gaussian distribution and similarities in the low-dimensional space with a t-distribution (Student's t-distribution). The heavy tails of the t-distribution solve the "crowding problem," producing sharper clusters.

The key hyperparameter of t-SNE is perplexity. It is related to the effective number of neighbors each point considers, and values between 5 and 50 are typically used. A small perplexity captures local structure better, while a large perplexity captures global structure better. In addition, learning_rate and n_iter (number of iterations) also affect the results, so appropriate tuning is necessary.

In practice, t-SNE is widely used for visualizing word embeddings, analyzing image features, and validating clustering results. However, because its computational cost is high, UMAP may be more suitable for large-scale datasets. Also, the cluster sizes and distances in t-SNE results must be interpreted with caution. It is a tool for visualization, not a clustering algorithm itself.

💻 Code Example

# t-SNE 완전 가이드: 시각화, 최적화, 비교
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.datasets import load_digits, fetch_20newsgroups
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import time

# 1. 기본 t-SNE 시각화
def basic_tsne_visualization():
    """MNIST 숫자 데이터 t-SNE 시각화"""
    # 데이터 로드
    digits = load_digits()
    X, y = digits.data, digits.target

    print(f"데이터 형태: {X.shape}")  # (1797, 64)

    # t-SNE 적용
    tsne = TSNE(
        n_components=2,      # 2D로 축소
        perplexity=30,       # 유효 이웃 수
        learning_rate=200,   # 학습률
        n_iter=1000,         # 반복 횟수
        random_state=42
    )

    start_time = time.time()
    X_tsne = tsne.fit_transform(X)
    elapsed = time.time() - start_time
    print(f"t-SNE 시간: {elapsed:.2f}초")

    # 시각화
    plt.figure(figsize=(12, 10))
    scatter = plt.scatter(
        X_tsne[:, 0], X_tsne[:, 1],
        c=y,
        cmap='tab10',
        alpha=0.7,
        s=20
    )
    plt.colorbar(scatter, label='숫자 클래스')
    plt.title('MNIST Digits t-SNE Visualization')
    plt.xlabel('t-SNE 1')
    plt.ylabel('t-SNE 2')
    plt.savefig('tsne_mnist.png', dpi=150)
    plt.close()

    return X_tsne

# 2. Perplexity 값에 따른 결과 비교
def compare_perplexity():
    """다양한 perplexity로 t-SNE 결과 비교"""
    digits = load_digits()
    X, y = digits.data, digits.target

    perplexities = [5, 15, 30, 50, 100]

    fig, axes = plt.subplots(1, 5, figsize=(25, 5))

    for ax, perp in zip(axes, perplexities):
        tsne = TSNE(
            n_components=2,
            perplexity=perp,
            random_state=42
        )
        X_tsne = tsne.fit_transform(X)

        ax.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap='tab10', s=10, alpha=0.7)
        ax.set_title(f'Perplexity = {perp}')
        ax.set_xticks([])
        ax.set_yticks([])

    plt.tight_layout()
    plt.savefig('tsne_perplexity_comparison.png', dpi=150)
    plt.close()

# 3. 대용량 데이터: PCA 전처리 + t-SNE
def optimized_tsne_pipeline():
    """대용량 데이터를 위한 PCA + t-SNE 파이프라인"""
    # 가상의 고차원 데이터 (10000 샘플, 784 차원)
    np.random.seed(42)
    n_samples = 10000
    n_features = 784

    # 3개 클러스터 생성
    X1 = np.random.randn(n_samples // 3, n_features) + np.array([5] * n_features)
    X2 = np.random.randn(n_samples // 3, n_features) + np.array([-5] * n_features)
    X3 = np.random.randn(n_samples // 3, n_features)
    X = np.vstack([X1, X2, X3])
    y = np.array([0] * (n_samples // 3) + [1] * (n_samples // 3) + [2] * (n_samples // 3))

    print(f"원본 데이터: {X.shape}")

    # Step 1: 스케일링
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)

    # Step 2: PCA로 먼저 차원 축소 (t-SNE 속도 향상)
    pca = PCA(n_components=50)
    X_pca = pca.fit_transform(X_scaled)
    print(f"PCA 후: {X_pca.shape}, 설명 분산: {pca.explained_variance_ratio_.sum():.2%}")

    # Step 3: t-SNE 적용
    start = time.time()
    tsne = TSNE(
        n_components=2,
        perplexity=30,
        n_iter=500,
        init='pca',  # PCA 초기화 (더 안정적)
        random_state=42
    )
    X_tsne = tsne.fit_transform(X_pca)
    print(f"t-SNE 시간: {time.time() - start:.2f}초")

    # 시각화
    plt.figure(figsize=(10, 8))
    plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap='tab10', s=5, alpha=0.5)
    plt.title('PCA + t-SNE Pipeline')
    plt.savefig('tsne_optimized.png', dpi=150)
    plt.close()

    return X_tsne

# 4. t-SNE vs UMAP 비교
def tsne_vs_umap():
    """t-SNE와 UMAP 성능 및 결과 비교"""
    try:
        import umap

        digits = load_digits()
        X, y = digits.data, digits.target

        # t-SNE
        start = time.time()
        tsne = TSNE(n_components=2, random_state=42)
        X_tsne = tsne.fit_transform(X)
        tsne_time = time.time() - start

        # UMAP
        start = time.time()
        umap_model = umap.UMAP(n_components=2, random_state=42)
        X_umap = umap_model.fit_transform(X)
        umap_time = time.time() - start

        print(f"t-SNE 시간: {tsne_time:.2f}초")
        print(f"UMAP 시간: {umap_time:.2f}초")
        print(f"UMAP이 {tsne_time/umap_time:.1f}배 빠름")

        # 시각화
        fig, axes = plt.subplots(1, 2, figsize=(16, 6))

        axes[0].scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap='tab10', s=10, alpha=0.7)
        axes[0].set_title(f't-SNE ({tsne_time:.1f}s)')

        axes[1].scatter(X_umap[:, 0], X_umap[:, 1], c=y, cmap='tab10', s=10, alpha=0.7)
        axes[1].set_title(f'UMAP ({umap_time:.1f}s)')

        plt.tight_layout()
        plt.savefig('tsne_vs_umap.png', dpi=150)
        plt.close()

    except ImportError:
        print("UMAP이 설치되지 않았습니다: pip install umap-learn")

# 5. 워드 임베딩 시각화
def visualize_word_embeddings():
    """워드 임베딩 t-SNE 시각화"""
    try:
        from gensim.models import KeyedVectors

        # 사전 학습된 Word2Vec (예시용 작은 모델)
        # 실제로는 'word2vec-google-news-300' 등 사용
        words = ['king', 'queen', 'man', 'woman', 'dog', 'cat', 'car', 'bike']

        # 가상의 임베딩 생성 (실제로는 Word2Vec에서 로드)
        np.random.seed(42)
        embeddings = np.random.randn(len(words), 100)

        # t-SNE 적용
        tsne = TSNE(n_components=2, perplexity=min(5, len(words)-1), random_state=42)
        embeddings_2d = tsne.fit_transform(embeddings)

        # 시각화
        plt.figure(figsize=(10, 8))
        for i, word in enumerate(words):
            plt.scatter(embeddings_2d[i, 0], embeddings_2d[i, 1], s=100)
            plt.annotate(word, (embeddings_2d[i, 0] + 0.1, embeddings_2d[i, 1]))
        plt.title('Word Embeddings t-SNE')
        plt.savefig('tsne_word_embeddings.png', dpi=150)
        plt.close()

    except ImportError:
        print("gensim이 설치되지 않았습니다: pip install gensim")

# 6. 인터랙티브 시각화
def interactive_tsne():
    """Plotly를 사용한 인터랙티브 t-SNE"""
    try:
        import plotly.express as px
        import pandas as pd

        digits = load_digits()
        X, y = digits.data, digits.target

        tsne = TSNE(n_components=2, random_state=42)
        X_tsne = tsne.fit_transform(X)

        df = pd.DataFrame({
            't-SNE 1': X_tsne[:, 0],
            't-SNE 2': X_tsne[:, 1],
            'digit': y.astype(str)
        })

        fig = px.scatter(
            df, x='t-SNE 1', y='t-SNE 2',
            color='digit',
            title='Interactive t-SNE Visualization',
            hover_data={'digit': True}
        )
        fig.write_html('tsne_interactive.html')
        print("인터랙티브 시각화: tsne_interactive.html 저장됨")

    except ImportError:
        print("plotly가 설치되지 않았습니다: pip install plotly")

# 실행
if __name__ == "__main__":
    print("=== 기본 t-SNE ===")
    basic_tsne_visualization()

    print("\n=== Perplexity 비교 ===")
    compare_perplexity()

    print("\n=== 최적화 파이프라인 ===")
    optimized_tsne_pipeline()

    print("\n=== t-SNE vs UMAP ===")
    tsne_vs_umap()

🗣️ Say It Like This in Practice

💬 In a Meeting

"I want to check whether the embedding model has been trained properly." - "How about visualizing it with t-SNE? If data of the same class clusters well together, the embedding has learned a meaningful representation. Start with a perplexity of around 30, and if the clusters don't show up clearly, adjust the value. But be careful when interpreting cluster sizes or distances."

💬 In an Interview

"Please explain the difference between t-SNE and PCA." - "PCA maximizes global variance through a linear transformation, whereas t-SNE is nonlinear and preserves local structure. PCA is fast and invertible but cannot capture complex structures, while t-SNE separates clusters well but is slow and cannot transform new data. For large datasets, it is usually efficient to first reduce to around 50 dimensions with PCA and then apply t-SNE."

💬 In a Technical Discussion

"t-SNE is slow—is there an alternative?" - "I recommend UMAP. It is more than 10 times faster than t-SNE and also preserves global structure better. It can also add new data to an existing embedding, so it can be used in production too. However, for the initial analysis, one option is to try several perplexity values with t-SNE and then produce the final visualization with UMAP."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Over-interpreting Cluster Size/Distance

In t-SNE results, you should not interpret a larger cluster size as meaning that the class is more dispersed, or interpret two clusters being close together as meaning they are actually similar. t-SNE preserves only local structure.

❌
Drawing Conclusions from a Single Run

t-SNE is a stochastic algorithm, so results vary depending on random_state. It is also sensitive to perplexity and learning_rate, so you should experiment with several settings and look for consistent patterns.

✅
The Right Approach

For high-dimensional data, first reduce to 50–100 dimensions with PCA and then apply t-SNE. Try several perplexity values (5, 30, 50), and use the results only as a supplementary analysis tool. For clustering, it is better to use K-means or DBSCAN separately.

🔗 Related Terms

📚 Learn More