Bird
Raised Fist0
ML Pythonml~20 mins

Hierarchical clustering in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Hierarchical clustering
Problem:You want to group similar data points into clusters without knowing the number of clusters beforehand. You use hierarchical clustering on a dataset of 2D points.
Current Metrics:The dendrogram shows clusters but the clusters formed by cutting the dendrogram at a certain height are not meaningful. Silhouette score is 0.45.
Issue:The clustering is not well separated. The linkage method and distance metric may not be optimal, causing poor cluster quality.
Your Task
Improve the quality of hierarchical clustering to get a silhouette score above 0.6 by adjusting linkage method and distance metric.
You must use hierarchical clustering.
You can only change linkage method and distance metric parameters.
Do not change the dataset or use other clustering algorithms.
Hint 1
Hint 2
Hint 3
Solution
ML Python
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage

# Generate sample data
X, _ = make_blobs(n_samples=150, centers=3, cluster_std=1.0, random_state=42)

# Compute linkage matrix with 'ward' linkage
Z = linkage(X, method='ward')

# Plot dendrogram
plt.figure(figsize=(8, 4))
dendrogram(Z)
plt.title('Dendrogram using Ward linkage')
plt.xlabel('Sample index')
plt.ylabel('Distance')
plt.show()

# Perform Agglomerative Clustering with 3 clusters, ward linkage
cluster = AgglomerativeClustering(n_clusters=3, linkage='ward')
labels = cluster.fit_predict(X)

# Calculate silhouette score
score = silhouette_score(X, labels)
print(f'Silhouette Score: {score:.2f}')
Changed linkage method to 'ward' which minimizes variance within clusters.
Used 'euclidean' distance metric compatible with 'ward' linkage (default for ward).
Set number of clusters to 3 based on data generation centers.
Results Interpretation

Before: Silhouette score = 0.45 (poor cluster quality)

After: Silhouette score = 0.72 (good cluster quality)

Choosing the right linkage method and distance metric in hierarchical clustering greatly improves cluster quality and separation.
Bonus Experiment
Try hierarchical clustering with 'complete' linkage and 'manhattan' distance. Compare the silhouette score with the 'ward' linkage result.
💡 Hint
Use linkage method='complete' and metric='cityblock' in the linkage function and AgglomerativeClustering.

Practice

(1/5)
1. What is the main idea behind hierarchical clustering in machine learning?
easy
A. It uses a neural network to classify data points into clusters.
B. It assigns data points to clusters based on a fixed number of clusters.
C. It builds a tree of clusters by joining or splitting data points step by step.
D. It randomly assigns data points to clusters without any order.

Solution

  1. Step 1: Understand hierarchical clustering concept

    Hierarchical clustering creates a tree-like structure by either merging or splitting data points stepwise.
  2. Step 2: Compare with other clustering methods

    Unlike fixed cluster methods, it does not require a preset number of clusters and builds a hierarchy instead.
  3. Final Answer:

    It builds a tree of clusters by joining or splitting data points step by step. -> Option C
  4. Quick Check:

    Hierarchical clustering = stepwise tree building [OK]
Hint: Think of building a family tree of data points step by step [OK]
Common Mistakes:
  • Confusing hierarchical clustering with k-means clustering
  • Thinking it requires a fixed number of clusters upfront
  • Believing it assigns clusters randomly
2. Which of the following Python code snippets correctly imports the function for hierarchical clustering from the SciPy library?
easy
A. from scipy.cluster.hierarchy import linkage
B. import sklearn.cluster.hierarchical as hc
C. from scipy.cluster import kmeans
D. import hierarchical from scipy.cluster

Solution

  1. Step 1: Identify correct import for hierarchical clustering

    The function linkage from scipy.cluster.hierarchy is used for hierarchical clustering.
  2. Step 2: Check other options for errors

    A has invalid syntax, B uses wrong module name (sklearn.cluster.hierarchical does not exist), C imports kmeans (not hierarchical).
  3. Final Answer:

    from scipy.cluster.hierarchy import linkage -> Option A
  4. Quick Check:

    Correct import = from scipy.cluster.hierarchy import linkage [OK]
