To demonstrate the use of cosine similarity, we will generate embeddings for three sentences using the OpenAI pre-trained model and calculate their cosine similarity. This will help us understand how similar or different the sentences are based on their embeddings.
from openai import OpenAI
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
# Initialize OpenAI client
client = OpenAI()
def get_openai_embedding(text: str) -> np.ndarray:
"""Fetch a 1536-dimensional embedding for 'text' using OpenAI."""
response = client.embeddings.create(
model="text-embedding-ada-002",
input=text
)
# Convert to a NumPy array for convenience
return np.array(response.data[0].embedding)
# Three test sentences
anchor_text = "I love pizza."
similar_text = "I enjoy pizza a lot."
different_text = "Penguins are cute animals."
# OpenAI embeddings
anchor_oa = get_openai_embedding(anchor_text)
similar_oa = get_openai_embedding(similar_text)
different_oa = get_openai_embedding(different_text)
sim_oa_similar = cosine_similarity([anchor_oa], [similar_oa])[0][0]
sim_oa_different = cosine_similarity([anchor_oa], [different_oa])[0][0]
print("OpenAI embeddings (text-embedding-ada-002):")
print(f" Anchor vs. Similar: {sim_oa_similar:.4f}")
print(f" Anchor vs. Different: {sim_oa_different:.4f}")
Output:
OpenAI embeddings (text-embedding-ada-002):
Anchor vs. Similar: 0.9603
Anchor vs. Different: 0.7973
We use cosine_similarity from sklearn.metrics.pairwise to calculate the similarity scores between the embeddings. The [0][0] indexing is used because cosine_similarity returns a 2D array (a matrix) even when comparing two single vectors. The [0][0] accesses the first element of this matrix, which contains the similarity score between the two vectors.
The output shows that for the OpenAI model, the "Anchor vs. Similar" pair has a higher cosine similarity score compared to the "Anchor vs. Different" pair, indicating that the sentences "I love pizza." and "I enjoy pizza a lot." are more semantically similar than "I love pizza." and "Penguins are cute animals."