Generative AI · Intermediate level

Intermediate level · Module 3: Tokens, Embeddings and Semantic Search · Lesson 2 of 3

Embeddings and Cosine Similarity

Learners create sentence embeddings with Sentence Transformers and compare meanings with cosine similarity.

In this lesson you will

  • Create sentence embeddings
  • Compute and interpret cosine similarity

Key concepts

embedding vectorSentence Transformerscosine similaritynormalisationsemantic similarity

The lesson

An embedding model maps text to a vector so that texts with similar meanings get similar vectors. all-MiniLM-L6-v2 (Apache-2.0) is a small Sentence Transformers model that runs on a CPU: model.encode(sentences) returns vectors.

Cosine similarity measures the angle between two vectors: close to 1 means very similar meaning, close to 0 unrelated. 'When must I pay the fees?' and 'Second-term fees are due by 14 March' score high even though they share few words.

Embedding quality depends on language. Many small models are trained mostly on English, so test them on any other language before relying on them.

Step by step

  1. Encode ten sentences with all-MiniLM-L6-v2.
  2. Compute the cosine similarity matrix.
  3. Find the most similar pairs.
  4. Test two sentences in another language and note the quality.

Practice activity

Build a similarity matrix for project sentences and interpret it.

Expected result: A correct matrix with sensible top pairs and a note on language limits.

Check your understanding

  1. What does a cosine similarity near 1 mean?

    Show answer

    The texts have very similar meanings.

  2. Why test embeddings on local-language text?

    Show answer

    Many models are trained mostly on English and may work poorly on other languages.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.