Debug: """ Discussion 202312DeclarationIndependence4: method=kmeans, k=4 -> score=0.5800…
- User
Debug:
""" Discussion 2023_12_Declaration_Independence_4: method=kmeans, k=4 -> score=0.5800 Discussion 2023_12_Declaration_Independence_4: method=kmeans, k=4 -> score=0.5700 Discussion 2023_12_Declaration_Independence_4: method=kmeans, k=6 -> score=0.5100 Discussion 2023_12_Declaration_Independence_4: method=kmeans, k=6 -> score=0.5200 Traceback (most recent call last): File "/XXX.10/site-packages/sklearn/utils/_param_validation.py", line 218, in wrapper return func(*args, **kwargs) File "/XXX.10/site-packages/sklearn/metrics/_classification.py", line 359, in accuracy_score y_type, y_true, y_pred = _check_targets(y_true, y_pred) File "/XXX.10/site-packages/sklearn/metrics/_classification.py", line 106, in _check_targets raise ValueError( ValueError: Classification metrics can't handle a mix of multiclass and unknown targets """
""" import pandas as pd
from sbert_based_clustering import * from leave_one_out_eval import *
def evaluate_score(df: pd.DataFrame) -> float: """ Evaluate clustering quality based on leave-one-out evaluation. :param df: DataFrame with 'text' and 'cluster_id' columns. :return: Average of content and style accuracy. """ # create a list of pairs (text, cluster_id) data = [] for _, row in df.iterrows(): data.append((row['text'], row['cluster_id']))
coderesults = leave_one_out_evaluate(data, model=MODEL_NAME) return (results['accuracy_content'] + results['accuracy_style']) / 2def grid_search_per_discussion(model_name: str, data_path: str, output_path: str, param_grid: dict, split=None): all_statements = pd.read_csv(data_path, index_col=0)
code - Assistant
- User
Thats wrong:
def cluster_sentences(sentences, embeddings=None, method='kmeans', n_clusters=5, **kwargs) -> dict[str, int]: """ Embed and cluster sentences by similarity.
code:param embeddings: :param sentences: List of sentences (strings). :param model_name: SentenceTransformer model to use. :param method: 'kmeans' or 'hierarchical'. :param n_clusters: Number of clusters. :param kwargs: Additional arguments passed to the clustering function. :return: Dictionary mapping sentence to cluster label. """ if method == 'kmeans': labels = cluster_kmeans(embeddings, n_clusters=n_clusters, **kwargs) elif method == 'hierarchical': labels = cluster_hierarchical(embeddings, n_clusters=n_clusters, **kwargs) else: raise ValueError(f"Unsupported clustering method: {method}") # TODO - change this to that the keys are the labels and the values are the list of clustered sentences? return dict(zip(sentences, labels)) - Assistant
I’ve refactored cluster_sentences so it now returns a simple list of integer labels—aligned positionally with your input sentences—instead of a dict keyed by sentence text. This avoids any mismatches or missing keys when you re-attach the labels in grid_search_per_discussion. Let me know if you’d like to integrate this into your full pipeline or need further tweaks!
- User
I don't want to change cluster_sentences. Instead, debug the original
- Assistant
The reason you’re still getting NaN (and hence “unknown targets”) is that your original cluster_sentences returns a dict keyed by sentence‐string: pythonCopyEditreturn dict(zip(sentences, labels))
If your sentences list has any duplicates, the latter occurrences overwrite earlier ones in that dict, and then when you do pythonCopyEdittemp_df['cluster_id'] = group['text'].map(labels_dict)
pandas will happily look up each text in your dict—but for any sentence that appeared twice, only the last label survives, and the other copy(s) become NaN.
Two ways to fix it, without touching cluster_sentences
Build an explicit list of labels from your dict Immediately after you call your clustering, do: pythonCopyEditlabels_dict = cluster_sentences(texts, embeddings=embeddings, method=method, n_clusters=n_clusters, **kwargs) labels = [labels_dict[text] for text in texts] temp_df = group.reset_index(drop=True).copy() temp_df['cluster_id'] = labels