Menu
CoddyTech

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:

Two charts of the same 102 cars. Left, linkage ward: the north car park and the south car park are two clusters of 53 and 49 cars, the road split between them. Right, linkage single: one cluster of 101 cars and 1 lone car

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 icon

Challenge

Medium

Wild strawberries grow in three patches, plus a few along a path. Which linkage finds the patches? plants holds their positions.

  1. For each linkage in linkages, cluster the plants into 3 groups.
  2. Print the group sizes as a list, largest first.
  3. 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] chained

Try 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unsupervised Learning

Practice on your own: Online Python compiler