Interactive companion · Chapter 11 · Unsupervised learning

Unsupervised Learning Lab

Unsupervised learning finds structure in unlabeled data, and a self-stretching map can even solve the traveling salesman problem.

Based on Chapter 11, “Supervised and unsupervised learning,” Sections 11.2, 11.4 and 11.8, in Alaa Khamis, Optimization Algorithms: AI techniques for design, planning, and control problems, Manning Publications, 2024 (ISBN 978-1633438835).

A self-organizing ring of neurons stretching over 194 cities in Qatar.

Part 1 · Section 11.2

Unsupervised learning

Unsupervised learning works with unlabeled data: clustering groups similar objects, and dimensionality reduction maps data to fewer dimensions while keeping its structure.

Section 11.2 of the book surveys the main families of clustering and dimensionality-reduction algorithms.

Part 2 · Similarity

Similarity measures

Pick a measure to see its contours of equal distance; click to place a point.

Chapter 11 of the book gives the formula for each measure and works a haversine example.

Distance explorer

Click to place a point

On the globe, the haversine formula gives great-circle distances. Pick two cities to compare it with a flat-map straight line.

Haversine

Part 3 · K-means

K-means clustering

K-means alternates two steps: assign every point to its nearest center, then move each center to the mean of its points. It converges, but to a local minimum that depends on the seeds. Click Next step, or try Bad seeds.

Chapter 11 of the book covers k-means++ seeding, the cost of k-means, and how it compares with other algorithms.

K-means step by step

Click to add points

Validating clusters

Internal measures (silhouette, Davies-Bouldin) judge a clustering from the data alone; external ones (ARI, NMI) compare it with known classes. The chart scores each k for the data above.

Chapter 11 of the book defines each validation index and explains the elbow method for choosing k.

Choosing k for the data above

Part 4 · Density and hierarchy

Beyond k-means: DBSCAN and agglomerative clustering

DBSCAN grows clusters of any shape from dense core points; agglomerative clustering keeps merging the closest clusters. Change ε and the linkage and compare ARI.

Three algorithms, one dataset

Part 5 · Section 11.4

Self-organizing maps

In a self-organizing map, the neuron closest to each input wins, and it and its lattice neighbors move toward the input. Change σ to compare neighborhood shapes, then train the 2D map below.

Section 11.4 of the book gives Algorithm 11.1 and the update rule, and explains why a SOM preserves topology.

Neighborhood functions (equation 11.6)

A 2D map unfolding over data

Neurons drawn at their weights

Part 6 · Section 11.8, Listing 11.5

Solving the TSP with a self-organizing map

Make the lattice a ring: it stretches like an elastic band over the cities, and reading them in ring order gives a tour. Press Run, then polish with 2-opt.

Section 11.8 of the book walks through Listing 11.5, its settings and results on qa194.

194 cities in Qatar

TSPLIB qa194, from the book’s repo

Part 7 · Code

Python in Google Colab

Open the book’s notebooks or the companion notebook with the from-scratch code below in Colab.

Notebooks

From-scratch implementations

# Similarity measures for clustering
import math
import numpy as np

x, y = np.array([1.0, 2.0]), np.array([4.0, 6.0])
print("Euclidean:", np.sqrt(((x - y) ** 2).sum()))                     # 5.0
print("Manhattan:", np.abs(x - y).sum())                               # 7.0
print("Chebyshev:", np.abs(x - y).max())                               # 4.0
print("cosine similarity:", round(x @ y / (np.linalg.norm(x) * np.linalg.norm(y)), 4))

# Mahalanobis distance accounts for the spread and correlation of the data
rng = np.random.default_rng(0)
data = rng.multivariate_normal([0, 0], [[4, 3], [3, 4]], 500)
S_inv = np.linalg.inv(np.cov(data.T))
maha = lambda a, b: math.sqrt((a - b) @ S_inv @ (a - b))
p, q = np.array([2.0, 2.0]), np.array([2.0, -2.0])
print(f"same Euclidean distance from the origin ({np.linalg.norm(p):.2f}), Mahalanobis: along the trend {maha(p, np.zeros(2)):.2f}, across it {maha(q, np.zeros(2)):.2f}")


def haversine(lat1, lon1, lat2, lon2, R=6371.0):
    """Great-circle distance in km."""
    la1, lo1, la2, lo2 = map(math.radians, (lat1, lon1, lat2, lon2))
    a = math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2
    return 2 * R * math.atan2(math.sqrt(a), math.sqrt(1 - a))


print(f"Los Angeles to Madrid: {haversine(34.0522, -118.2437, 40.4168, -3.7038):,.1f} km")   # about 9,363 km
Part 8 · Summary

What to remember

Distance matters

The measure decides what “close” means.

K-means is local search

It lowers inertia every step but depends on its seeds.

Validate

Internal indexes need no labels; external ones do.

SOMs

A ring-shaped SOM gives good TSP tours.

References: T. Kohonen, “Self-organized formation of topologically correct feature maps,” 1982. M. Ester, H.-P. Kriegel, J. Sander and X. Xu, “A density-based algorithm for discovering clusters in large spatial databases with noise,” 1996. D. Arthur and S. Vassilvitskii, “k-means++: the advantages of careful seeding,” 2007. TSPLIB national instances (qa194). A. Khamis, Optimization Algorithms: AI techniques for design, planning, and control problems, Manning, 2024, Chapter 11.

Part 9 · Quiz

Check your understanding

Two quick questions on Chapter 11. Pick an answer to check it.

Q1. Two runs of k-means on the same data with the same k give different clusterings. Why?

Q2. When a ring-shaped self-organizing map is used to solve the TSP, how is the tour obtained?

For more exercises with full solutions, see Appendix C, “Exercises and solutions,” in Optimization Algorithms. The coding solutions are also on GitHub (Chapter 11).