Concepts and worked examples
Similarity, neighbors, and clusters
Choose a useful way to measure similarity and interpret groups with care.
Start with a representation
Represent an object as a feature vector x = (x₁, …, xₚ). Similarity matching finds comparable customers, documents, or products; supervised nearest-neighbor prediction also uses their observed targets. Clustering groups records without a target. These tasks share geometry but answer different questions. A cluster is not automatically a meaningful business segment, and similarity is not proof that one object causes another outcome.
For x = (1, 2) and z = (4, 6), Manhattan distance is d₁(x, z) = Σⱼ |xⱼ − zⱼ| = 3 + 4 = 7. Euclidean distance is d₂(x, z) = √Σⱼ(xⱼ − zⱼ)² = √25 = 5. Strictly, distance is the L1 or L2 norm of the difference vector, not the norm of either point alone. L1 emphasizes additive coordinate changes; L2 gives large coordinate differences greater influence through squaring.
For present-item sets A = {milk, bread, tea} and B = {bread, tea, eggs}, Jaccard similarity is |A ∩ B|/|A ∪ B| = 2/4 = 0.5; Jaccard distance is 1 − 0.5 = 0.5. Shared absences do not contribute. This suits sparse purchase indicators where jointly not buying thousands of products says little. Two empty sets need an explicit convention, often similarity 1; verify the library rather than divide by zero. Binary Euclidean distance is not inherently invalid, but it encodes a different notion of similarity.
Cosine similarity is (x · z)/(‖x‖₂‖z‖₂). For x = (1, 1) and z = (1, 0), it is 1/√2 ≈ 0.7071; cosine distance 1 − cosine ≈ 0.2929. Multiplying a nonzero vector by a positive scalar preserves direction. L2-normalized nonzero vectors satisfy ‖x − z‖₂² = 2(1 − cosine). A zero vector cannot be normalized: assign an explicit fallback or exclude it from cosine retrieval. The common 1 − cosine distance does not satisfy every metric axiom, notably the triangle inequality; index assumptions therefore matter.
Scale without leaking
An income feature measured in dollars can dominate age measured in years. Fit standardization, robust scaling, imputation, feature selection, and learned weights on training data only, then transform held-out cases. Unit-length normalization removes vector magnitude, whereas per-feature standardization changes coordinate scales; they are not interchangeable. Cosine ignores overall vector length, not arbitrary changes to individual feature units. Irrelevant features and redundant dimensions can overwhelm a useful signal even after scaling.
Nearest neighbors predict locally
For kNN classification, the positive-neighbor fraction estimates a local probability: p̂ = positives/k. With three positives among five neighbors, p̂ = 0.6. For regression, average neighbor outcomes. Distance-weighted prediction uses p̂ = Σᵢ wᵢyᵢ/Σᵢwᵢ or the same expression for numeric targets. Distances 1, 2, and 4 give inverse-distance weights 1, 0.5, and 0.25. Targets 10, 20, and 40 then produce (10 + 10 + 10)/1.75 ≈ 17.14, versus the unweighted mean 23.33.
Handle exact distance zero separately, for example by averaging only exact matches; an epsilon changes behavior and should be documented. Weighting does not remove the need to tune k, the distance metric, and preprocessing. Small k permits a jagged boundary and high variance; large k smooths predictions and can erase local structure. At k equal to the training-set size, uniform classification returns the training class prior and regression returns the training mean. k = 1 is flexible, not inevitably wrong on every problem.
Training mainly stores examples, but brute-force prediction costs roughly O(np) distance work per query and considerable memory. Trees can accelerate low-dimensional search; distance concentration often weakens them in high dimensions. Approximate indexes exchange recall for latency and need their own quality checks. Neighbor examples can support explanations, but they explain resemblance, not causal mechanisms. Validate neighborhood stability, subgroup coverage, and response time as well as predictive accuracy.
Hierarchical clustering
Agglomerative clustering begins with singleton clusters and repeatedly merges the closest pair. A dendrogram records nested merges; a horizontal cut selects a partition. Single linkage uses the nearest cross-cluster pair and can chain through noise. Complete linkage uses the farthest pair and favors compact clusters but can be outlier-sensitive. Average linkage averages cross-cluster distances, offering a compromise. Ward linkage minimizes the increase in within-cluster squared error and requires compatible Euclidean geometry; it is not just another name for nearest-pair distance.
Merge height reflects the chosen dissimilarity or merge cost, not a probability that a segment is real. Different linkage and scaling choices can produce different hierarchies. Hierarchical methods can be expensive in memory and generally do not undo early merges. Inspect representative records and stability under resampling before naming business segments.
K-means and soft alternatives
K-means minimizes Σᵢ ‖xᵢ − μcᵢ‖₂². Initialize k centers, assign each point to its nearest center, recompute each center as its assigned-point mean, and repeat until convergence or a stopping rule. For one-dimensional points 1, 2, 8, 9, the partition {1, 2}, {8, 9} has centers 1.5 and 8.5 and total squared error 1. Multiple starts or k-means++ initialization reduce poor local solutions; they do not guarantee the global optimum. Empty clusters require a defined implementation policy.
Scale meaningful features, inspect outliers, and choose k using stability, business usefulness, an elbow plot, and silhouette scores rather than one automatic rule. For each point, silhouette s = (b − a)/max(a, b), where a is mean within-cluster distance and b the lowest mean distance to another cluster. It favors separated, compact shapes and depends on geometry; high scores do not establish causal or actionable segments. K-means struggles with elongated groups, unequal densities, and nonnumeric attributes.
Hard clustering assigns one label. A Gaussian mixture model instead estimates component membership probabilities. Full covariance permits rotated elliptical contours; diagonal covariance permits axis-aligned ellipses; spherical covariance is more restrictive. Probabilities describe uncertainty under the fitted mixture, not guaranteed real-world categories. Component count, covariance regularization, and initialization matter. Profiling summarizes typical behavior and deviations within groups; an unusual Gaussian score is a flag for investigation, not proof of fraud.
Reduce dimensions, preserve humility
PCA centers numeric data and finds orthogonal directions of greatest variance; scale first when units should not dictate importance. Truncated SVD approximates a matrix with fewer singular components and can operate on sparse text without centering. Latent factors can compress user–item preferences and improve speed or denoising, but lose information and interpretability. High variance or reconstruction quality does not guarantee predictive relevance. Fit transformations within training folds and validate the downstream task; latent factors are not discovered causal explanations.
Question: Would a higher silhouette guarantee better customer targeting?
No. Silhouette measures separation under the selected geometry. Targeting also requires useful outcomes, stable membership, operational feasibility, and evidence about intervention effects.
Question: Why can kNN fail after adding more features?
Irrelevant dimensions distort neighborhoods and concentrate distances. Scale, select features inside validation, consider dimensionality reduction, and reassess accuracy and latency together.
See leakage-safe validation, sparse text geometry, and profiling and link prediction.