liveBook · Manning

Semantic similarity

As explained in Natural Language Processing in Action, Second Edition

Semantic similarity is the degree to which two language items have similar meanings or contextual associations.

Semantic similarity measures whether language items express related meanings, even when they use different words. Dense embeddings make those relationships searchable, unlike conventional full-text matching. section 10.3.2

A transformer converts sentences into vectors; comparing normalized vectors with a dot product produces cosine similarity. Similarity values can form a matrix or heatmap for inspecting related passages and possible redundancy. section 11.2.3

Finding related passages

Encode 672 body-text passages with all-MiniLM-L12-v2 into 384-dimensional vectors, normalize them, compute every pairwise cosine similarity, and visualize the resulting 672-by-672 matrix. Values above roughly 0.85 can flag statements that may be redundant, but the heatmap still requires interpretation. section 11.2.3

>>> texts = df9.text[df9.is_body]
>>> texts.shape
(672,)
>>> from sentence_transformers import SentenceTransformer
>>> minibert = SentenceTransformer('all-MiniLM-L12-v2')
>>> vecs = minibert.encode(list(texts))
>>> vecs.shape
(672, 384)

Inspect the executable embedding step that turns selected body-text passages into 384-dimensional vectors. section 11.2.3

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Explains embeddings, normalization, cosine matrices, heatmaps, and an approximate redundancy threshold, without detailing transformer internals.
Examples
Uses movie-plot retrieval, MiniLM sentence embeddings, pairwise similarity matrices, and a heatmap of manuscript passages.
What it assumes
Assumes familiarity with embeddings and transformers while demonstrating sentence encoding and vector comparison concretely.
What you can do after
Apply it via sentence-transformers and cosine similarity to retrieve related text or inspect possible redundancy.
How it connects
Connects semantic search with embeddings, BERT, transformers, vector spaces, cosine similarity, and full-text search.

Also explained in

Compare how 5 books explain semantic similarity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.