pythonbeginner

Sentence Transformers Local Embeddings

Generate high-quality text embeddings locally using Sentence Transformers without API calls.

python
from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer('all-MiniLM-L6-v2')

sentences = [
    'Machine learning powers modern AI.',
    'Deep learning is a subset of ML.',
    'Python is a popular programming language.',
    'The weather is sunny today.',
]

embeddings = model.encode(sentences, normalize_embeddings=True)

# Cosine similarity (dot product of normalised vectors)
sim_matrix = embeddings @ embeddings.T

for i, s in enumerate(sentences):
    most_similar = np.argsort(sim_matrix[i])[::-1][1]
    print(f'{s!r} -> most similar: {sentences[most_similar]!r} ({sim_matrix[i][most_similar]:.3f})')

Use Cases

  • semantic search
  • local embeddings
  • text similarity

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.