News headlines in embedding space: a Hugging Face dataset meets sentence transformers

Setup: install HyperTools (run this cell first on Colab)
[ ]:
# HyperTools setup: use 1.1 or newer; retain a current local checkout.
import importlib.util
from importlib.metadata import version, PackageNotFoundError
from packaging.version import Version
from pathlib import Path
try:
    _hypertools_version = Version(version('hypertools'))
except PackageNotFoundError:
    _hypertools_version = Version('0')
if _hypertools_version < Version('1.1.0'):
    _spec = importlib.util.find_spec('hypertools')
    if _spec and _spec.origin and (Path(_spec.origin).resolve().parents[1] / '.git').exists():
        raise RuntimeError('Select a HyperTools 1.1 checkout/kernel before running this tutorial; the installer will not replace your checkout.')
    %pip install -q "hypertools[interactive]>=1.1.0"
else:
    print('Keeping HyperTools', _hypertools_version, 'in this kernel. Optional extras are loaded when requested.')

Modern language models turn text into high-dimensional embedding vectors – a perfect match for HyperTools! In this tutorial we’ll embed news headlines from a Hugging Face dataset using a small sentence-transformers model, and then use HyperTools to explore the embedding space.

Both the dataset loader and the sentence-embedding model come from HyperTools’ [text] extra, which HyperTools installs on demand the first time it is needed: hyp.load fetches the dataset from the Hugging Face Hub, and hyp.plot embeds the text. (The companion Wikipedia tutorial uses the same embedding route on a document corpus, and adds an animated spin and a density overlay; this one focuses on a labeled dataset and on what the labels reveal.)

[1]:
%matplotlib inline

import hypertools as hyp

Embedding news headlines

We’ll use a small sample (400 headlines) from the AG News dataset, which contains news headlines from four categories: World, Sports, Business, and Sci/Tech. To turn each headline into a vector we’ll use `all-MiniLM-L6-v2 <https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2>`__, a compact sentence-embedding model that maps each document onto a 384-dimensional vector.

hyp.load accepts any Hugging Face dataset id, and returns a DataFrame with the dataset’s own label names already decoded (decode_labels=True by default) – no integer codes to translate by hand. We load a 2,000-row slice of the training split and take a random sample of 400 rows with a fixed seed, so the sample mixes all four categories.

HyperTools does the embedding itself: every hyp.plot call below takes the raw headlines together with vectorizer='all-MiniLM-L6-v2', which hands the text straight to that sentence-transformers model (for an embedding vectorizer HyperTools skips the topic-model stage it applies to count-based text by default). Encoding 400 headlines takes about a second, so re-encoding per call costs less than carrying an embedding matrix around.

[2]:
# a plain (non-streaming) load decodes the dataset's own label names by default
news = hyp.load('fancyzhx/ag_news', split='train[:2000]')
sample = news.sample(400, random_state=42)   # a mixed 400-headline sample

headlines = sample['text'].tolist()
categories = sample['label'].tolist()
print(len(headlines), 'headlines across', sorted(set(categories)))
400 headlines across ['Business', 'Sci/Tech', 'Sports', 'World']

Plotting the embedding space

Passing the category labels via the hue argument colors each headline by its news category, and legend=True labels those groups (it derives the group names from hue itself, in order of first appearance). HyperTools embeds the headlines and reduces the 384-dimensional embeddings to 3D (using incremental PCA by default) before plotting.

[3]:
fig = hyp.plot(headlines, 'o', vectorizer='all-MiniLM-L6-v2',
               hue=categories, legend=True,
               title='AG News headlines (MiniLM embeddings)')
../_images/tutorials_hugging_face_embeddings_6_0.png

Even in three dimensions, headlines from the same category tend to occupy the same part of the embedding space.

Soft clustering with Gaussian mixture models

What if we didn’t know the category labels? We can discover structure directly from the embeddings. Setting cluster='GaussianMixture' fits a mixture model and colors each observation by its blend of cluster memberships – points that sit between clusters get intermediate colors, revealing the soft category boundaries.

We pass n_clusters=4 to match the four known AG News categories; for a mixture model HyperTools forwards that count as n_components. The mixture is fit to the 3-D reduced coordinates that get drawn, not to the raw 384-dimensional vectors, and each point’s color reflects its cluster membership.

[4]:
fig = hyp.plot(headlines, 'o', vectorizer='all-MiniLM-L6-v2',
               cluster='GaussianMixture', n_clusters=4,
               title='Gaussian mixture soft clustering')
../_images/tutorials_hugging_face_embeddings_8_0.png

Nonlinear embeddings with UMAP

PCA is linear; nonlinear methods like UMAP can often do a better job of untangling text embeddings. Just pass reduce='UMAP':

ndims=2 asks for a flat 2-D projection instead of the default 3. UMAP is stochastic and is left unseeded here, so the layout differs from run to run; pass reduce={'model': 'UMAP', 'kwargs': {'random_state': 42}} to fix it in place.

[5]:
fig = hyp.plot(headlines, 'o', vectorizer='all-MiniLM-L6-v2',
               reduce='UMAP', ndims=2,
               hue=categories, legend=True,
               title='UMAP embedding of AG News headlines')
../_images/tutorials_hugging_face_embeddings_10_0.png

Next steps

Try swapping in a different Hugging Face dataset or embedding model, aligning embeddings from two models with hyp.align, or exploring interactive 3D plots with backend='plotly'. For an animated tour of an embedding map (animate='spin') and a volumetric density overlay, see the Wikipedia tutorial.