Hint: Remember SciPy's hierarchy module has linkage function [OK]
Common Mistakes:
  • Using sklearn.cluster.hierarchical which does not exist
  • Confusing kmeans import with hierarchical clustering
  • Incorrect import syntax
3. Given the following Python code using SciPy for hierarchical clustering, what will be the output of print(Z)?
from scipy.cluster.hierarchy import linkage
import numpy as np

X = np.array([[1, 2], [1, 4], [5, 2], [5, 4]])
Z = linkage(X, method='single')
print(Z)
medium
A. A 3x4 array showing the order and distance of cluster merges
B. A 4x4 distance matrix of all points
C. A list of cluster labels for each point
D. An error because method 'single' is invalid

Solution

  1. Step 1: Understand linkage output format

    The linkage function returns a matrix with rows showing which clusters merged, their distance, and cluster size.
  2. Step 2: Check method and output shape

    Method 'single' is valid. For 4 points, output is (4-1)=3 rows and 4 columns.
  3. Final Answer:

    A 3x4 array showing the order and distance of cluster merges -> Option A
  4. Quick Check:

    linkage output = cluster merges matrix [OK]
Hint: linkage returns merge info, not labels or distance matrix [OK]
Common Mistakes:
  • Expecting cluster labels instead of merge matrix
  • Confusing linkage output with distance matrix
  • Thinking 'single' method is invalid
4. You run this code but get an error:
from scipy.cluster.hierarchy import dendrogram
import numpy as np

X = np.array([[1, 2], [3, 4], [5, 6]])
dendrogram(X)
What is the problem and how to fix it?
medium
A. The array X has wrong shape; reshape it to 1D before dendrogram().
B. You must pass a linkage matrix, not raw data, to dendrogram(). Use linkage() first.
C. dendrogram() requires labels argument; add labels=['a','b','c'].
D. You need to import dendrogram from sklearn.cluster, not scipy.

Solution

  1. Step 1: Identify dendrogram input requirements

    dendrogram() expects a linkage matrix, not raw data points.
  2. Step 2: Fix by computing linkage first

    Use linkage() on X to get the linkage matrix, then pass it to dendrogram().
  3. Final Answer:

    You must pass a linkage matrix, not raw data, to dendrogram(). Use linkage() first. -> Option B
  4. Quick Check:

    dendrogram input = linkage matrix [OK]
Hint: Always run linkage() before dendrogram() [OK]
Common Mistakes:
  • Passing raw data directly to dendrogram()
  • Thinking dendrogram needs labels argument
  • Importing dendrogram from wrong library
5. You want to cluster customer data using hierarchical clustering but do not know how many clusters to choose. Which approach helps you decide the number of clusters without setting it upfront?
hard
A. Use PCA to reduce dimensions before clustering.
B. Use k-means clustering instead with a fixed k value.
C. Randomly assign clusters and check accuracy.
D. Cut the dendrogram at a chosen distance threshold to form clusters.

Solution

  1. Step 1: Understand hierarchical clustering flexibility

    Hierarchical clustering builds a tree and allows cutting at any distance to form clusters.
  2. Step 2: Use distance threshold to decide clusters

    By choosing a height to cut the dendrogram, you get clusters without presetting their number.
  3. Final Answer:

    Cut the dendrogram at a chosen distance threshold to form clusters. -> Option D
  4. Quick Check:

    Distance threshold cutting = flexible cluster count [OK]
Hint: Cut dendrogram by distance, not fixed cluster count [OK]
Common Mistakes:
  • Thinking hierarchical clustering needs fixed cluster count upfront
  • Confusing with k-means clustering method
  • Ignoring dendrogram visualization for cluster choice
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