Clustering and distance
Find structure without target labels
Clustering groups records by a chosen notion of similarity without requiring known target labels. Imagine fictional machine cycle durations of 0, 2, 8 and 10 seconds above a baseline. Two groups may help an engineer investigate operating modes, but the numbers do not tell us what those modes mean. Cluster 0 and cluster 1 are arbitrary identifiers, not ordered classes or verified diagnoses. Unlike supervised classification, there is no known target used to fit the groups. Choose features and distances according to the intended investigation.
One k-means update by hand
K-means seeks to minimize the sum of squared Euclidean distances from points to their assigned centers (within-cluster sum of squares, also called inertia). Lloyd’s algorithm alternates assigning each point to a nearest center and replacing each nonempty center with its cluster mean. With initial centers 0 and 8, points 0 and 2 go to the first cluster; 8 and 10 go to the second. New centers are 1 and 9. The sum of squared distances to the original assigned centers is 8; to the updated centers it is 4. The code runs exactly one update, not a complete fit. Labels refer to the old centers; recompute assignments if evaluating new centers. Ties choose the earliest index. Empty clusters retain their old center, a teaching policy rather than a universal library rule. Inputs are small finite one-dimensional numbers; no centers raises an error, and no points leaves all centers unchanged.
def lloyd_step(points, centers): if not centers: raise ValueError("At least one center required") groups = [[] for _ in centers] labels = [] for x in points: label = min(range(len(centers)), key=lambda j: (x - centers[j]) ** 2) labels.append(label) groups[label].append(x) updated = [sum(g) / len(g) if g else c for g, c in zip(groups, centers)] return labels, updated
labels, centers = lloyd_step([0, 2, 8, 10], [0, 8])print(labels)print(centers)Why k and feature scale matter
A full iterative implementation stops using a stated tolerance, unchanged assignments or an iteration budget; initialization can lead to different local minima. Try different initial centers and compare inertia for the same k. Increasing k can reduce optimal inertia even when extra groups have no operational value. In two dimensions, a point (0,0) is closer to (4,0) than (1,100), but if the second feature is measured in hundreds of original units, the latter becomes (1,1) and is closer. Scaling changes the model geometry. Fit any scaling on reference/training data, then reuse it unchanged. K-means favors compact groups under squared Euclidean distance; it may split elongated shapes or merge differently sized clusters. A mean center need not be an observed record.
Hierarchical and density-based alternatives
Agglomerative hierarchical clustering starts with singleton groups and repeatedly merges groups using a linkage criterion. Single linkage uses the closest pair, complete linkage the farthest pair, and average linkage the average pairwise distance. For points 0,2,9, the first merge under these rules is {0,2}; its single-link distance to 9 is 7, complete-link 9, average-link 8. A dendrogram records the merge structure; selecting a cut determines groups. DBSCAN instead uses neighborhoods of radius eps and a minimum count min_samples, including the point itself. A core point meets that count; a non-core point reachable directly from a core point can be a border point; points not density-reachable from any core are noise. With [0,1,2,9], radius 1 and count 3, only 1 is core; 0 and 2 are borders and 9 is noise. At count 2, all first three are core. The following code checks core status only; it does not compute connected components, border assignments or full DBSCAN. Duplicate observations count separately. Positive eps and integer min_samples are assumed; boundary distances count.
def core_flags(points, eps, min_samples): if eps <= 0 or min_samples < 1: raise ValueError("Positive radius and count required") return [sum(abs(x - y) <= eps for y in points) >= min_samples for x in points]
print(core_flags([0, 1, 2, 9], 1, 3))print(core_flags([0, 1, 2, 9], 1, 2))Evaluate a clustering responsibly
Without labels, use internal criteria and domain checks. Silhouette for a point compares its mean distance a to other members of its cluster with the smallest mean distance b to another cluster: (b-a)/max(a,b), when defined; higher values can indicate better separation under the chosen distance. Singleton conventions and degenerate cases depend on the implementation. Compare stability across seeds, feature representations and data samples; examine group sizes and actual feature summaries. Inertia alone is not a fair comparison across different k. A density algorithm may mark valid rare operating modes as noise; uneven density can make one radius unsuitable. Practice: rerun the centroid example with centers [2,10] and explain why labels are not ground truth. Next: information loss and unusual observations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Clustering and distance quiz
Apply clustering and representation concepts to small synthetic examples.
What are the updated centers for [0,2,8,10] with initial centers [0,8]?
Without external labels or domain validation, what does a k-means label of 1 mean?
For observations [0, 1, 2, 9], eps = 1 and min_samples = 3 (including self and boundary), which observation is core?
What is complete-link distance from {0,2} to {9}?
Why can the globally optimal k-means inertia be nonincreasing as k grows, for the same data and distance?