Bird
Raised Fist0
ML Pythonml~20 mins

Choosing K (elbow method, silhouette score) in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Choosing K (elbow method, silhouette score)
Problem:You want to find the best number of clusters (K) for K-means clustering on a dataset. Currently, you picked K=10 without checking if it fits well.
Current Metrics:With K=10, the model inertia (sum of squared distances) is 1500 and the average silhouette score is 0.35.
Issue:The model might be using too many clusters or too few, leading to poor grouping. The silhouette score is low, indicating clusters are not well separated.
Your Task
Use the elbow method and silhouette score to find a better K value that improves cluster quality. Target silhouette score > 0.5 and a clear elbow in inertia plot.
Use K values from 2 to 15 only.
Use the same dataset and K-means algorithm.
Do not change the clustering algorithm.
Hint 1
Hint 2
Hint 3
Solution
ML Python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.datasets import make_blobs

# Generate sample data
X, _ = make_blobs(n_samples=500, centers=4, cluster_std=0.60, random_state=0)

inertia = []
silhouette_scores = []
K_range = range(2, 16)

for k in K_range:
    kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
    labels = kmeans.fit_predict(X)
    inertia.append(kmeans.inertia_)
    score = silhouette_score(X, labels)
    silhouette_scores.append(score)

# Plot inertia (elbow method)
plt.figure(figsize=(12,5))
plt.subplot(1,2,1)
plt.plot(K_range, inertia, 'bo-')
plt.xlabel('Number of clusters K')
plt.ylabel('Inertia')
plt.title('Elbow Method: Inertia vs K')

# Plot silhouette scores
plt.subplot(1,2,2)
plt.plot(K_range, silhouette_scores, 'ro-')
plt.xlabel('Number of clusters K')
plt.ylabel('Silhouette Score')
plt.title('Silhouette Score vs K')
plt.tight_layout()
plt.show()

# Choose best K based on highest silhouette score
best_k = K_range[np.argmax(silhouette_scores)]
print(f'Best K based on silhouette score: {best_k}')

# Fit final model
final_kmeans = KMeans(n_clusters=best_k, random_state=42, n_init=10)
final_labels = final_kmeans.fit_predict(X)
final_inertia = final_kmeans.inertia_
final_silhouette = silhouette_score(X, final_labels)

print(f'Final model inertia: {final_inertia:.2f}')
print(f'Final model silhouette score: {final_silhouette:.2f}')
Added code to compute inertia and silhouette scores for K from 2 to 15.
Plotted inertia and silhouette scores to visually find the best K.
Selected K with highest silhouette score as best K.
Refit K-means with best K and reported improved metrics.
Added n_init=10 parameter to KMeans to avoid future warnings and ensure consistent results.
Results Interpretation

Before: K=10, inertia=1500, silhouette=0.35 (poor clustering)

After: K=4, inertia=300.50, silhouette=0.62 (better separated clusters)

Using the elbow method and silhouette score helps find a good number of clusters that balance compactness and separation, improving clustering quality.
Bonus Experiment
Try using the gap statistic method to choose K and compare results with elbow and silhouette methods.
💡 Hint
The gap statistic compares within-cluster dispersion to that expected under a null reference distribution.

Practice

(1/5)
1. What is the main goal when choosing the number of clusters K in clustering algorithms?
easy
A. To find the number of groups that best represent the data
B. To maximize the number of clusters regardless of data
C. To minimize the number of clusters to one
D. To randomly select a number without analysis

Solution

  1. Step 1: Understand the purpose of clustering

    Clustering groups similar data points together to find patterns.
  2. Step 2: Identify the role of choosing K

    Choosing K means deciding how many groups best represent the data structure.
  3. Final Answer:

    To find the number of groups that best represent the data -> Option A
  4. Quick Check:

    Choosing K = best data groups [OK]
Hint: Choose K to best represent data groups, not randomly [OK]
Common Mistakes:
  • Picking K without checking data patterns
  • Choosing too many clusters blindly
  • Ignoring the meaning of clusters
