Short answer: Yes — that CLI is the intended way to run it when you want sambert embeddings + hdbscan clustering, but the script contains a few bugs/typos and missing safety checks that will cause it to crash unless fixed. Below I list the problems I found and a compact patch you can drop into the file to make the script robust for the command you showed.
Problems that will cause immediate errors
from openai import OpenAI is commented out but OpenAI() is used in main_cluster_mentions / main_embeddings — only matters if you ever run with --embedding_method openai. (Not relevant for sambert.)
Typos/NameErrors:
UMAP_MIN_DIST is used in agglomerative_clusterer and hdbscan_clusterer but the constant is UMAP_MIN_DISTS (plural). -> NameError.
UMAP creation when some params are None:
agglomerative_clusterer and hdbscan_clusterer always call UMAP(...) even when neighbors, min_dist or n_components are None. UMAP expects numeric values and will error. (You handled this correctly in kmeans_clusterer but not in the other two.)
Missing output directory creation:
df.to_csv(f"{clusters_dir}/{out_name}") will fail if clusters_dir doesn't exist.
Minor: print_cluster_stats type hint expects KMeans but you pass other clusterers — not a runtime error, but misleading.
Practical/ops: SentenceTransformer("MPA/sambert") requires the model to be available (internet or cached). Encoding many sentences can be memory-intensive — consider batching / device parameter.
Minimal patch (drop into your script; I mark changed sections)
Replace the contents of the three clusterer functions and add directory creation checks. You can copy-paste this replacement into your file:
pythonCopy code# --- Add near top or where constants are defined (no change needed if already defined) ---
UMAP_N_NEIGHBORS, UMAP_MIN_DISTS, UMAP_N_COMPONENTS already exist
--- Ensure output directories exist where clusters are saved ---
def main_cluster_mentions(fname, en_fname, embedding_path, dir):
data = load_data(fname)
if Path(embedding_path).exists():
data["en_embedding"] = pd.read_pickle(embedding_path)
else:
# if using OpenAI embeddings you need to uncomment the import and make the client available
# from openai import OpenAI
client = OpenAI() # only if you uncomment import
data = main_embeddings(data, client, embedding_path, translate=True)
# ensure output dir exists
os.makedirs(dir, exist_ok=True)
for col in ["en_embedding"]:
print(f"\n~~ Clustering based on {col} ~~\n")
matrix = np.vstack(data[col].dropna().values)
for n_clusters in range(4, 8):
for seed in [0, 1, 2, 3, 4]:
...
pythonCopy code# --- Fixed agglomerative_clusterer ---
def agglomerative_clusterer(matrix, df, col, clusters_dir):
os.makedirs(clusters_dir, exist_ok=True)
for n_clusters in AGGLO_N_CLUSTERS:
for neighbors in UMAP_N_NEIGHBORS:
for min_dist in UMAP_MIN_DISTS: # <-- fixed name
for n_components in UMAP_N_COMPONENTS:
# only run UMAP if all params are not None (same logic as kmeans_clusterer)
if not (neighbors is None or min_dist is None or n_components is None):
umap_model = UMAP(n_neighbors=neighbors,
n_components=n_components,
min_dist=min_dist,
metric='cosine')
reduced_matrix = umap_model.fit_transform(matrix)
else:
reduced_matrix = matrix
plot_dendrogram(
reduced_matrix,
method="average",
metric="cosine",
title=f"Dendrogram (k={n_clusters}, neighbors={neighbors}, min_dist={min_dist}, n_components={n_components})",
save_path=f"{clusters_dir}/dendro_k_{n_clusters}_neighbors_{neighbors}_min_dist_{min_dist}_n_components_{n_components}.png"
)
print(f"\n~~ Agglomerative Clustering with {n_clusters} clusters ~~\n")
print(f"n_neighbors: {neighbors}, min_dist: {min_dist}, n_components: {n_components}")
clustering = AgglomerativeClustering(n_clusters=n_clusters,
metric='cosine',
linkage='average',
compute_distances=True)
df = df.dropna(subset=[col])
df['cluster'] = clustering.fit_predict(reduced_matrix)
out_name = f"agglo_k_{n_clusters}_neighbors_{neighbors}_min_dist_{min_dist}_n_components_{n_components}.csv"
df.to_csv(f"{clusters_dir}/{out_name}")
print_cluster_stats(df, f"{col}_embeddings", n_clusters, clusterer=clustering)
print("Done with Agglomerative clustering")
pythonCopy code# --- Fixed hdbscan_clusterer ---
def hdbscan_clusterer(matrix, df, col, clusters_dir):
os.makedirs(clusters_dir, exist_ok=True)
for min_cluster_size in HDBSCAN_MIN_CLUSTER_SIZE:
for min_sample in HDBSCAN_MIN_SAMPLES:
for neighbors in UMAP_N_NEIGHBORS:
for min_dist in UMAP_MIN_DISTS: # <-- fixed name
for n_components in UMAP_N_COMPONENTS:
# same conditional as kmeans_clusterer
if not (neighbors is None or min_dist is None or n_components is None):
umap_model = UMAP(n_neighbors=neighbors,
n_components=n_components,
min_dist=min_dist,
metric='cosine')
reduced_matrix = umap_model.fit_transform(matrix)
else:
reduced_matrix = matrix
print(f"\n~~ HDBSCAN with min_cluster_size={min_cluster_size} ~~\n")
print(f"n_neighbors: {neighbors}, min_dist: {min_dist}, n_components: {n_components}")
clusterer = HDBSCAN(min_cluster_size=min_cluster_size,
metric='euclidean',
min_samples=min_sample)
df = df.dropna(subset=[col])
df['cluster'] = clusterer.fit_predict(reduced_matrix)
print(f"Noise points (label = -1): {df[df.cluster == -1].shape[0]}")
out_name = f"hdbscan_min_size_{min_cluster_size}_neighbors_{neighbors}_min_dist_{min_dist}_n_components_{n_components}_min_sample_{min_sample}.csv"
df.to_csv(f"{clusters_dir}/{out_name}")
n_clusters = df.cluster.nunique() - 1
print_cluster_stats(df, f"{col}_embeddings", n_clusters, clusterer=clusterer)
print("Done with HDBSCAN clustering")
pythonCopy code# --- Improve SentenceTransformer encode call (in main_stransformer) to use device and batching ---
def main_stransformer(...):
...
device = "cuda" if torch.cuda.is_available() else "cpu"
model = SentenceTransformer("MPA/sambert")
# Move model if required and pass device to .encode for efficiency
# (some sentence-transformers versions accept device param)
model.to(device)
df = pd.read_csv(path2sentences, index_col=0)
sentences = df[col].fillna("").astype(str).tolist()
print("~~ Encoding sentences to embeddings ~~\n")
print("Number of sentences:", len(sentences))
# better: batch and optionally show progress
embeddings = model.encode(sentences, device=device, show_progress_bar=True, batch_size=64)
embeddings = embeddings.tolist()
...
Checklist before running your example command
Fix the three changes above (or apply the patch).
Create the target directory or let the script create it (the patch does os.makedirs(..., exist_ok=True)).
Install dependencies: sentence-transformers, hdbscan, umap-learn, scikit-learn, torch, etc.
Make sure the model MPA/sambert is available (internet or cached). If you want to use --embedding_method openai, uncomment from openai import OpenAI and ensure OpenAI SDK & API key are configured.
Watch memory/GPU: encoding large CSVs may OOM — use batch_size in encode.
Conclusion
With the fixes above, your CLI:
arduinoCopy code--data_fname "../data/inclusive_mentions_2025-10-22.csv"
--cluster_dir "hdbscan_sambert_oct2025" --col "output"
--method "hdbscan" --embedding_method "sambert"
should run and produce HDBSCAN CSV outputs in hdbscan_sambert_oct2025/. If you want, I can produce a patched full script file (ready-to-run) that includes these fixes and some safety checks (batching, logging, limit on sample size) — tell me and I’ll paste the full corrected script.