Backend & AI Engineer: Visualizing Social Sentiment with Sentence Transformers & PCA

Processing thousands of social media comments on movie trailers or announcements is exhausting. Simple sentiment classifiers (positive vs. negative) miss the rich, semantic themes of what the audience is actually saying. For example, knowing that 60% of comments are negative doesn't tell you *why*—are they complaining about the CGI, the script changes, or the casting?

To solve this, we can design an advanced Natural Language Processing (NLP) pipeline that leverages HuggingFace Sentence Transformers to vectorize comments into high-dimensional space, and then runs Principal Component Analysis (PCA) to project these vectors onto a 2D plot, revealing distinct semantic clusters.


The Architecture: Text to Coordinates

Our pipeline follows three distinct mathematical steps:

  1. Embedding Ingestion: We load raw text comments and pass them through a pre-trained transformer model (like all-mpnet-base-v2 or all-minilm-l6-v2) to generate 768-dimensional dense vectors representing the semantic meaning of each comment.
  2. Dimensionality Reduction: High-dimensional spaces are impossible to visualize. We use PCA to project the 768 dimensions down to 2 principal components (X and Y coordinates) that capture the maximum variance of the dataset.
  3. Visual Mapping: We plot the coordinates, color-coding key clusters so analysts can visually identify audience themes.

Step 1: Vectorizing Comments with Sentence Transformers

First, we write a Python script that loads our comments and uses the sentence-transformers library to compute embeddings in-memory:

from sentence_transformers import SentenceTransformer
import pandas as pd
import json

def generate_comment_embeddings(comments_csv_path: str):
    # Load comments
    df = pd.read_csv(comments_csv_path)
    comments = df['comment_text'].dropna().tolist()
    
    # Load high-performance transformer model
    model = SentenceTransformer('all-mpnet-base-v2')
    
    # Generate 768-dimensional dense vectors
    print("Generating vector embeddings...")
    embeddings = model.encode(comments, show_progress_bar=True)
    
    return comments, embeddings

Step 2: Dimensionality Reduction using PCA

Next, we use scikit-learn to perform Principal Component Analysis on our high-dimensional vectors, mapping them down to a 2D coordinate system:

from sklearn.decomposition import PCA
import numpy as np

def reduce_dimensions(embeddings, n_components=2):
    """
    Reduces high-dimensional embeddings to 2D coordinates using PCA.
    """
    pca = PCA(n_components=n_components)
    coordinates = pca.fit_transform(embeddings)
    
    # Log explained variance ratio to monitor compression quality
    explained_variance = np.sum(pca.explained_variance_ratio_)
    print(f"Explained Variance Ratio (2D): {explained_variance * 100:.2f}%")
    
    return coordinates

Step 3: Plotting Semantic Audience Clusters

Once coordinates are mapped, we plot the results. By running K-Means clustering alongside PCA, we can group similar comments and display them visually, allowing analysts to hover and instantly read the clustered themes (e.g. "complaints about lighting" vs "excitement for the trailer theme"):

import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

def plot_clusters(comments, coordinates, n_clusters=4):
    # Segment coordinates into distinct clusters
    kmeans = KMeans(n_clusters=n_clusters, random_state=42)
    labels = kmeans.fit_predict(coordinates)
    
    # Create the scatter plot
    plt.figure(figsize=(10, 8))
    scatter = plt.scatter(
        coordinates[:, 0], 
        coordinates[:, 1], 
        c=labels, 
        cmap='viridis', 
        alpha=0.6, 
        edgecolors='w'
    )
    
    plt.title("Social Sentiment Clustering (PCA)", fontsize=14)
    plt.xlabel("Component 1", fontsize=12)
    plt.ylabel("Component 2", fontsize=12)
    plt.colorbar(scatter, label="Cluster ID")
    plt.grid(True, linestyle='--', alpha=0.5)
    plt.savefig("audience_sentiment_clusters.png", dpi=300)
    plt.close()

Performance Optimization Takeaways

  1. Select the Right Model: Use all-minilm-l6-v2 for light, high-speed, serverless execution, and reserve the heavier all-mpnet-base-v2 for complex, high-accuracy analysis.
  2. Batch Ingestion: Always feed comments into the transformer in batches to utilize GPU acceleration efficiently.
  3. Explained Variance Audit: Monitor your explained variance ratios. If 2D PCA captures less than 40% of the variance, consider using t-SNE or UMAP for better non-linear cluster separation.

By mapping raw comments to semantic vector spaces and reducing them to clean visual clusters, you turn overwhelming feedback streams into highly structured, visual audience research dashboards.

Interactive 2D/3D Embedding Projections with Sentence-Transformers, PCA & UMAP

Cluster hundreds of thousands of customer feedback posts and social posts into actionable semantic topics using normalized dense embeddings and dimensionality reduction.

import numpy as np
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sentence_transformers import SentenceTransformer

def project_comment_clusters(comments: list[str], n_clusters: int = 5) -> list[dict]:
    model = SentenceTransformer("all-MiniLM-L6-v2")
    embeddings = model.encode(comments, normalize_embeddings=True, batch_size=64)

    coords_2d = PCA(n_components=2, random_state=42).fit_transform(embeddings)
    labels = KMeans(n_clusters=n_clusters, n_init="auto", random_state=42).fit_predict(embeddings)

    return [
        {
            "text": text,
            "cluster_id": int(cluster),
            "x": float(np.round(pt[0], 4)),
            "y": float(np.round(pt[1], 4)),
        }
        for text, cluster, pt in zip(comments, labels, coords_2d)
    ]

Explore Core Backend & AI Engineering Guides

Need NLP clustering or vector analytics dashboards? Book a 1-Day Programming Sprint ($100 USD via Credit/Debit Card or Rp 1.000.000 via QRIS / Bank Virtual Account).


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs