Hierarchical clustering groups similar data points step-by-step. It helps find natural groups without knowing how many groups there are.
Hierarchical clustering (linkage) in SciPy
Start learning this pattern below
Jump into concepts and practice - no test required
from scipy.cluster.hierarchy import linkage Z = linkage(data, method='single', metric='euclidean')
data is your input data as a 2D array or matrix.
method chooses how to link clusters: 'single', 'complete', 'average', etc.
Z = linkage(data, method='single')Z = linkage(data, method='complete')Z = linkage(data, method='average')Z = linkage(data, method='ward')This code clusters 5 points using average linkage. It prints the linkage matrix showing how clusters merge step-by-step. Then it draws a dendrogram to visualize the cluster hierarchy.
import numpy as np from scipy.cluster.hierarchy import linkage, dendrogram import matplotlib.pyplot as plt # Sample data: 5 points with 2 features each data = np.array([[1, 2], [2, 3], [5, 8], [6, 8], [7, 9]]) # Perform hierarchical clustering using average linkage Z = linkage(data, method='average') # Print linkage matrix print(Z) # Plot dendrogram to visualize clustering plt.figure(figsize=(6, 4)) dendrogram(Z, labels=["A", "B", "C", "D", "E"]) plt.title('Hierarchical Clustering Dendrogram') plt.xlabel('Sample') plt.ylabel('Distance') plt.tight_layout() plt.show()
The linkage matrix has 4 columns: indices of clusters merged, distance between them, and number of original points in the new cluster.
Use dendrograms to understand cluster merging visually.
Different linkage methods can produce different cluster shapes.
Hierarchical clustering groups data step-by-step without preset cluster count.
Linkage methods control how distances between clusters are calculated.
Dendrograms help visualize the cluster structure and merging process.
Practice
linkage function in scipy.cluster.hierarchy do in hierarchical clustering?Solution
Step 1: Understand hierarchical clustering process
Hierarchical clustering builds clusters step-by-step by merging closest groups.Step 2: Role of
Thelinkagefunctionlinkagefunction calculates distances between clusters at each step to decide which to merge next.Final Answer:
It calculates distances between clusters step-by-step to form a hierarchy. -> Option AQuick Check:
Linkage = stepwise cluster distance calculation [OK]
- Thinking linkage assigns fixed clusters first
- Confusing linkage with visualization functions
- Assuming linkage normalizes data
linkage function from scipy.cluster.hierarchy?Solution
Step 1: Identify correct module path
Thelinkagefunction is inside thehierarchysubmodule ofscipy.cluster.Step 2: Use correct Python import syntax
Python import syntax for functions isfrom module import function. So,from scipy.cluster.hierarchy import linkageis correct.Final Answer:
from scipy.cluster.hierarchy import linkage -> Option DQuick Check:
Correct import = from scipy.cluster.hierarchy import linkage [OK]
- Using wrong module path
- Wrong import syntax like 'import linkage from ...'
- Importing from scipy.cluster directly
from scipy.cluster.hierarchy import linkage import numpy as np X = np.array([[1, 2], [3, 4], [5, 6]]) Z = linkage(X, method='single') print(Z.shape)
Solution
Step 1: Understand linkage output shape
Forndata points, linkage returns a matrix withn-1rows and 4 columns.Step 2: Calculate shape for 3 points
Here,n=3, so output shape is (2, 4).Final Answer:
(2, 4) -> Option CQuick Check:
Linkage shape = (n-1, 4) = (2, 4) [OK]
- Expecting shape (n, 4) instead of (n-1, 4)
- Confusing columns count
- Miscounting number of data points
from scipy.cluster.hierarchy import linkage import numpy as np X = np.array([[1, 2], [3, 4], [5, 6]]) Z = linkage(X, method='fast') print(Z)
Solution
Step 1: Check valid linkage methods
Valid methods include 'single', 'complete', 'average', 'ward', etc. 'fast' is not valid.Step 2: Confirm input data and syntax
Input can be raw data array; print statement syntax is correct in Python 3.Final Answer:
The method 'fast' is not a valid linkage method. -> Option AQuick Check:
Invalid method name causes error [OK]
- Assuming 'fast' is a valid method
- Thinking input must be 1D array
- Confusing linkage input requirements
Solution
Step 1: Understand merges in hierarchical clustering
Fornpoints, hierarchical clustering performsn-1merges to combine all points into one cluster.Step 2: Apply to 5 points with 'ward' method
With 5 points, the linkage matrix records 4 merges regardless of method.Final Answer:
4 merges, because each merge reduces clusters by one until one cluster remains. -> Option BQuick Check:
Merges = n-1 = 4 for 5 points [OK]
- Thinking merges equal number of points
- Assuming method changes merge count
- Confusing merges with cluster count