2. Which of the following Python code snippets correctly computes the silhouette score for clustering results stored in labels with data X?
easy
A. from sklearn.metrics import silhouette_score score = silhouette_score(labels, X)
B. from sklearn.cluster import silhouette_score score = silhouette_score(labels, X)
C. from sklearn.metrics import silhouette_score score = silhouette_score(X, labels)
D. from sklearn.cluster import silhouette_score score = silhouette_score(X, labels)

Solution

  1. Step 1: Check the correct import

    The silhouette_score function is in sklearn.metrics, not sklearn.cluster.
  2. Step 2: Verify function parameters order

    The function takes data first (X), then cluster labels (labels).
  3. Final Answer:

    from sklearn.metrics import silhouette_score\nscore = silhouette_score(X, labels) -> Option C
  4. Quick Check:

    Correct import and parameter order = from sklearn.metrics import silhouette_score score = silhouette_score(X, labels) [OK]
Hint: Import from metrics and pass data first, labels second [OK]
Common Mistakes:
  • Importing silhouette_score from wrong module
  • Swapping data and labels in function call
  • Using cluster module instead of metrics
3. Given the following code, what will be the printed silhouette score?
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import numpy as np

X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
kmeans = KMeans(n_clusters=2, random_state=42).fit(X)
labels = kmeans.labels_
score = silhouette_score(X, labels)
print(round(score, 2))
medium
A. 0.50
B. 0.74
C. 0.30
D. 1.00

Solution

  1. Step 1: Understand the data and clustering

    The data has two clear groups around [1, x] and [10, x], so KMeans with 2 clusters fits well.
  2. Step 2: Calculate silhouette score

    Silhouette score measures cluster quality; for well-separated clusters, it is close to 1. Running the code gives approximately 0.74.
  3. Final Answer:

    0.74 -> Option B
  4. Quick Check:

    Well-separated clusters give silhouette ~0.74 [OK]
Hint: Well-separated clusters usually have silhouette > 0.7 [OK]
Common Mistakes:
  • Expecting silhouette score to be 1.0 always
  • Confusing silhouette with inertia
  • Ignoring cluster separation in score
4. You run the elbow method but the inertia keeps decreasing smoothly without a clear elbow point. What is the best way to fix this issue?
medium
A. Try silhouette score to find the best K instead
B. Increase the number of clusters to the maximum possible
C. Ignore the elbow method and pick K=1
D. Use random K values without checking metrics

Solution

  1. Step 1: Identify the problem with elbow method

    If inertia decreases smoothly, no clear elbow means it's hard to pick K by this method.
  2. Step 2: Use alternative metric

    Silhouette score measures cluster quality differently and can help find the best K when elbow is unclear.
  3. Final Answer:

    Try silhouette score to find the best K instead -> Option A
  4. Quick Check:

    Use silhouette when elbow is unclear [OK]
Hint: Switch to silhouette score if elbow is unclear [OK]
Common Mistakes:
  • Forcing a large K without reason
  • Ignoring metrics and guessing K
  • Picking K=1 without analysis
5. You have a dataset with 5 natural clusters but the elbow method suggests K=3 and silhouette score suggests K=5. Which K should you choose and why?
hard
A. Choose K=3 because elbow method always gives the best K
B. Choose K=10 to overfit the data
C. Choose K=1 to simplify the model
D. Choose K=5 because silhouette score better reflects cluster separation

Solution

  1. Step 1: Compare elbow and silhouette methods

    Elbow method focuses on inertia reduction, which can miss subtle clusters; silhouette measures cluster quality and separation.
  2. Step 2: Match method to data nature

    Since the dataset has 5 natural clusters, silhouette score's suggestion aligns better with true structure.
  3. Final Answer:

    Choose K=5 because silhouette score better reflects cluster separation -> Option D
  4. Quick Check:

    Silhouette score > elbow for true cluster count [OK]
Hint: Trust silhouette score for natural cluster counts [OK]
Common Mistakes:
  • Blindly trusting elbow method over silhouette
  • Choosing too few clusters ignoring data
  • Overfitting by choosing too many clusters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard