In this script. Add visualization of the clusters: import math import pandas as pd…
- User
In this script. Add visualization of the clusters:
import math
import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score, davies_bouldin_score import matplotlib.pyplot as plt
Show all columns
pd.set_option('display.max_columns', None)
Numeric columns from the paper
numeric_cols = ['participation', 'overall_responsivity', 'internal_cohesion', 'social_impact', 'newness', 'communication_density']
Load data
df = pd.read_csv('../data/du_results_6_aspects_129_discussions.csv') df.columns = [col.replace('_score', '') for col in df.columns]
Clip outliers at 1st and 99th percentiles
for c in numeric_cols: lower = np.nanpercentile(df[c], 1) upper = np.nanpercentile(df[c], 99) df[c] = np.clip(df[c], lower, upper)
Extract feature matrix
X = df[numeric_cols]
=== Step 1: Z-score standardization (as in the paper) ===
scaler = StandardScaler() X_scaled = scaler.fit_transform(X)
=== Step 2: Determine optimal number of clusters ===
sil_scores, db_scores = [], [] k_values = range(3, 10)
for k in k_values: kmeans = KMeans(n_clusters=k, random_state=42) labels = kmeans.fit_predict(X_scaled) sil_scores.append(silhouette_score(X_scaled, labels)) db_scores.append(davies_bouldin_score(X_scaled, labels))
best_sil = np.argmax(sil_scores) + 3 best_db = np.argmin(db_scores) + 3 print(f"Best k by Silhouette: {best_sil}, Davies-Bouldin: {best_db}")
=== Step 3: Plot metrics ===
plt.figure(figsize=(8, 5)) plt.plot(k_values, sil_scores, marker='o', label='Silhouette') plt.plot(k_values, db_scores, marker='s', label='Davies-Bouldin') plt.xlabel('Number of clusters (k)') plt.ylabel('Score') plt.title('Clustering Metrics for Optimal k') plt.legend() plt.show()
=== Step 4: Run K-Means with chosen k ===
best_k = math.floor((best_db + best_sil)/2) # you can also use best_sil if preferred kmeans = KMeans(n_clusters=best_k, random_state=0) df['cluster'] = kmeans.fit_predict(X_scaled)
=== Step 5: Centroids in standardized scale ===
centroids_scaled = pd.DataFrame(kmeans.cluster_centers_, columns=numeric_cols)
=== Step 6: Convert centroids back to original scale ===
centroids_original = pd.DataFrame(scaler.inverse_transform(kmeans.cluster_centers_), columns=numeric_cols)
print("\nCentroids in standardized space:") print(centroids_scaled)
print("\nCentroids in original scale:") print(centroids_original)
=== Step 7: Plot centroids ===
features = centroids_scaled.columns clusters = centroids_scaled.index n_clusters = len(clusters) n_features = len(features)
- Assistant
Sure! We can add a visualization of the actual clusters in feature space. Since you have 6 numeric features, a simple 2D scatter plot isn’t enough to show all dimensions, but we can:
Use PCA to reduce the features to 2 dimensions for visualization.
Color the points by cluster.
Optionally, mark the cluster centroids in the PCA space.
Here’s how to extend your script: pythonCopy codefrom sklearn.decomposition import PCA
=== Step 8: Visualize clusters in 2D using PCA ===
pca = PCA(n_components=2) X_pca = pca.fit_transform(X_scaled)
df['pca1'] = X_pca[:, 0] df['pca2'] = X_pca[:, 1]
Transform centroids to PCA space
centroids_pca = pca.transform(kmeans.cluster_centers_)
plt.figure(figsize=(8, 6)) for c in range(best_k): cluster_points = df[df['cluster'] == c] plt.scatter(cluster_points['pca1'], cluster_points['pca2'], label=f'Cluster {c+1}', alpha=0.6)
Plot centroids
plt.scatter(centroids_pca[:, 0], centroids_pca[:, 1], c='black', marker='X', s=150, label='Centroids')
- User
I got this
What can you say?
- Assistant
Looking at your PCA scatter plot:
Cluster Separation:
Clusters 2 (orange) and 4 (red) are fairly tight and well-separated along PCA 1.
Cluster 3 (green) is more spread out vertically along PCA 2, indicating higher variability in those features.
Cluster 1 (blue) and Cluster 5 (purple) overlap somewhat, suggesting those groups are more similar in the features captured by the first two principal components.
Centroids:
The black “X” markers show the centroids, which are roughly at the centers of each cluster cloud.
You can see that the centroid positions reflect the main location of each cluster but some clusters (like Cluster 5/purple) are elongated or overlapping, so the centroid may not fully capture their spread.
Dimensionality Reduction:
PCA 1 seems to capture the main variance separating the orange, red, and green clusters.
- User
Show me alternative visualizations using PCA, t-SNE, and UMAP.
- Assistant
Perfect — those are the three most common ways to visualize high-dimensional clustering results. You already have PCA; let’s add t-SNE and UMAP side by side for comparison. Here’s a drop-in extension for your script: pythonCopy codefrom sklearn.manifold import TSNE import umap.umap_ as umap
=== Step 8 (alt): Compare PCA, t-SNE, UMAP ===
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
--- PCA ---
pca = PCA(n_components=2, random_state=42) X_pca = pca.fit_transform(X_scaled) axes[0].scatter(X_pca[:, 0], X_pca[:, 1], c=df['cluster'], cmap='tab10', alpha=0.6) axes[0].set_title("PCA (2D)") axes[0].set_xlabel("PC1") axes[0].set_ylabel("PC2")
--- t-SNE ---
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.