Agglomerative Models
Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 17 of 51.
Cars fill two car parks, with a line of cars along the road between. Two ways of merging into 2 clusters:
scikit-learn does the merging. Say where to stop with n_clusters:
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=2, linkage="ward")
labels = model.fit_predict(X)linkage decides how far apart two groups are:
"ward", the default: keeps groups tight"complete": their farthest pair"average": the average of all pairs"single": their closest pair
Single follows chains: here the road swallows both car parks. Ward makes round, even groups.
Challenge
MediumWild strawberries grow in three patches, plus a few along a path. Which linkage finds the patches? plants holds their positions.
- For each linkage in
linkages, cluster the plants into 3 groups. - Print the group sizes as a list, largest first.
- When the largest group holds more than half the plants, add
chained.
For another meadow:
ward: [40, 38, 31]
complete: [41, 37, 31]
average: [41, 37, 31]
single: [86, 22, 1] chainedTry it yourself
import numpy as np
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
# Where 109 wild strawberry plants grow in a meadow (meters): three patches and a path
rng = np.random.default_rng(4)
plants = np.round(np.concatenate([
rng.normal([2, 3], 0.8, size=(40, 2)),
rng.normal([9, 4], 1.0, size=(35, 2)),
rng.normal([6, 10], 0.9, size=(25, 2)),
np.column_stack([np.linspace(3, 8, 9), np.linspace(3.2, 4, 9)]) + rng.normal(0, 0.15, size=(9, 2)),
]), 2)
linkages = ["ward", "complete", "average", "single"]
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unsupervised Learning
1Finding Groups
Learning Without LabelsMeasuring SimilarityK-Means by HandK-Means in scikit-learnRecap: Gym Members7PCA in Practice
Seeing 64 DimensionsComponents as PatternsCompress and RebuildPCA Before a ModelRecap: Face Scanner10Project: Digit Explorer
Look at the DigitsShrink with PCACluster the DigitsName the ClustersFind the Odd OnesPractice on your own: Online Python compiler