Given list: 1. UNIVERSITY OF TEXAS MD ANDERSON CANCER CENTER 2. UNIVERSITY OF TEXAS MEDICAL BRANCH 3. UNIVERSITY OF TEXAS MEDICAL BRANCH AT GALVESTON 4. UNIVERSITY OF TEXAS MEDICAL BRANCH SCHOOL 5. UNIVERSITY OF TEXAS MEDICAL SCHOOL AT HOUSTON 6. UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SA 7. UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SAN ANTONIO 8. UNIVERSITY OF TEXAS MEDICAL SCHOOL OF SAN ANTONIO 9. UNIVERSITY OF SOUTHERN CALIFORNIA KECK SCHOOL OF MEDICINE 10. UNIVERSITY OF SOUTHERN CALIFORNIA LAC USC MEDICAL CENTER 11. UNIVERSITY OF SOUTHERN CALIFORNIA LOS ANGELES 12. UNIVERSITY OF SOUTHERN CALIFORNIA OF SOCIAL WORK give me a python code to cluster in two main bucket. you may use embedding for semanticor TFidf approach
Assistant
User
tell me using AgglomerativeClustering
Assistant
Certainly! Here's how you can cluster your list of institution names into two main buckets using AgglomerativeClustering from scikit-learn along with TF-IDF vectorization for text features.
User
use , distance_threshold
Assistant
Certainly! Below is an example Python code snippet that clusters your given list of institution names into two main buckets using TF-IDF vectorization followed by KMeans clustering. The two clusters should roughly separate Texas-based institutions from Southern California-based ones based on semantic similarity.
python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
# Your list of institution names
institutions = [
"UNIVERSITY OF TEXAS MD ANDERSON CANCER CENTER",
"UNIVERSITY OF TEXAS MEDICAL BRANCH",
"UNIVERSITY OF TEXAS MEDICAL BRANCH AT GALVESTON",
"UNIVERSITY OF TEXAS MEDICAL BRANCH SCHOOL",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT HOUSTON",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SA",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SAN ANTONIO",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL OF SAN ANTONIO",
"UNIVERSITY OF SOUTHERN CALIFORNIA KECK SCHOOL OF MEDICINE",
"UNIVERSITY OF SOUTHERN CALIFORNIA LAC USC MEDICAL CENTER",
"UNIVERSITY OF SOUTHERN CALIFORNIA LOS ANGELES",
"UNIVERSITY OF SOUTHERN CALIFORNIA OF SOCIAL WORK"
]
# Step 1: Vectorize with TF-IDF
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(institutions)
# Step 2: KMeans clustering into 2 clusters
kmeans = KMeans(n_clusters=2, random_state=42)
kmeans.fit(X)
# Step 3: Output clusters
cluster_0 = []
cluster_1 = []
for i, label in enumerate(kmeans.labels_):
if label == 0:
cluster_0.append(institutions[i])
else:
cluster_1.append(institutions[i])
print("Cluster 0:")
for inst in cluster_0:
print(f"- {inst}")
print("\nCluster 1:")
for inst in cluster_1:
print(f"- {inst}")
Explanation:
TF-IDF Vectorizer converts text into numerical vectors emphasizing important words.
KMeans clustering groups entries into two clusters.
Likely, one cluster will contain the University of Texas entries and the other the University of Southern California entries.
Optional: Using Sentence Transformers for Embeddings
If you want a more semantic understanding, you can use a sentence transformer model to embed the texts, and then cluster on these embeddings, e.g.:
python
from sentence_transformers import SentenceTransformer
from sklearn.cluster import KMeans
institutions = [
# same list here
]
model = SentenceTransformer('all-MiniLM-L6-v2')
embeddings = model.encode(institutions)
kmeans = KMeans(n_clusters=2, random_state=42)
kmeans.fit(embeddings)
cluster_0 = []
cluster_1 = []
for i, label in enumerate(kmeans.labels_):
if label == 0:
cluster_0.append(institutions[i])
else:
cluster_1.append(institutions[i])
print("Cluster 0:")
for inst in cluster_0:
print(f"- {inst}")
print("\nCluster 1:")
for inst in cluster_1:
print(f"- {inst}")
This approach is generally more accurate for semantic clustering.
Let me know if you want me to run clustering with any specific approach or help interpret the clusters!
python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import AgglomerativeClustering
institutions = [
"UNIVERSITY OF TEXAS MD ANDERSON CANCER CENTER",
"UNIVERSITY OF TEXAS MEDICAL BRANCH",
"UNIVERSITY OF TEXAS MEDICAL BRANCH AT GALVESTON",
"UNIVERSITY OF TEXAS MEDICAL BRANCH SCHOOL",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT HOUSTON",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SA",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SAN ANTONIO",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL OF SAN ANTONIO",
"UNIVERSITY OF SOUTHERN CALIFORNIA KECK SCHOOL OF MEDICINE",
"UNIVERSITY OF SOUTHERN CALIFORNIA LAC USC MEDICAL CENTER",
"UNIVERSITY OF SOUTHERN CALIFORNIA LOS ANGELES",
"UNIVERSITY OF SOUTHERN CALIFORNIA OF SOCIAL WORK"
]
# Step 1: TF-IDF vectorization
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(institutions)
# Step 2: Agglomerative Clustering with 2 clusters
agg_clustering = AgglomerativeClustering(n_clusters=2, affinity='cosine', linkage='average')
labels = agg_clustering.fit_predict(X.toarray()) # AgglomerativeClustering needs dense arrays
# Step 3: Separate clusters
cluster_0 = [institutions[i] for i in range(len(institutions)) if labels[i] == 0]
cluster_1 = [institutions[i] for i in range(len(institutions)) if labels[i] == 1]
# Output the clusters
print("Cluster 0:")
for inst in cluster_0:
print(f"- {inst}")
print("\nCluster 1:")
for inst in cluster_1:
print(f"- {inst}")
Notes:
AgglomerativeClustering does not support sparse matrices, so we convert TF-IDF matrix to dense .toarray().
Using affinity='cosine' with linkage='average' is a good practice when working with TF-IDF vectors and text data. (Note: In scikit-learn versions prior to 1.2, affinity argument is used; in 1.2 and later it's renamed metric.)
You can swap affinity='cosine' for another metric, but cosine similarity is often better for text data.
If you want an example using embeddings (e.g., sentence transformers) before agglomerative clustering, let me know!
Certainly! Using distance_threshold with AgglomerativeClustering means you don't predefine the number of clusters, instead you specify a threshold for merging clusters — the algorithm will cluster until the merge distances exceed this threshold.
Here’s how you can modify the previous example to use distance_threshold (and not specify n_clusters):
python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import AgglomerativeClustering
institutions = [
"UNIVERSITY OF TEXAS MD ANDERSON CANCER CENTER",
"UNIVERSITY OF TEXAS MEDICAL BRANCH",
"UNIVERSITY OF TEXAS MEDICAL BRANCH AT GALVESTON",
"UNIVERSITY OF TEXAS MEDICAL BRANCH SCHOOL",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT HOUSTON",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SA",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL AT SAN ANTONIO",
"UNIVERSITY OF TEXAS MEDICAL SCHOOL OF SAN ANTONIO",
"UNIVERSITY OF SOUTHERN CALIFORNIA KECK SCHOOL OF MEDICINE",
"UNIVERSITY OF SOUTHERN CALIFORNIA LAC USC MEDICAL CENTER",
"UNIVERSITY OF SOUTHERN CALIFORNIA LOS ANGELES",
"UNIVERSITY OF SOUTHERN CALIFORNIA OF SOCIAL WORK"
]
# Step 1: Vectorize text data
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(institutions)
# Step 2: AgglomerativeClustering with distance_threshold
# Note: must not set n_clusters when distance_threshold is set
agg_clustering = AgglomerativeClustering(
distance_threshold=0.7, # You can adjust this threshold (between 0 and 2 for cosine distances)
n_clusters=None,
affinity='cosine',
linkage='average'
)
# AgglomerativeClustering expects dense input, convert sparse to dense
labels = agg_clustering.fit_predict(X.toarray())
# Step 3: Group institutions by cluster label
clusters = {}
for label, inst in zip(labels, institutions):
clusters.setdefault(label, []).append(inst)
# Print clusters
for cluster_id, items in clusters.items():
print(f"Cluster {cluster_id}:")
for item in items:
print(f"- {item}")
print()
Important Notes:
When using distance_threshold, do not specifyn_clusters.
distance_threshold controls how far clusters can be merged:
Smaller values → more clusters (more fine-grained)
Larger values → fewer clusters (more merging)
For cosine affinity, the distance is 1 - cosine similarity, so range is roughly [0, 2].
You may need to try different distance_threshold values to get exactly two main buckets — e.g., try 0.6, 0.7, 0.8, etc.
If you want, I can help you tune the threshold or visualize dendrograms to choose the best cut.