Editor

Find the Best K with Silhouette

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 lesson

Compute the silhouette score for K=2 through K=6. Print each as "K=X: Y.YYYY". Then print the K with the highest silhouette score on a new line as "Best K: X".

from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=200, centers=3,
cluster_std=1.0, random_state=42)
# Find best K using silhouette score

More K-Means Clustering exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz