I want to write a script that clusters multiple statements by similarity. I will use a…
- User
I want to write a script that clusters multiple statements by similarity.
I will use a sentence transformer to produce embeddings and then use K-means or Hierarchical methods to identify clusters.
Can you implement this?
These are themodels a want to use:
sambert
from sentence_transformers import SentenceTransformer, util sentences = ["אמא הלכה לגן", "אבא הלך לגן", "ירקוני קונה לנו פיצות"]
model = SentenceTransformer('MPA/sambert') embeddings = model.encode(sentences) print(util.cos_sim(embeddings, embeddings))
from transformers import AutoTokenizer, AutoModel import torch
#Mean Pooling - Take attention mask into account for correct averaging def mean_pooling(model_output, attention_mask): token_embeddings = model_output[0] #First element of model_output contains all token embeddings input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
Sentences we want sentence embeddings for
sentences = ["אמא הלכה לגן", "אבא הלך לגן", "ירקוני קונה לנו פיצות"]
Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('MPA/sambert') model = AutoModel.from_pretrained('MPA/sambert')
Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
Compute token embeddings
with torch.no_grad(): model_output = model(**encoded_input)
Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
print("Sentence embeddings:") print(sentence_embeddings)
paraphrase-multilingual-mpnet-base-v2
paraphrase-multilingual-MiniLM-L12-v2
distiluse-base-multilingual-cased-v1
distiluse-base-multilingual-cased-v2
- Assistant
I’ve drafted a standalone Python script that:
Uses any of your listed SentenceTransformer models (e.g. MPA/sambert, paraphrase-multilingual-mpnet-base-v2, distiluse-base-multilingual-cased-v1, etc.)
Embeds the sentences via embed_sentences(...)
Offers two clustering options:
K-means via cluster_kmeans(...)
Hierarchical Agglomerative via cluster_hierarchical(...) (supports cosine or Euclidean linkage)
Wraps it all in a cluster_sentences(...) function for easy reuse
Includes an example at bottom showing how to switch models, methods, and n_clusters
Feel free to adjust default hyperparameters, add more clustering methods, or integrate this into a larger pipeline! Let me know if you’d like tweaks—e.g. visualization of clusters, automatic cluster-count estimation (e.g. silhouette), or batching for very large datasets.