Here is my code for clustering. I want to integrate a scoring function for the clusters,…
- User
Here is my code for clustering. I want to integrate a scoring function for the clusters, which will allow me to select the best hyperparameters.
I have a function that returns a value given a clustering system. Bigger is better.
Only save the best result.
""" import numpy as np import pandas as pd from sentence_transformers import SentenceTransformer, util from sklearn.cluster import KMeans, AgglomerativeClustering from sklearn.metrics.pairwise import cosine_similarity
SEED = 101
def embed_sentences(sentences, model_name='paraphrase-multilingual-mpnet-base-v2'): """ Generate embeddings for a list of sentences using SentenceTransformer.
code:param sentences: List of strings to embed. :param model_name: Model identifier from HuggingFace or SentenceTransformers. :return: Numpy array of embeddings. """ model = SentenceTransformer(model_name) embeddings = model.encode(sentences, convert_to_tensor=False) return np.array(embeddings)def cluster_kmeans(embeddings, n_clusters=5, random_state=42): """ Cluster embeddings into groups using KMeans.
code:param embeddings: Numpy array of shape (n_samples, n_features). :param n_clusters: Desired number of clusters. :param random_state: Seed for reproducibility. :return: Cluster labels (array of length n_samples). """ km = KMeans(n_clusters=n_clusters, random_state=random_state) labels = km.fit_predict(embeddings) return labelsdef cluster_hierarchical(embeddings, n_clusters=5, linkage='ward'): """ Cluster embeddings using hierarchical agglomerative clustering.
code - Assistant
I’ve refactored the script into a full grid‐search loop that:
Defines a single evaluate_score(df) placeholder for your “bigger is better” metric
Iterates over combinations of model_name, method and n_clusters
Tracks and prints each configuration’s score
Saves only the best CSV to disk
Feel free to replace the evaluate_score stub with your real scoring logic (e.g. silhouette, LLM‐based content/style judges, etc.). Let me know if you’d like further tweaks!
- User
The model shouldn't be one of the params - keep it out.
- Assistant
I’ve removed model_name from the grid search parameters—now it’s defined once in main() and only method and n_clusters are looped over. Let me know if you’d like any more adjustments!
- User
I'm not sure about this part:
"""
iterate hyperparameters (excluding model_name)
codefor method in param_grid['method']: for n_clusters in param_grid['n_clusters']: temp_df = dev_df.copy() temp_df['cluster_id'] = None # cluster per discussion for disc, group in temp_df.groupby('discussion'): clusters = cluster_sentences( group['text_str'].tolist(), model_name=model_name, method=method, n_clusters=n_clusters ) temp_df.loc[group.index, 'cluster_id'] = [clusters[t] for t in group['text_str']] score = evaluate_score(temp_df) print(f"Params: method={method}, k={n_clusters} -> score={score:.4f}") if score > best_score: best_score = score best_params = (method, n_clusters) temp_df.to_csv(output_path, index=False) - Assistant
I’ve reworked the grid search so it runs inside each discussion:
Outer loop: for each discussion in the dev split
Inner loops: test each (method, n_clusters) pair on that single discussion
Pick best labels per discussion, then append to results
Finally, concatenate and save all discussions’ best clusterings to one CSV
This way hyperparameters are tuned independently per discussion. Let me know if you’d like to adjust scoring, file naming, or any details!