Complete Clustering Pipeline
Advanced · Write the code · from K-Means Clustering: Find Patterns in Data Without Labels
From the lesson: K-Means Clustering: Find Patterns in Data Without Labels
A streaming service groups users into "action fans," "comedy lovers," and "documentary watchers" - without anyone filling out a survey. A retailer segments customers into "big spenders," "bargain hunters," and "window shoppers" based on purchase behavior. Nobody labeled these groups. The algorithm discovered them.
Read the lessonBuild a full pipeline: scale the customer data with StandardScaler, find the best K (from 2 to 5) using silhouette score, then print the best K and its silhouette score rounded to 4 decimal places. Format: "Best K: X" then "Silhouette: X.XXXX" on separate lines.
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score
import numpy as np
# Customer data: [annual_spend, visit_frequency, avg_basket]
np.random.seed(42)
customers = np.vstack([
np.random.normal([200, 2, 30], [50, 1, 10], (80, 3)),
np.random.normal([800, 8, 80], [100, 2, 15], (50, 3)),
np.random.normal([2000, 15, 150], [200, 3, 20], (30, 3))
])
# Scale, find best K, print results
More K-Means Clustering exercises
- Run Your First K-MeansAdvanced
- Predict the Inertia PatternAdvanced
- Find the Best K with SilhouetteAdvanced
- Use DBSCAN to Handle NoiseAdvanced
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz