Clustering and Anomaly Detection

Find structure in data that has no labels. Measure how alike observations are and scale features so that distances are fair, then group data with k-means, hierarchical clustering and DBSCAN. Choose the number of clusters with the elbow method and silhouette scores, read and cut dendrograms, and check whether clusters are stable and meaningful. Finally, detect anomalies with a Gaussian model of normal data, choose its threshold with precision, recall and F1, and design features that make unusual cases stand out.

IntermediateLesson 8 of 9 in Machine Learning Course

What you will learn

  1. Explain what clustering and anomaly detection do with unlabeled data, measure how alike two observations are, and scale features so that every distance means what you intend.
    • Explain what clustering and anomaly detection do with unlabeled data
      Distinguish unsupervised from supervised learning, describe the three families of clustering methods, and recognize the choices that shape every clustering.
    • Measure how alike two observations are
      Compute Euclidean, Manhattan, cosine and binary-matching measures, and choose a measure that matches what similar should mean for the data.
    • Scale and encode features before clustering
      Show how units and ranges distort distances, standardize or rescale features correctly, and decide which features and weights to use.
  2. Carry out the k-means algorithm by hand and in scikit-learn, explain why it converges and why it can stop at a poor solution, and recognize data for which k-means is a poor choice.
    • Run the k-means algorithm step by step
      Define the k-means objective and centroids, carry out assignment and update steps on a small data set, and explain why the cost never increases.
    • Use k-means in practice and know its limits
      Avoid poor local minima with restarts and k-means++, run k-means in scikit-learn, and recognize cluster shapes, sizes and outliers that k-means handles badly.
  3. Choose k with the elbow method and silhouette scores, then interpret, test and report clusters so that conclusions rest on groups that are real and useful.
    • Choose k with the elbow method
      Plot the k-means cost against k, find the elbow, and recognize when the curve or the purpose of the analysis has to decide.
    • Compute and read silhouette scores
      Calculate the silhouette of single points and of a whole clustering, use it to compare values of k, and know where it misleads.
    • Interpret, validate and report clusters
      Describe clusters in the original units, test whether they are stable, compare them with known labels when available, and report the analysis honestly.
  4. Merge observations step by step with different linkage rules, then read a dendrogram and cut it to obtain a chosen number of clusters.
    • Merge clusters with agglomerative clustering and linkage
      Carry out agglomerative clustering by hand with single, complete, average and Ward linkage, and explain how the linkage shapes the clusters.
    • Read and cut a dendrogram
      Read similarity from merge heights, cut the tree at a height or into a chosen number of clusters, and recognize when a nested hierarchy does not fit the data.
  5. Classify points as core, border or noise, build DBSCAN clusters by hand, tune eps and min_samples, and choose among k-means, hierarchical clustering and DBSCAN.
    • Classify points as core, border or noise
      Apply the DBSCAN definitions of neighborhood, core, border and noise points to form clusters by hand and in scikit-learn.
    • Tune DBSCAN and choose a clustering method
      Set min_samples and eps with rules of thumb and a k-distance plot, recognize DBSCAN's weaknesses, and match k-means, hierarchical clustering or DBSCAN to a problem.
  6. Model normal data with Gaussian densities, flag observations with low density, choose the threshold with labeled examples, and design features so that anomalies stand out.
    • Model normal data with Gaussian densities
      Estimate a mean and variance for each feature, combine the feature densities into p(x), and flag new observations whose density falls below a threshold.
    • Set the threshold and evaluate an anomaly detector
      Split normal and anomalous examples into training, validation and test sets, choose the threshold with precision, recall and F1, and avoid misleading accuracy figures.
    • Choose features and decide when to use anomaly detection
      Decide between anomaly detection and supervised learning, transform skewed features, add features that expose missed anomalies, and use the multivariate Gaussian for correlated features.

Clustering and Anomaly Detection study guide

6 chapters

1

Prepare data that reflects similarity

Clustering starts with a choice about what makes two observations alike. A group of documents may share a topic despite different lengths, while a group of machines may share a pattern of sensor readings. Learn how unlabeled data supports grouping and anomaly detection, then choose distances, scales, and feature encodings that express the similarity you care about. These choices shape the result before any algorithm runs.

1.1 Groups and unusual observations

A table can contain useful structure even when no row has a known answer. Clustering looks for groups of similar rows. Anomaly detection looks for rows that fit poorly with the normal data.

Learn without target labels

In supervised learning, each training input comes with a target label: an email is marked spam or not spam, for example. A classifier learns to predict that known category. Unsupervised learning receives the inputs without those labels. A cluster label such as 0, 1, or 2 is an output of the grouping process, not a supplied answer.

Those numbers have no rank or meaning by themselves. After grouping customers, describe each group's typical purchasing behavior and size before giving it a useful name. Swapping labels 0 and 1 leaves the groups unchanged. With no known grouping to compare against, judge compactness, separation, stability, and usefulness for the purpose.

Three ways to form groups
FamilyHow groups formMain choice
Centroid-basedPoints join a nearby centerNumber of groups
HierarchicalSuccessive merges form a nested treeLinkage and a tree cut
Density-basedConnected dense regions form clustersNeighborhood and density settings

k-means represents each group by its mean and needs the number of clusters in advance. Agglomerative hierarchical clustering builds the tree first; you select a level afterward. DBSCAN finds dense regions and can label isolated points as noise. Ordinary k-means and a flat cut of an agglomerative tree assign every observation to a group, even an observation that fits poorly.

Clustering can group articles by topic, genes by activity, or image pixels by color. Gaussian anomaly detection instead fits a density model to normal observations and flags low-density cases. Sensor readings that fit no normal operating pattern are candidates for inspection. A DBSCAN noise point offers a related signal: it lies outside the dense groups for the chosen settings.

A partition needs evidence

Ask k-means for four clusters in an evenly scattered square of points and it will still return a partition. The output alone does not establish four distinct types. Repeat the analysis and check whether useful, separated groups persist. Clusters describe the measured features; they do not explain what caused the differences.

Begin by stating the purpose, choosing and cleaning relevant features, and deciding how similarity should work. Then scale or encode those features, select a distance and algorithm, and compare reasonable settings. Finish by evaluating and profiling the groups in understandable units. Record those choices so someone else can reproduce the analysis.

Key Takeaways

  • A cluster label names a group; its numeric value has no rank.
  • Clustering groups observations; anomaly detection flags unusual ones.
  • k-means, hierarchical clustering, and DBSCAN form groups in different ways.
  • Check separation, stability, and purpose before interpreting a partition.

1.2 Distances that match the data

A distance is small for observations that should count as alike. The right measure depends on whether similarity means nearby values, matching directions, or shared presences.

Numeric distances

Euclidean distance is straight-line distance across the features:

d(x,z)=∑j=1p(xj−zj)2.

For (1,2) and (4,6), the differences are 3 and 4. Their squared differences sum to 25, so the distance is 5. Manhattan distance adds absolute differences, giving 7. It gives a large coordinate difference less relative weight than Euclidean distance does. They are the Minkowski distances with powers 2 and 1, respectively.

A metric is nonnegative, is zero exactly for identical vectors, is symmetric, and obeys the triangle inequality: a direct distance cannot exceed a route through a third point. Squared Euclidean distance preserves the ranking of pairs but fails this last rule. On the line at 0, 1, and 2, the squared direct distance is 4 while the two shorter squared distances add to 2. k-means still uses squared distances because its objective is a sum of squared deviations from means.

Profiles and directions

Cosine similarity compares vector directions:

cos⁡(x,z)=x⋅z∥x∥∥z∥.

Vectors (2,0,1) and (4,0,2) have cosine similarity 1 and cosine distance 0: their proportions agree despite different totals. This suits word-count profiles when document length should not determine the grouping. A zero vector has no direction, so handle empty documents before using cosine. Cosine similarity can be negative for signed features; nonnegative count vectors give values from 0 to 1.

Correlation-based distance is one minus the correlation between feature profiles. It captures matching rises and falls while allowing differences in overall level and scale. Choose it when a profile's pattern matters more than its magnitude.

Binary and mixed features

For binary vectors, let a count shared ones, d shared zeros, and b,c mismatches. With p=a+b+c+d:

MeasureSimilarityUseful when
Simple matching(a+d)/pOnes and zeros both matter
Jaccarda/(a+b+c)Shared absences add no evidence

For the purchase vectors (1,1,0,0,1,0) and (1,0,0,0,1,1), the counts are a=2,b=1,c=1,d=2. Simple matching is 4/6; Jaccard is 2/4. Two customers skipping the same rare item should not necessarily become more similar. For similarities from 0 to 1, subtracting from 1 gives a dissimilarity.

Mixed numeric and categorical data can use Gower distance. It averages feature-level dissimilarities: range-scaled absolute differences for numbers, and 0 for a categorical match or 1 for a mismatch. Another route is one-hot encoding with suitably weighted numeric features.

A distance matrix stores all pairwise dissimilarities. For a symmetric measure its diagonal is zero and there are n(n−1)/2 distinct off-diagonal pairs. Hierarchical clustering and silhouette calculations use these comparisons. Replacing one measure with another changes the neighbors and can change the groups.

Key Takeaways

  • Euclidean distance takes a square root; squared Euclidean distance does not.
  • Cosine compares direction; correlation compares centered profiles.
  • Jaccard ignores shared zeros; simple matching counts them.
  • Gower combines numeric and categorical dissimilarities.
  • A symmetric distance matrix has one distinct value per unordered pair.

1.3 Scaling and encoding features

Distance combines feature differences as numbers. Without deliberate scaling, the feature with the largest numeric spread can control the result, even when its unit is arbitrary.

Watch units change the neighbors

Consider customers P = (25 years, 2,000 MB), Q = (60 years, 2,050 MB), and R = (26 years, 3,000 MB). In raw units, P is about 61 from Q but 1,000 from R. Change MB to GB and the distances become about 35 and 1.41. The nearest neighbor reverses although the customers have not changed.

Standardization expresses a feature in standard deviations from its mean:

z=x−xˉs.

Suppose age has standard deviation 15 years and data use has standard deviation 500 MB. For P and Q, the scaled differences are 35/15 and 50/500; their distance is about 2.33. For P and R, the differences are 1/15 and 1,000/500; their distance is about 2.00. Both features now contribute on comparable scales.

Pick a scale for the purpose
ScalingCalculationMain consideration
Standard(x−xˉ)/sMean and spread react to extremes
Min–max(x−min⁡)/(max⁡−min⁡)One extreme stretches the range
Robust(x−median)/IQRLess affected by a few extremes

A constant feature has no spread; remove it or handle it before dividing by its spread. Scaling each feature is useful when units differ, but raw differences can already be meaningful. Pixel color channels share a scale, and map coordinates in kilometers describe one geometric space. Scaling their axes independently can change the intended geometry.

Scaling sets weights. Multiplying a standardized feature by 3 multiplies its contribution to squared Euclidean distance by 9. Several near-duplicate features also give one aspect extra weight. Irrelevant features add differences that can hide useful structure.

Encode categories and keep the transformation

One-hot encoding gives a category its own 0/1 column. Two different categories differ in two columns, giving Euclidean distance 2 for that categorical block. Check the block's weight against numeric features, especially after further scaling. Arbitrary integer category codes would create an ordering and spacing that the categories do not have.

Learn all transformation settings from the data used to fit the model. Apply those same settings to new observations; do not fit a fresh scaler to each incoming batch. In Python, scaler.fit(X_train) learns the settings and scaler.transform(X_new) reuses them. A Pipeline keeps scaling and clustering together.

When clusters feed a predictive model, reserve validation and test data before fitting the scaler or clustering. Otherwise their feature values influence the training representation. Standardization changes feature contributions while preserving the order of values within each nonconstant feature.

Key Takeaways

  • Units can change raw distances and nearest neighbors.
  • Use fitted scaling values again for new observations.
  • A feature multiplier is squared in its squared-distance contribution.
  • Choose relevant features and inspect categorical-block weights.
  • Fit preprocessing on training data when clusters feed a predictive model.
2

Group observations with k-means

k-means alternates two simple operations: assign points to nearby centers, then move the centers to the means of their assigned points. Follow the changes in a small data set and connect them to the squared-distance objective. Then use restarts and explicit Python settings to obtain repeatable results, and learn which shapes and outliers can make a low-cost solution misleading.

2.1 Assignments, means, and falling cost

k-means places observations into a chosen number of groups. Each group has a centroid, the mean of its members feature by feature, which may lie between observed points.

The quantity being minimized

The objective is the within-cluster sum of squares:

J=∑i=1n∥x(i)−μc(i)∥2.

For each point, select its assigned centroid, square their Euclidean distance, and add the results. scikit-learn calls this sum inertia_. Dividing by the number of observations gives an average distortion with the same minimizing partition.

Lloyd's algorithm chooses a cluster count and starting centroids, then repeats:

  1. Assign: send each point to its nearest centroid.
  2. Update: replace each centroid with the mean of its assigned points.

Stop when assignments no longer change or the centroid movement meets the chosen tolerance.

Follow two passes

Use A = (1, 1), B = (2, 1), C = (1, 2), D = (5, 4), E = (6, 5), and F = (5, 5), with two starting centers at A and B. C joins A because its distances are 1 and about 1.41. D, E, and F join B; D, for example, is about 4.24 from B and 5 from A.

The first assignment gives {A, C} and {B, D, E, F}, with cost 76. Their means are (1, 1.5) and (4.5, 3.75). Moving to those means lowers the cost to 20.25.

Now B is about 1.12 from the first mean and 3.72 from the second. It switches groups. With the centers temporarily fixed, the cost falls to 7.6875. Recompute the means:

μ1=(4/3,4/3),μ2=(16/3,14/3).

The cost becomes 8/3≈2.67. Another assignment changes nothing, so these groups are stable under the two operations.

Why the operations work

With fixed centers, choosing the nearest one cannot increase a point's squared distance. With fixed memberships, the mean minimizes the group's sum of squared distances. Each operation therefore leaves the objective unchanged or lowers it. The ordinary algorithm reaches a stable solution, but different starts can reach different local minima. A stable result need not be the globally smallest possible cost.

Statistics texts also measure a cluster's variation by W(C)=∣C∣−1∑i,i′∈C∥xi−xi′∥2, with ordered pairs. This equals twice its centroid-based sum of squares, so minimizing the total gives the same partition.

If a cluster becomes empty, its mean cannot be computed. Implementations need an explicit repair: restart the center or drop the cluster. scikit-learn relocates an empty center using a point far from its current assigned center. A rising cost during ordinary assignment and mean updates should prompt a check of the calculations and unchanged input data.

Key Takeaways

  • The centroid is the feature-by-feature mean.
  • Assignment and mean updates each leave cost unchanged or lower it.
  • Convergence gives a stable solution, which can be a local minimum.
  • Inertia is a sum of squared distances, not a sum of distances.
  • Empty clusters need an explicit repair.

2.2 Reliable starts and suitable data

Starting centers matter because k-means improves its current partition without searching every possible partition. Use several starts and inspect whether the resulting groups fit the data's shape.

Escape a poor start

For the values 0, 2, 10, 12, 20, and 22 with three clusters, starting at 0, 2, and 16 can settle at {0}, {2}, and {10, 12, 20, 22}. The cost is 104 and neither ordinary step improves it. Starting at 1, 11, and 21 gives three pairs with total cost 6.

Random restarts run the algorithm from several sets of starting centers and keep the smallest cost. Compare runs with the same observations, scaling, and cluster count. A seed makes a run repeatable; several seeds test sensitivity to initialization.

k-means++ spreads the initial centers. Pick the first randomly, then select each further center with probability proportional to its squared distance from the nearest existing center. scikit-learn uses a greedy variant by default. This improves initialization without guaranteeing the global optimum.

Run it with explicit settings
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(
    StandardScaler(),
    KMeans(n_clusters=3, n_init=10, random_state=0),
)
model.fit(X_train)
labels = model[-1].labels_
centers = model[-1].cluster_centers_
inertia = model[-1].inertia_
new_labels = model.predict(X_new)

The centers are in standardized units. Convert them back with the fitted scaler for interpretation. Since scikit-learn 1.4, n_init='auto' is the default; with k-means++ it runs one initialization. Set an integer explicitly when you want several starts. Label numbers can swap between runs while membership remains identical.

Recognize a poor fit
Data featureWhy k-means can struggle
Curved or ring-shaped groupsNearest-center boundaries are flat
Very different group spreadsOne broad group may split while others merge
Extreme observationsSquared deviations pull means strongly
A custom dissimilarityThe arithmetic mean may be the wrong center

The values 0, 2, and 100 have mean 34. One extreme value pulls the center far from the two ordinary observations. Inspect outliers, or consider DBSCAN for noise handling and k-medoids for centers that are actual observations. Standard k-means is tied to squared Euclidean geometry; substituting Manhattan or Jaccard distance leaves its mean update unjustified.

A useful non-grouping application is color quantization. Treat RGB pixels as observations and replace each color with its centroid's color. A 128 × 128 image at 24 bits per pixel uses 393,216 bits. A 16-color palette uses 384 bits for the colors plus 65,536 bits for 4-bit pixel indices: 65,920 bits before other file overhead. The palette trades color detail for storage.

Key Takeaways

  • Keep the lowest-cost restart for fixed data, scaling, and cluster count.
  • k-means++ improves starting centers without ensuring the global optimum.
  • Set restarts and the seed explicitly in code.
  • Flat assignment boundaries suit compact, roughly round groups.
  • Outliers can pull means far from typical observations.
  • Standard k-means requires squared Euclidean geometry.
3

Choose a cluster count and assess the groups

A smaller k-means cost can come from adding more groups, so cost alone cannot choose a useful cluster count. Read the change in cost, compare within-group and between-group distances, and check whether the resulting memberships persist. Interpretation adds another test: the profiles should make sense in the original units and serve the purpose of the analysis. A clear report records both the choices and the evidence.

3.1 Finding the elbow in the cost curve

Adding centers gives k-means more freedom to fit the data. The lowest achievable cost cannot increase as the cluster count grows, and one center per observation gives cost zero. A rule that simply picks the smallest cost would keep adding clusters.

Look at the reductions

The elbow method looks for a change from large reductions to small ones. Run k-means with several initializations for each candidate count, keeping the input features and scaling fixed. Plot the best inertia against the count.

For counts 1 through 6, suppose inertias are 1,000, 520, 210, 180, 160, and 145. The successive reductions are:

Change in countCost reduction
1 to 2480
2 to 3310
3 to 430
4 to 520
5 to 615

The reduction from two to three clusters is still substantial. The next reduction is only 30, so three clusters is the elbow candidate. It is the count just before the improvements flatten, not the count with the largest absolute reduction from its predecessor.

Build a comparable curve
from sklearn.cluster import KMeans

inertias = []
for k in range(1, 7):
    fit = KMeans(n_clusters=k, n_init=20,
                 random_state=0).fit(X_scaled)
    inertias.append(fit.inertia_)

Fit the scaler once for this comparison. Changing scaling between runs changes the objective's geometry and breaks the comparison. The numeric size of inertia also depends on observation count and feature units, so a cost of 200 on one data set cannot be ranked against 100 on another as a statement about cluster quality.

The theoretical minimum decreases or stays flat, but fitted runs can land at different local minima. If the curve rises at a larger count, rerun that count with more initializations before interpreting the bend. The increase signals a fitting problem, not evidence that extra centers intrinsically raise the best possible cost.

When no bend is clear

Some data gives a smooth curve. Do not manufacture a sharp elbow by staring at a small change. Compare silhouette values, membership stability, and practical constraints. The gap statistic offers another comparison: it contrasts observed cost with cost expected from data without cluster structure.

A clothing manufacturer may need three sizes or five sizes. More groups improve fit but add production and stocking costs. The chosen count can serve that operational choice even when no unique natural count exists. Keep the evidence distinct: a visible elbow supports a count from the data; a fixed number of available size categories supports it from the purpose.

Key Takeaways

  • The lowest achievable inertia cannot increase with the cluster count.
  • An elbow is where large reductions become small.
  • A rising fitted cost calls for better restarts.
  • Use other evidence when the curve has no clear elbow.

3.2 Comparing cohesion with separation

A silhouette asks whether a point is closer to its own group than to competing groups. It uses average distances, which prevents a single nearby point from standing in for a whole neighboring cluster.

Compute the two averages

For point i, let a(i) be its mean distance to the other members of its own cluster; exclude the point itself. For every other cluster, compute the mean distance to all its members. The smallest of those means is b(i).

s(i)=b(i)−a(i)max⁡{a(i),b(i)}.

Using the largest of the two means in the denominator keeps the score between −1 and 1. Near 1 means good separation, near 0 means little preference between groups, and a negative value means another group is closer on average. A singleton cluster receives zero by convention.

Work one point through

Take clusters {1, 2, 3} and {8, 9}. For point 3, its own-cluster distances are 2 and 1, so a=1.5. The other-cluster distances are 5 and 6, so b=5.5. Therefore s=(5.5−1.5)/5.5≈0.727.

Across all five points, the silhouettes are about 0.800, 0.846, 0.727, 0.833, and 0.857. Their mean is about 0.813. If the partition becomes {1, 2} and {3, 8, 9}, point 3 instead has a=5.5 and b=1.5, giving about −0.727. Its assignment is now poorly supported by distances.

Compare counts and inspect the plot

A mean silhouette summarizes all observations. Compare candidate counts on the same features and measure. In the example, splitting into {1, 2}, {3}, and {8, 9} lowers the mean to about 0.427. The two-group result is better supported.

The mean can hide a weak cluster. A silhouette plot groups and sorts individual bars by cluster. Look for many negative bars or a whole cluster below the overall mean. Bar-block thickness shows cluster size; unexpected size imbalance deserves investigation, though unequal groups can be meaningful.

from sklearn.metrics import silhouette_score, silhouette_samples

mean_score = silhouette_score(X_scaled, labels)
point_scores = silhouette_samples(X_scaled, labels)

Silhouette requires at least two labels and fewer labels than observations. Use a random sample for a large data set because pairwise distances are expensive. Keep the distance measure consistent with clustering.

Match the score to the geometry

Silhouette favors compact, separated groups. Two interlocking crescents may be correctly recovered by DBSCAN yet score poorly because distances cut across the curves. Inspect the geometry before ranking algorithms by this number. For DBSCAN, state whether noise was excluded or treated as a label; the choice changes what the score evaluates. A noise label is not a discovered dense cluster.

Key Takeaways

  • Compute the nearest other cluster by mean distance, not by its nearest point.
  • Positive, near-zero, and negative silhouettes indicate different membership support.
  • Singletons score zero; a one-cluster result cannot be scored.
  • Inspect per-cluster bars as well as the overall mean.
  • Silhouette can underrate meaningful curved clusters.

3.3 Profiles, stability, and a clear report

A useful clustering needs both a readable description and evidence that it survives reasonable analysis choices. Begin with what the members look like in familiar units.

Turn centers into profiles

Report each group's size and the mean or median of every important feature. If a standardized centroid has coordinate z, invert it using the fitted feature mean and standard deviation:

x=xˉ+zs.

With age mean 40 years and standard deviation 15 years, a coordinate of −0.8 corresponds to 28 years. With data-use mean 2,500 MB and standard deviation 500 MB, a coordinate of 1.2 corresponds to 3,100 MB. The group can be described as "younger customers with high data use"; its arbitrary numeric label adds no explanation.

A centroid is a mean, so inspect medians and unusual members too. An isolated point forced into a k-means or hierarchical group can distort its average. Very small clusters and negative silhouettes are useful places to look for errors or anomalies.

Ask whether membership persists

Rerun with different random seeds. Repeat on random subsamples, such as 80% of the observations, and compare memberships for the observations shared between runs. Compare nearby cluster counts and other reasonable choices of scaling or distance. Persistent groups offer stronger evidence than groups that dissolve with a small change.

Compare memberships, not raw label numbers: labels may swap. A repeatable seed gives reproducibility of one run; stability asks whether the pattern survives changing the seed or sample.

Internal evaluation uses only the input data and partition, as inertia and silhouette do. External evaluation compares a partition with known labels. The adjusted Rand index equals 1 for identical groupings and is near 0 for chance-level agreement. A low score can mean the clusters capture a different pattern from the supplied categories; examine the intended purpose before judging.

Keep evaluation data independent

If cluster assignments become features for a predictive model, fit the scaler and clustering using training observations alone. Apply the fitted transformation and nearest-center assignment to validation and test observations. Their labels need not be present for leakage to occur: their feature values can already change the learned representation.

Clustering describes patterns in measured features of a sample. It does not establish causes or discrete types in a population. Even a method that always partitions the data needs independent evidence that its groups are useful.

Make the analysis reproducible

A report should state:

  • The purpose, selected features, cleaning, and scaling.
  • The distance, algorithm, and settings: count or density parameters, linkage, restarts, and seed as applicable.
  • Evaluation scores and how they were calculated, including any noise handling.
  • Each group's size and profile in original units.
  • Stability findings and analysis choices that changed the result materially.

Key Takeaways

  • Profile groups in original units and report their sizes.
  • Stability concerns membership across reasonable changes.
  • Internal and external scores answer different questions.
  • Cluster features for a later model must be fitted on training data alone.
  • A report needs settings and evidence as well as group names.
4

Build a tree and choose its cut

Hierarchical clustering records how observations combine, keeping the small groups inside the larger ones. The linkage rule decides which clusters count as close and can change the entire tree. Work through several rules, then read merge heights and choose a cut. The resulting dendrogram gives a view of nested structure, with a different tradeoff from fitting an independent k-means solution for each cluster count.

4.1 Merging clusters with linkage rules

Agglomerative clustering starts with one cluster per observation. It merges the closest pair, updates the distances between clusters, and repeats until all observations belong to one cluster. A full tree on n observations contains n−1 merges. Divisive clustering starts together and splits downward instead.

Define distance between groups
LinkageDissimilarity used for the next merge
SingleSmallest cross-cluster point distance
CompleteLargest cross-cluster point distance
AverageMean of all cross-cluster point distances
CentroidDistance between cluster means
WardIncrease in total within-cluster squared error

Use values A = 0, B = 1, C = 4, D = 9, and E = 11. Single, complete, and average linkage first merge A with B at 1, then D with E at 2. Next C joins {A, B}, but the height depends on the rule: 3 for single, 4 for complete, and 3.5 for average. The final merge heights are 5, 11, and about 8.33, respectively. Average linkage uses all six distances across the final groups, whose sum is 50; averaging just a representative pair would apply a different rule.

Ward tracks added squared error

For clusters with sizes n1,n2 and means m1,m2, the increase is

ΔJ=n1n2n1+n2∥m1−m2∥2.

Merging A and B adds 0.5. Merging D and E adds 2. C joining {A, B} adds about 8.17, and the last merge adds about 83.33. These increases sum to 94, the squared error of all five values about their mean. Ward needs Euclidean geometry. Software heights may transform this increase, so check the convention before interpreting a height as added error.

What the rule changes

Single linkage can chain through a series of close pairs, following curved shapes but also joining groups through narrow bridges. Complete linkage and Ward favor compact groups; average linkage balances pairwise distances. Ward and k-means both use squared error, but hierarchical merges are greedy and never undone. They need not produce the same partition.

Centroid linkage can have an inversion, where a later merge has a lower height. This creates a downward step in the tree. With their usual valid distance settings, single, complete, average, and Ward do not have these inversions.

Exact unrestricted hierarchical clustering is costly for large samples. There are n(n−1)/2 pairs: 49,995,000 at 10,000 observations. Many implementations store pairwise distances, although some compute them as needed. A small or medium sample is often more practical.

from scipy.cluster.hierarchy import linkage
Z = linkage(X_scaled, method="average", metric="euclidean")

SciPy returns the merge history. In scikit-learn, AgglomerativeClustering(n_clusters=3, linkage='ward') returns flat labels. Single, complete, and average linkage can use measures such as Manhattan or cosine; Ward requires Euclidean distance.

Key Takeaways

  • Linkage defines how distances between whole clusters are calculated.
  • Single linkage can chain; complete and Ward favor compact groups.
  • Ward chooses the smallest increase in total squared error.
  • An early hierarchical merge is never undone.
  • Centroid linkage can produce a later merge at a lower height.
  • Pairwise comparisons can make exact hierarchy expensive on large samples.

4.2 Reading merge heights and cutting the tree

A dendrogram draws the merge history with observations as leaves. A horizontal bar joins two branches at their merge height. Read the height where two observations first share a branch to find their tree-based dissimilarity.

The horizontal order can change

Either branch below a merge can be rotated without changing memberships or heights. A five-leaf binary tree has four merges and 16 possible branch orientations. Two leaves drawn side by side can still join only near the top.

For A = 0, B = 1, C = 4, D = 9, and E = 11, complete linkage merges at heights 1, 2, 4, and 11. C can appear beside D on the page even though their first common merge is at 11. Horizontal spacing is a drawing choice, not a distance scale.

Count branches at a cut

Imagine a horizontal line through the tree. Every branch it crosses represents one cluster at that height. In this complete-linkage example:

Cut heightGroups
Below 1{A}, {B}, {C}, {D}, {E}
3{A, B}, {C}, {D, E}
6{A, B, C}, {D, E}
Above 11{A, B, C, D, E}

The largest merge gap is between 4 and 11. Cutting inside it gives two groups and is a useful candidate. Compare that cut with silhouettes, stability, and the purpose of the analysis. A long gap is evidence of separation within this tree, not a separate estimate of how many observations exist.

If distinct merges have the same height, a horizontal cut can pass through several at once and skip a cluster count. Centroid inversions also complicate a simple height cut. Inspect these features before assuming every requested count is available from a horizontal line.

Nested groups are a constraint

Raising a cut only joins existing groups; it never moves one member alone to a different branch. Every higher group is a union of lower ones. This helps reveal relationships at several scales, but a sample's best two-group and three-group solutions may not be nested. Independently fitting k-means at each count can reorganize memberships in a way one tree cannot.

The cophenetic distance between two observations is their first common merge height. Cophenetic correlation compares all these tree distances with the original pairwise distances. A value near 1 means the tree preserves those distances faithfully; it does not choose the cut by itself.

Draw and cut in Python
from scipy.cluster.hierarchy import dendrogram, fcluster

dendrogram(Z)
labels = fcluster(Z, t=6, criterion="distance")
labels_at_most_two = fcluster(Z, t=2, criterion="maxclust")

The distance cut uses a dissimilarity threshold. maxclust asks for no more than the requested number of clusters, so check the actual count returned. Always record linkage and distance. Single, complete, and average heights reflect their specified distances; Ward heights use a different convention. Compare heights inside one tree, not as interchangeable values across linkages or programs.

Key Takeaways

  • Merge height shows when observations join; leaf spacing does not.
  • A horizontal cut groups the branches it crosses.
  • Higher cuts join lower clusters into nested groups.
  • Tied merge heights can skip cluster counts under a height cut.
  • Cophenetic correlation measures how well tree distances match original distances.
5

Find dense regions and isolated points

DBSCAN builds groups by following dense neighborhoods, allowing a cluster to bend or stretch and leaving isolated observations as noise. Learn the difference between core, border, and noise points, then trace how connected core points form a group. Choosing a radius and minimum neighborhood count takes care: units, feature count, and differences in density all change what one pair of settings can recover.

5.1 Core points build DBSCAN clusters

DBSCAN groups connected dense regions. It does not require a cluster count, and it can leave points outside all clusters. Two parameters define local density: a radius, eps, and a minimum neighborhood count, min_samples.

Count the point itself

A neighborhood contains every observation whose distance from a point is at most eps, including that point. In the ordinary unweighted setting:

  • A core point has at least min_samples observations in its neighborhood.
  • A border point is not core but lies within eps of a core point.
  • A noise point is neither core nor within eps of any core point.

Count every neighborhood before deciding which low-count points are border. A low count alone only establishes that a point is not core.

Classify a small sample

Use values 1, 2, 3, 4.2, 10, 11, 11.6, and 20, with eps=1.5 and min_samples=3.

ValueNeighborhood countRole
12Border
23Core
33Core
4.22Border
102Border
113Core
11.62Border
201Noise

For instance, 3 sees 2, 3, and 4.2. The point 4.2 sees only 3 and itself, but it lies beside core point 3, so it is border. Point 20 has no core neighbor and stays noise.

Connect through core points

Core points 2 and 3 are within the radius, so they belong to one component. Attach their border points 1 and 4.2 to obtain {1, 2, 3, 4.2}. Core point 11 and its border points form {10, 11, 11.6}. The remaining point is noise.

The radius bounds each neighborhood, not the whole cluster. A chain of neighboring core points can extend far beyond eps, following a ring or curved region. Border points attach to a core component but do not extend it by forming a chain of non-core points. Two dense components remain distinct even if a non-core point lies within the radius of both; that shared border point can be assigned to whichever component reaches it first. Core membership and noise status are unchanged by input order for fixed distances and settings.

Inspect the Python output
from sklearn.cluster import DBSCAN

fit = DBSCAN(eps=0.5, min_samples=5).fit(X_scaled)
labels = fit.labels_
core_indices = fit.core_sample_indices_

The returned labels use −1 for noise and nonnegative numbers for clusters. fit_predict also returns these training labels; scikit-learn DBSCAN has no predict method for incoming observations. Fit and scale with the intended distance units. Noise points are candidates for anomaly review: their role says they are isolated under these settings, not why they are isolated.

Key Takeaways

  • Neighborhood counts include the point itself.
  • A low-count point is border only when it has a core neighbor.
  • Connected core points form clusters, with border points attached.
  • The radius limits neighborhoods, not cluster diameter.
  • A border point cannot connect two core components.
  • DBSCAN labels noise as −1 and has no new-point predict method.

5.2 Choosing density settings and a method

DBSCAN replaces the cluster-count choice with a neighborhood-radius and density choice. Those settings determine which structure the method can see.

Start with the density count

A useful starting value for min_samples is about twice the number of features and at least 3. Larger or noisier data may need more. Raising this count requires denser local support and generally increases noise. It is a starting heuristic, not a universal best setting.

To choose eps, make a k-distance plot. For each observation, find the distance to its (min_samples − 1)-th nearest other observation. Sort these distances in increasing order. Look near the knee where the curve starts rising sharply; points beyond it need larger radii to meet the core criterion.

from sklearn.neighbors import NearestNeighbors

m = 6
neighbors = NearestNeighbors(n_neighbors=m).fit(X_scaled)
distances, indices = neighbors.kneighbors(X_scaled)
k_distances = sorted(distances[:, -1])

Supplying the training matrix as the query includes each point itself among the returned neighbors. The last column therefore gives the distance to the fifth other neighbor when the minimum count is 6.

Check the resulting groups

With values 1, 2, 3, 4.2, 10, 11, 11.6, and 20 and minimum count 3, a radius of 1.0 leaves 4.2 and 20 as noise. At 1.5, 4.2 joins the first group. At 6, all points except 20 merge into one cluster. Increasing the radius can turn noise into border or core points and can connect formerly separate dense components.

Inspect the noise share and the largest cluster's share. Nearly everything as noise suggests the radius may be too small; nearly everything together suggests it may be too large. Compare nearby settings and inspect the data geometry before settling on a value.

Know when one radius is insufficient

Clusters with very different densities may need incompatible radii. A small radius loses the sparse group; a large one can connect the dense group to unwanted surroundings. HDBSCAN is an alternative designed for varying densities and is available in scikit-learn from version 1.3. With many features, distances become less distinct and density becomes harder to judge; relevant feature selection helps.

Coordinates also need suitable geometry. For latitude and longitude, use radians with metric='haversine'. A 0.5 km radius becomes about 0.5/6371≈7.85×10−5 radians using a 6,371 km Earth radius.

Match the method to the purpose
NeedUseful starting method
Large numeric sample; compact groups; assign new pointsk-means
Small or medium sample; custom dissimilarity; nested structureHierarchical clustering
Irregular dense regions; isolated points should remain noiseDBSCAN

A few hundred documents with a custom distance may suit a hierarchy. Dense taxi-pickup hot spots with irregular shapes may suit DBSCAN. Compare reasonable methods using profiles and stability as well as scores; their different geometry can make one score an incomplete comparison.

Key Takeaways

  • Use a k-distance knee as a starting radius, then inspect the result.
  • Match the neighbor rank to counting the query point itself.
  • Check both the noise share and the largest cluster share.
  • One radius can struggle with very different densities.
  • Choose the algorithm for geometry, sample size, and assignment needs.
6

Detect observations that fit normal data poorly

A Gaussian detector learns the shape of normal measurements, then assigns a density to each new observation. Low density signals a case to inspect. Work from feature means and variances to a combined score, choose the flagging threshold with labeled validation examples, and test it independently. Feature design matters especially when unusual relationships between ordinary-looking measurements reveal the fault.

6.1 Fitting and scoring a Gaussian detector

Gaussian anomaly detection estimates a model of normal data. A new observation is flagged when its estimated density falls below a chosen threshold: p(x)<ε.

Estimate each feature's bell curve

For a feature with mean μ and standard deviation σ, the Gaussian density is

p(x;μ,σ2)=12πσexp⁡(−(x−μ)22σ2).

The curve is highest at its mean and decreases toward both tails. About 68%, 95%, and 99.7% of normal values fall within one, two, and three standard deviations. Fit each feature on observations known or believed to be normal.

For m training values, estimate

μj=1m∑ixj(i),σj2=1m∑i(xj(i)−μj)2.

The variance here divides by the training count, giving the maximum-likelihood estimate. Sample variance in descriptive statistics divides by one less; do not mix the two conventions inside a calculation.

Five engines have temperatures 70, 72, 74, 76, and 78 °C. Their mean is 74 °C and their squared deviations sum to 40, giving variance 8 °C². Vibration readings 2.0, 2.2, 2.4, 2.6, and 2.8 mm/s give mean 2.4 and variance 0.08. The sample-variance alternatives are 10 and 0.1.

Combine the densities

The product model treats features as independent:

p(x)=∏jp(xj;μj,σj2).

At 75 °C and 3.4 mm/s, the engine's feature densities are about 0.1325 and 0.00272. Their product is about 0.00036, below a threshold of 0.001, so the engine is flagged. At 80 °C and 2.4 mm/s the product is about 0.0210, above that threshold.

Several moderately unusual feature values can jointly make the product small. The model does not require one extreme feature. However, its independence structure misses relationships: two values can each look ordinary while their combination breaks a strong normal correlation.

Density is not point probability

Density has units. A continuous variable has probability associated with an interval, not the density height at an exact point. The vibration density at its peak is about 1.41 per mm/s; a density above 1 is valid. Changing feature units changes the density scale, so the numeric threshold belongs to the fitted model and representation.

The same ranking has a simpler view. Within one fitted product model, log density is a constant minus half the sum of squared z-scores. The two example engines have squared-z sums 12.625 and 4.5. A larger sum corresponds to lower density and greater unusualness. Summing log densities also avoids numerical underflow from multiplying many small numbers. A zero estimated variance needs handling before using the density formula.

Key Takeaways

  • Fit means and variances from normal training observations.
  • Maximum-likelihood variance divides by the training count.
  • Multiply independent feature densities, or sum their logarithms.
  • Flag a point when its density is below the threshold.
  • Density can exceed 1 and changes with feature units.
  • The product model cannot represent feature correlations.

6.2 Choosing a threshold with validation data

A fitted density model still needs a decision threshold. A few labeled anomalies help choose that threshold and measure whether the flags are useful.

Separate fitting, choosing, and testing

One possible allocation of 10,000 normal engines and 20 faulty engines is:

SplitNormalFaultyPurpose
Training6,0000Fit the density model
Validation2,00010Choose the threshold
Test2,00010Evaluate the final detector

Inspect and remove obvious anomalies before fitting the normal model. Extreme training anomalies can move the mean and inflate variance, making faults look ordinary. Fit preprocessing on training data too, then apply it consistently to the remaining splits.

Try thresholds on validation scores, select using the chosen performance criterion, and evaluate once on the untouched test set. Repeated threshold changes based on test results turn that set into tuning data and make its performance optimistic.

Count the outcomes that matter

Let true positives be real anomalies flagged, false positives be normal observations flagged, and false negatives be anomalies missed.

P=TPTP+FP,R=TPTP+FN,F1=2PRP+R.

Precision asks how many flags are genuine. Recall asks how many real anomalies are caught. F1 is their harmonic mean and is low if either is low.

Suppose 12 validation engines are flagged and 8 are faulty. There are 10 faulty engines in total, so TP=8,FP=4,FN=2. Precision is about 0.667, recall is 0.8, and F1 is about 0.727. A threshold that flags all 10 faults plus 40 normal engines reaches recall 1 but precision 0.2, giving F1 about 0.333.

Accuracy hides this tradeoff. Flagging nothing gets 2,000 of 2,010 validation cases right, about 99.5%, yet catches no faults.

Choose for the consequences

Raising the density threshold admits more points into the condition p(x)<ε. More observations are flagged, recall cannot decrease on the same labeled sample, and precision usually falls. Lowering the threshold makes flags more selective. Precision need not change monotonically because the newly added cases can include different mixes of normal and anomalous observations.

Maximum F1 is a useful balanced choice, but consequences can call for another criterion. If missing a fault is much more costly than an extra inspection, prefer high recall at an acceptable precision. With almost no labeled faults, a low percentile of normal training densities can set an initial flag rate, such as 1%. Expert review of flags can then provide labels for better tuning. This detector learns normality; it can flag kinds of fault absent from the training examples.

Key Takeaways

  • Fit on normal data, tune on validation data, and evaluate on test data.
  • Precision measures flag reliability; recall measures anomalies caught.
  • F1 balances precision and recall, while accuracy can hide missed anomalies.
  • A higher density threshold flags more observations.
  • Choose the threshold for the cost of missed faults and false alarms.

6.3 Features that expose unusual relationships

A detector can miss a real fault when its features do not make that fault unusual. Inspect validation errors to decide whether a transformation, a new feature, or a different normal model is needed.

Decide which learning task fits

Anomaly detection is useful when normal observations are plentiful, labeled anomalies are rare, and future anomalies may differ from those already seen. Supervised learning is useful when enough labeled positives exist and future positives resemble them. A known manufacturing defect with many examples may support classification; a new machine failure may be better caught by departures from normal operation.

Inspect feature distributions

Plot histograms before fitting bell curves. For strongly skewed positive measurements, a logarithm, square root, or cube root can give a more suitable distribution. Values 1, 10, 100, and 1,000 become 0, 1, 2, and 3 under a base-10 logarithm. For zeros, a suitable positive offset permits a log transformation. Apply the chosen transformation identically to training, validation, test, and incoming data, and reassess the fitted density and threshold.

Multiplying a feature by a constant changes its mean and spread by the same scale, so its z-scores and unusualness ranking stay the same. A nonlinear transformation changes the distribution's shape and can change that ranking. Scaling and transformation therefore play different roles.

Look at missed faults

CPU load and network traffic normally rise together on a server. A reading of 90% CPU with almost no traffic can be unusual as a pair even if each value lies within its own usual range. The product Gaussian has no correlation term to recognize the broken relationship. A CPU-to-traffic ratio can expose the mismatch as an extreme feature. Define behavior near zero traffic before using the ratio.

A multivariate Gaussian models these relationships through a covariance matrix:

p(x)=exp⁡(−D2/2)(2π)n/2∣Σ∣1/2,D2=(x−μ)⊤Σ−1(x−μ).

Here μ is the mean vector, Σ describes variances and covariances, and D2 is squared Mahalanobis distance. A point far from the normal relationship has a large distance even if its individual coordinates are ordinary. A diagonal covariance matrix reduces this to the product model's sum of squared z-scores.

Check whether the model can be estimated

Full covariance needs many more observations than features and an invertible matrix. A duplicated feature or exact combination such as x3=x1+x2 makes it singular. With limited data, a product model and a useful relationship feature may be more practical.

A single bell curve can also misrepresent several normal modes. If a machine normally runs idle or at full load, the fitted mean can lie in a rarely visited gap and give it the highest density. Faults there may be missed; a high threshold may instead flag normal outer values. Group the normal modes and model them separately, or consider a density-based method. Choose improvements from validation errors, keeping the test set for the final assessment.

Key Takeaways

  • Use supervised learning when positive examples are sufficient and representative.
  • Transforms can make skewed features more suitable for a Gaussian model.
  • Validation misses can reveal a useful ratio or relationship feature.
  • Full covariance detects departures from normal feature relationships.
  • Exact feature dependence makes the covariance matrix singular.
  • Several normal modes can make one Gaussian misleading.

Clustering and Anomaly Detection examples

6 Walkthroughs

1

Decide what similar means

13 steps
Move from unlabeled observations to a distance and representation that suit the purpose.
  1. 1
    IntroductionStart with the grouping purpose

    A collection of machine readings has no supplied group labels. You want groups that reflect operating behavior, and you also want to notice unusual readings. Before fitting a model, decide which measurements should make two machines similar. We will connect that choice to distances, feature scales, and the meaning of the returned groups.

  2. 2
    ExplanationInputs without category answers

    A supervised classifier receives examples with known targets, such as faulty or normal. Clustering receives the feature values without target group labels and creates a partition. A returned cluster number is a name for a group, not an answer supplied during training. You still need to describe the members to understand what that group represents.

  3. 3
    ConnectionChoose a grouping family

    k-means represents each group with a center and needs a cluster count. Hierarchical clustering records nested merges and lets you choose a tree cut afterward. DBSCAN follows connected dense regions and can leave points as noise. Gaussian anomaly detection fits normal density and flags low-density readings; it asks about unusualness rather than producing a partition.

  4. 4
    ChallengeWhat does a returned partition establish?

    A k-means fit splits uniformly scattered points into three groups. Has it established three distinct natural types?

    ---reveal---

    No. It was asked to return three groups and can partition even data without separate groups. Check separation, membership stability, and usefulness. The labels describe the chosen representation and settings; interpreting the partition requires evidence beyond the existence of those labels.

  5. 5
    ExampleWork a numeric distance

    Compare vectors (2,1) and (5,5). Their feature differences are 3 and 4. Euclidean distance squares these differences, adds 9 and 16, then takes the square root to give 5. Manhattan distance adds the absolute differences to give 7. The same pair therefore has different numerical dissimilarities under different rules.

  6. 6
    ExplanationWhen direction matters more than length

    Word-count vectors (1,2) and (3,6) describe the same proportions at different totals. Cosine similarity is 1, so cosine distance is 0, even though their Euclidean distance is positive. This is useful when article length should not dominate topic similarity. Correlation distance goes further by comparing centered profiles, allowing an overall level shift too.

  7. 7
    Key InsightIgnore uninformative shared absences

    For binary records, simple matching counts shared ones and shared zeros. Jaccard counts shared ones divided by positions with at least one one. If two customers both skipped thousands of rare items, counting every skipped item can make them seem strongly alike. Jaccard removes that contribution and concentrates on what at least one customer selected.

  8. 8
    ChallengeChoose a measure for mixed features

    Machines have a numeric reading and an unordered machine-type category. You want a combined comparison without making category codes act like measurements. What is one suitable distance?

    ---reveal---

    Gower distance combines range-scaled numeric differences with 0 for a categorical match and 1 for a mismatch. One-hot encoding with deliberate weighting is another route. Raw codes such as 1, 2, and 3 would introduce an unsupported spacing between types.

  9. 9
    ExampleSee why raw units matter

    Two features measure time and distance. Changing time from seconds to milliseconds multiplies its numeric differences by 1,000. In raw Euclidean distance, its squared contribution grows by a million while distance is unchanged. The observations describe the same events, but their nearest neighbors may change because the representation changed one feature’s weight.

  10. 10
    ExplanationPut differences on useful scales

    Standardization uses z=(x−xˉ)/s to express deviations in standard deviations. Min–max scaling uses the observed range; robust scaling uses the median and IQR and is less affected by a few extremes. Select the scale that matches the intended weighting. Features already sharing one meaningful geometric unit may work best without separate axis rescaling.

  11. 11
    TipReuse the learned transformation

    Fit the scaler on the observations used to build the model, then reuse its learned values for incoming observations. A new batch should not move the coordinate system around the stored centers. When cluster labels feed a predictive model, fit preprocessing and clustering on training data only, keeping validation and test observations out of both fitting steps.

  12. 12
    ChallengeCombine scaling with a new assignment

    A fitted scaler has mean 10 and standard deviation 2 for a feature. Its stored standardized centers are 0 and 3. A new observation has raw value 15. Where does it go?

    ---reveal---

    Reuse the training scale: (15 − 10)/2 = 2.5. It is 0.5 from center 3 and 2.5 from center 0, so it joins center 3. Fitting a new scaler to that observation would destroy the comparison with the stored centers.

  13. 13
    RecapTake the choices into fitting

    A clustering starts with a purpose and a definition of similarity. Choose features, encodings, scales, and distances that support that definition, then select a grouping family. Keep the fitted transformation for new observations. After fitting, interpret memberships from feature profiles and examine evidence that the groups persist across reasonable choices.

2

Follow k-means from a poor start

12 steps
Carry a small fit through assignments, mean updates, and an initialization check.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionWatch the centers move
  2. 2
    ExampleState the starting fit
  3. 3
    ExampleMake the first assignment
  4. 4
    ExampleUpdate the means
  5. 5
    ExampleAssign again and finish the update
  6. 6
    Key InsightExplain the falling objective
  7. 7
    ChallengeCheck a proposed update
  8. 8
    ExplanationTry more than one starting arrangement
  9. 9
    TipMake Python choices explicit
  10. 10
    ConnectionRecognize a geometric mismatch
  11. 11
    ChallengeChoose between an easier fit and a different model
  12. 12
    RecapUse convergence as one piece of evidence
3

Choose a count and defend the result

14 steps
Use a cost curve, silhouette calculation, and stability evidence to assess a candidate partition.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild a case for the groups
  2. 2
    ExampleCompare costs at several counts
  3. 3
    TipKeep the comparison compatible
  4. 4
    ChallengeWhat if the bend is absent?
  5. 5
    ExampleFind own-cluster distance
  6. 6
    ExampleFind the competing-cluster mean
  7. 7
    ExampleCalculate and interpret the silhouette
  8. 8
    ChallengeCatch a negative membership
  9. 9
    Key InsightRead more than the mean
  10. 10
    ExampleDescribe the groups in original units
  11. 11
    ExplanationSeparate repeatability from stability
  12. 12
    ChallengeEvaluate a use of cluster features
  13. 13
    ChallengeCombine the checks in a report
  14. 14
    RecapState what each check contributes
4

Merge a sample and read its tree

11 steps
Compare linkage rules, trace merge heights, and choose a nested partition.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild one tree from small values
  2. 2
    ExampleStart with the nearest pair
  3. 3
    ExampleCompare the next and final heights
  4. 4
    ExplanationUnderstand Ward’s extra criterion
  5. 5
    ChallengeTest the linkage distinction
  6. 6
    ExplanationRead where two branches first meet
  7. 7
    ExampleMake a horizontal cut
  8. 8
    ChallengeCheck a different cut
  9. 9
    TipHandle equal heights carefully
  10. 10
    ChallengeUse the hierarchy for the right task
  11. 11
    RecapRead the tree under its chosen rule
5

Build DBSCAN clusters from neighborhoods

12 steps
Count local support, connect core points, and test the radius settings.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionLet local density define the groups
  2. 2
    ExplanationFix the two settings
  3. 3
    ExampleCount before attaching border points
  4. 4
    ExampleConnect core regions
  5. 5
    ChallengeCan a border chain extend a cluster?
  6. 6
    TipInterpret the fitted output
  7. 7
    ExplanationConstruct a neighbor-distance plot
  8. 8
    ChallengeKeep the rank consistent
  9. 9
    ExampleWatch groups change with radius
  10. 10
    Key InsightRecognize density mismatch
  11. 11
    ChallengeChoose a method for the same purpose
  12. 12
    RecapAudit neighborhoods before interpreting labels
6

Fit normality and choose useful flags

16 steps
Follow Gaussian fitting, validation threshold selection, and a feature-design diagnosis.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate a score from a decision
  2. 2
    ExampleFit the normal feature
  3. 3
    ExplanationCombine feature densities
  4. 4
    ExampleTurn one score into a flag
  5. 5
    ChallengeInterpret a height above one
  6. 6
    ExplanationGive each split its own job
  7. 7
    ExampleCount flags and missed faults
  8. 8
    ExampleCompare a second threshold
  9. 9
    ChallengeChoose evidence for the decision
  10. 10
    ExampleInspect the misses for a relationship
  11. 11
    ExplanationModel covariance when data supports it
  12. 12
    TipCheck that the model can be fitted
  13. 13
    ChallengeCan a bigger sample fix dependence?
  14. 14
    ConnectionChoose between learning normality and faults
  15. 15
    ChallengeCombine error analysis with independent evaluation
  16. 16
    RecapFinish with an evaluated detector

Clustering and Anomaly Detection practice questions

50 Practice Questions in 5 sets

Set 1: Core ideas and first calculations10 Practice Questions

Question 1 of 10

A model groups unlabeled audio clips by their measured features. What kind of learning is this?
  1. Supervised classification
  2. Supervised regression
  3. Unsupervised learning
  4. Label-based validation
Show answerHide answer
Answer: C
The model receives features without target categories and forms its own groups, so this is unsupervised learning. Supervised classification would require known category labels in its training examples. A numeric group label produced afterward does not change how the model was trained.

Question 2 of 10

What is the Euclidean distance between (2,3) and (5,7)?
  1. 7
  2. 5
  3. 25
  4. 7
Show answerHide answer
Answer: B
The feature differences are 3 and 4, whose squares sum to 25. Taking the square root gives Euclidean distance 5. The value 25 is squared Euclidean distance, while 7 adds absolute differences and gives Manhattan distance.

Question 3 of 10

What is the centroid of the points (2, 2), (4, 2), and (3, 5)?
  1. (3, 3)
  2. (9, 9)
  3. (3, 2)
  4. (2, 3)
Show answerHide answer
Answer: A
Average each feature separately: the first coordinates sum to 9 and the second coordinates also sum to 9. Dividing each by three gives (3, 3). Taking the most frequent second coordinate would give 2, but a centroid uses the mean, not the mode.

Question 4 of 10

Points 1, 3, 9, and 11 start with centers at 1 and 3. After one assignment and one mean update, where are the centers?
  1. 2 and 10
  2. 2 and 11
  3. 1 and 6
  4. 1 and 23/3
Show answerHide answer
Answer: D
The first center receives only 1, while 3, 9, and 11 are nearer the second center. Their mean is 23/3, so the updated centers are 1 and 23/3. Centers 2 and 10 describe the natural pairs, but those are not the memberships produced by this first assignment.

Question 5 of 10

For cluster counts 1 through 5, inertias are 840, 390, 140, 122, and 110. What count does the elbow suggest?
  1. 2 clusters
  2. 3 clusters
  3. 4 clusters
  4. 5 clusters
Show answerHide answer
Answer: B
The reductions are 450, 250, 18, and 12, so improvements become much smaller after the third cluster. That makes three the elbow candidate. Choosing five because its cost is smallest overlooks the built-in cost reduction from adding more centers.

Question 6 of 10

A point has mean own-cluster distance 3 and smallest mean other-cluster distance 8. What is its silhouette?
  1. 0.375
  2. 1.667
  3. −0.625
  4. 0.625
Show answerHide answer
Answer: D
The silhouette is (8−3)/8=0.625, using the larger mean in the denominator. Its positive sign supports the assigned cluster because its own-cluster mean distance is smaller. Dividing the difference by 3 would give 1.667, which is outside the silhouette range.

Question 7 of 10

Clusters are {0, 2} and {7, 8}. What is their complete-linkage distance?
  1. 8
  2. 5
  3. 6.5
  4. 7
Show answerHide answer
Answer: A
Complete linkage takes the largest distance across the two clusters, here the distance from 0 to 8. The nearest pair is 2 and 7, whose distance 5 would be single linkage. Averaging cross-group distances would apply another linkage rule and would not give the complete-linkage height.

Question 8 of 10

DBSCAN uses eps = 1.1 and min_samples = 3 on values 0, 1, 2, and 5. What is the role of point 0?
  1. Core
  2. Noise
  3. Border
  4. A separate cluster
Show answerHide answer
Answer: C
Point 0 has only itself and point 1 in its neighborhood, so its count of two is too small for core status. Point 1 sees 0, 1, and 2 and is core. Since 0 is within eps of that core point, it is border, not noise despite its low own count.

Question 9 of 10

A product Gaussian gives feature densities 0.04 and 0.03 for a reading. The density threshold is 0.002. What decision follows?
  1. Keep it: joint density is 0.07.
  2. Keep it: joint density is 0.0012.
  3. Flag it: joint density is 0.0006.
  4. Flag it: joint density is 0.0012.
Show answerHide answer
Answer: D
The independent-feature model multiplies densities, so the joint score is 0.04 × 0.03 = 0.0012. This is below 0.002 and triggers a flag. Adding the two density values would give 0.07, but addition is appropriate for log densities, not ordinary densities.

Question 10 of 10

A validation sample contains 16 faults. Threshold A flags 15 cases, including 12 faults. Threshold B flags 30 cases, including 15 faults. Which threshold has higher F1, and what are its precision and recall?
  1. A: precision 0.80, recall 0.75.
  2. B: precision 0.50, recall 0.94.
  3. A: precision 0.75, recall 0.80.
  4. B: precision 0.94, recall 0.50.
Show answerHide answer
Answer: A
Threshold A has precision 12/15 = 0.80, recall 12/16 = 0.75, and F1 about 0.774. Threshold B has precision 0.50, recall 0.9375, and F1 about 0.652. Catching more faults improves recall, but B adds enough false alarms to lower its F1.
Set 2: Compare methods and interpret output10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A dendrogram has merges at heights 1, 3, 7, and 12 for five leaves. How many clusters does a horizontal cut at height 5 produce?
  1. 2
  2. 4
  3. 3
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two binary records share three presences and four absences, with one mismatch in each direction. What are their simple matching and Jaccard similarities?
  1. 7/9 and 3/5
  2. 3/9 and 7/9
  3. 7/9 and 3/9
  4. 3/5 and 7/9
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A feature value is 68, with fitted training mean 50 and standard deviation 6. What standardized value should be passed to the fitted clustering model?
  1. 18
  2. 11.33
  3. −3
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does KMeans(n_clusters=4, n_init=12, random_state=7) request?
  1. Twelve clusters and four starts.
  2. Four clusters and twelve starts.
  3. Four clusters and seven starts.
  4. Twelve clusters and seven starts.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Two fitted partitions have identical memberships, but cluster labels 0 and 1 are exchanged. What is their adjusted Rand index?
  1. 0
  2. −1
  3. 1
  4. 0.5
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Two clusters contain 2 and 3 points, and their means are 4 units apart. What increase in squared error would their Ward merge cause?
  1. 19.2
  2. 16
  3. 9.6
  4. 80
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For DBSCAN with min_samples = 6 counting the point itself, which other-neighbor rank belongs in the k-distance plot?
  1. Fourth nearest other point
  2. Sixth nearest other point
  3. Seventh nearest other point
  4. Fifth nearest other point
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Normal training values are 4, 7, and 10. What mean and maximum-likelihood variance are fitted?
  1. Mean 7, variance 9
  2. Mean 7, variance 6
  3. Mean 7, variance 18
  4. Mean 6, variance 7
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A validation sample has 12 faults. A flags 10 cases including 8 faults; B flags 18 cases including 10 faults. Missed faults cost 12 units each and false alarms cost 1 unit each. Which threshold minimizes this validation cost?
  1. A, with cost 50
  2. B, with cost 26
  3. B, with cost 32
  4. A, with cost 26
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A full Gaussian uses three features, with the third always exactly the sum of the first two. There are 5,000 normal observations. What prevents use of the ordinary covariance inverse, and what direct change addresses it?
  1. Too few observations; collect another 5,000.
  2. Exact dependence; remove a redundant feature.
  3. Different units; standardize all three features.
  4. Skewed features; lower the density threshold.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Check memberships and validate decisions10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Which clustering method can leave observations outside all clusters using a noise label?
  1. Standard k-means
  2. DBSCAN
  3. Complete-linkage tree cut
  4. Ward-linkage tree cut
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A one-hot category block is [1, 0, 0] for one observation and [0, 0, 1] for another. What is that block’s squared Euclidean contribution?
  1. 1
  2. 2
  3. 2
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For the same scaled data and three clusters, completed restarts have inertias 88, 72, 79, and 75. Which fit should be retained under the k-means objective?
  1. The fit with inertia 72.
  2. The fit with inertia 75.
  3. The fit with inertia 79.
  4. The fit with inertia 88.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

On unchanged scaled data, a three-cluster fit has inertia 115 and a four-cluster fit has inertia 138. What should be done before interpreting the curve?
  1. Select three solely from the increase.
  2. Rescale four clusters until cost falls.
  3. Treat 138 as a natural elbow height.
  4. Refit four clusters with more starts.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Point 4 is assigned with points 0 and 1. The other clusters are {5, 9} and {10, 12}. Using absolute distance, what is its silhouette?
  1. −5/7
  2. 1/7
  3. −1/7
  4. −1/6
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A team fits a scaler and k-means on all observations, then uses cluster labels as inputs to a classifier with a held-out test split. What repair preserves an independent evaluation?
  1. Keep the clusters; refit only the classifier.
  2. Split first; refit scaler and clusters on training.
  3. Keep the scaler; refit clusters on all inputs.
  4. Split labels only; reuse the full-data clusters.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Leaves P and Q are adjacent in a dendrogram but first join at height 9; P and R first join at height 2. Which pair is more similar according to this tree?
  1. P and R, from their merge at 2.
  2. P and Q, from their adjacent leaves.
  3. P and Q, from their merge at 9.
  4. Both pairs, since all leaves share a root.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

DBSCAN uses eps = 1.1 and min_samples = 4 on 0, 0.4, 0.8, 1.6, 2.4, 2.8, and 3.2. How many clusters form, and what is point 1.6?
  1. One cluster; 1.6 connects core regions.
  2. Two clusters; 1.6 is noise.
  3. No clusters; all points lack support.
  4. Two clusters; 1.6 is shared border.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

With a fixed minimum count, nearly every DBSCAN point is noise at eps = 0.05, while at eps = 5 almost all points form one group. What is a useful next step?
  1. Choose 5 because it eliminates most noise.
  2. Choose 0.05 because noise means poor data.
  3. Raise the cluster count before another fit.
  4. Inspect the k-distance knee and nearby radii.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Two Gaussian features each look ordinary for a missed faulty reading, but normal data shows a strong relationship that this pair breaks. What change directly targets this failure?
  1. Model covariance or add a relationship feature.
  2. Raise all feature units by a constant factor.
  3. Add an exact duplicate of each feature.
  4. Collect more examples of the same normal pair.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Diagnose difficult clustering results10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Which scaling rule uses the median and interquartile range?
  1. Standard scaling
  2. Min–max scaling
  3. One-hot encoding
  4. Robust scaling
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two nonnegative count vectors are (2, 3) and (4, 6). What are their cosine distance and Euclidean distance?
  1. 0 and √13
  2. 1 and √13
  3. 0 and 13
  4. 1 and 13
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A numeric block contains one standardized measure. Another block contains three exact copies of that same measure, each standardized separately. What is the copied block’s squared-distance weight relative to the single measure?
  1. The same weight.
  2. Nine times as large.
  3. Three times as large.
  4. One third as large.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A one-dimensional k-means cluster contains 2 and 6. Its current center is 3. With memberships fixed, what center and inertia follow from the mean update?
  1. Center 4, inertia 4.
  2. Center 4, inertia 8.
  3. Center 3, inertia 10.
  4. Center 8, inertia 40.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A sample has one tight central blob and a dense outer ring, with no outliers. Many k-means restarts still split both regions into wedges. What best explains the failure?
  1. The seed prevents enough independent iterations.
  2. The nearest-center geometry mismatches the groups.
  3. The ring requires a smaller convergence tolerance.
  4. The missing noise label makes the center undefined.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Clustering A has silhouettes 0.9, 0.9, 0.9, and −0.6. Clustering B has 0.6 for every point on the same data and distance. Which has the higher mean, and what does inspecting A reveal?
  1. B; A has one poorly supported assignment.
  2. A; its strongest memberships dominate the mean.
  3. B; all of A’s assignments are poorly supported.
  4. A; a negative score indicates strong separation.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Clusters U = {0, 4} and V = {5, 6, 15} are compared on a line. What are their average-linkage and centroid-linkage distances?
  1. 1 and 20/3
  2. 20/3 and 15
  3. 15 and 20/3
  4. 20/3 and 20/3
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A DBSCAN core chain runs through a curved region 30 units across, using eps = 1. Is its width alone a reason to split the cluster?
  1. Yes; every pair must be within eps.
  2. Yes; each cluster radius must equal eps.
  3. No; eps bounds local neighborhoods.
  4. No; eps sets a minimum cluster diameter.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A held-out sample has 24 faults. Threshold L flags 20 cases including 16 faults; H flags 40 cases including 22 faults. Which has better F1?
  1. H, about 0.688.
  2. L, about 0.800.
  3. L, about 0.727.
  4. H, about 0.917.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Normal operation has two tight temperature modes with a rarely visited gap. A single Gaussian places its mean in that gap. What detection error is especially plausible?
  1. A faulty gap reading receives high normal density.
  2. Every normal mode becomes impossible to score.
  3. All gap readings necessarily get low density.
  4. Covariance becomes singular solely from two modes.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine evidence and transfer the methods10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A fitted model names groups 0, 1, and 2. What can be inferred from the number 2 alone?
  1. It ranks a group first.
  2. It identifies a group.
  3. It gives group density.
  4. It counts group errors.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Points 0, 4, 6, and 10 are assigned as {0, 6} and {4, 10}. After updating both means and then reassigning all points, what are the memberships and the next updated centers?
  1. {0, 6}, {4, 10}; centers 3 and 7.
  2. {0, 4}, {6, 10}; centers 3 and 7.
  3. {0, 4}, {6, 10}; centers 2 and 8.
  4. {0}, {4, 6, 10}; centers 0 and 20/3.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For counts 1 through 5, inertias are 500, 410, 330, 260, and 200. The reductions decline gradually with no sharp bend. What conclusion is supported?
  1. Five groups are best because their cost is least.
  2. Two groups are best because the first drop is largest.
  3. One group is best because it has no split error.
  4. The curve alone does not select a clear count.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Two three-cluster fits use the same data and scale. A has inertia 120 and changes memberships substantially across seeds; B has inertia 124 and stable memberships across seeds and subsamples. What is the strongest report?
  1. A fits cost better; B offers stronger stability evidence.
  2. A is better on every criterion because cost is lower.
  3. B has lower squared error because its groups persist.
  4. A’s instability proves three natural groups are absent.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A four-leaf tree merges {A, B} and {C, D} separately at height 2, then merges those groups at height 8. Can a horizontal height cut yield exactly three clusters?
  1. Yes; any cut strictly between heights 2 and 8.
  2. Yes; a cut halfway between heights 0 and 2.
  3. No; the count jumps from four to two at height 2.
  4. No; a full binary tree can have only two clusters.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For eps = 1.1 and min_samples = 4, DBSCAN receives values 0, 0.3, 0.6, 0.9, 1.8, and 2.7. What happens to points 1.8 and 2.7?
  1. Both are border in the same cluster.
  2. 1.8 is border; 2.7 is noise.
  3. 1.8 is core; 2.7 is border.
  4. Both are noise outside every cluster.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A geographic DBSCAN call uses latitude and longitude in degrees and sets haversine eps to 0.002 for a desired 2 km radius. Using Earth radius 6,371 km, what correction is needed?
  1. Convert coordinates to radians; use eps ≈ 0.000314.
  2. Keep degrees; use eps ≈ 0.000314.
  3. Convert coordinates to radians; keep eps = 0.002.
  4. Keep degrees; set eps = 2.0.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A fixed independent Gaussian has means 20 and 5, with standard deviations 4 and 2. Which reading has lower density: A = (28, 5) or B = (24, 9)?
  1. A, because its largest raw deviation is 8.
  2. A, because its squared-z sum is 8 against 5.
  3. B, because its squared-z sum is 3 against 2.
  4. B, because its squared-z sum is 5 against 4.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A fixed density model flags observations below ε. On the same labeled sample, ε is increased. What must be true about recall?
  1. It must decrease.
  2. It must become one.
  3. It cannot decrease.
  4. It must stay fixed.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A fitted product Gaussian ranks observations by unusualness. One positive feature is changed from meters to centimeters, the model is refitted on those converted training values, and all inputs are converted consistently. What happens to rankings and an equivalent density threshold?
  1. Rankings stay fixed; multiply the threshold by 100.
  2. Rankings reverse; divide the threshold by 100.
  3. Rankings stay fixed; leave the threshold unchanged.
  4. Rankings stay fixed; divide the threshold by 100.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

79 Key Terms, each with its definition

A

Adjusted Rand index
The adjusted Rand index measures agreement between two partitions after accounting for chance, with one indicating identical groupings.
The adjusted Rand index stays one when only the numeric names of otherwise identical clusters are swapped.
Agglomerative clustering
Agglomerative clustering starts with one cluster per observation and repeatedly merges the closest pair under a selected linkage rule.
Agglomerative clustering commits to each early merge before building the larger nested groups above it.
Anomaly
An anomaly is an observation that departs from the normal pattern according to the selected representation and detection method.
A sensor reading outside all dense groups is an anomaly candidate to inspect for errors or faults.
Assignment step
The assignment step is the k-means operation that sends every observation to its nearest current centroid while keeping the centers fixed.
A point can switch groups during the assignment step after the previous mean update moved the centers.
Average linkage
Average linkage defines between-cluster dissimilarity as the mean of all pairwise distances between members of the two clusters.
Average linkage uses every cross-group pair, so it differs from distance between two cluster means.

B

Border point
A border point fails the DBSCAN core count but lies within the radius of a core point and can therefore join that point's cluster.
A shared border point can join either nearby core component without connecting the components together.

C

Centroid
A centroid is the feature-by-feature mean of a cluster's assigned observations, serving as its representative point in k-means.
The centroid of three two-feature readings may lie between the observed readings instead of matching one.
Centroid linkage
Centroid linkage measures between-cluster dissimilarity by the distance between their means and can produce decreasing merge heights.
Centroid linkage can create an inversion after merging two groups changes the position of their mean.
Chaining
Chaining is the joining of clusters through successive close pairs, allowing single linkage to form long or straggling groups.
Chaining can connect two visible blobs through a thin bridge even when their centers are far apart.
Cluster
A cluster is a group of observations judged similar under the selected features, scaling, distance, and grouping method.
One cluster contains machines with high temperatures and low vibration under the selected features.
Cluster count
The cluster count is the number of groups retained in a partition, selected from data evidence, the analysis purpose, or both.
An operational limit of four output categories may determine the cluster count even without a sharp elbow.
Cluster label
A cluster label is an arbitrary name assigned to a group, with no numeric rank or subject meaning supplied by the number itself.
Changing a cluster label from 0 to 2 leaves its membership and interpretation unchanged.
Cluster profile
A cluster profile describes a group's size and typical feature values, usually in original units so its members are understandable.
A cluster profile reports median temperature and vibration beside the number of machines in the group.
Cohesion
Cohesion describes how closely observations within a cluster fit together under the chosen distance and representation.
The own-cluster mean distance in a silhouette calculation measures local cohesion for that point.
Color quantization
Color quantization replaces many image colors with a smaller palette, which k-means can create by grouping RGB pixel vectors.
Color quantization replaces each pixel with its assigned centroid color and stores the palette index.
Complete linkage
Complete linkage defines between-cluster dissimilarity as the largest distance from a member of one cluster to a member of the other.
Complete linkage delays merging two groups when even one cross-group pair is far apart.
Cophenetic correlation
Cophenetic correlation measures agreement between original pairwise distances and the pairwise distances represented by merge heights.
A high cophenetic correlation supports the tree's distance representation without choosing its cut.
Cophenetic distance
Cophenetic distance is the height at which two observations first belong to the same branch in a hierarchical clustering tree.
Two adjacent leaves can have a large cophenetic distance if they join only near the top of the tree.
Core point
A core point has enough observations within the DBSCAN radius, including itself, to meet the selected minimum neighborhood count.
A core point can extend a DBSCAN cluster by linking to another core point within the radius.
Correlation distance
Correlation distance is one minus the correlation of two feature profiles, comparing their centered patterns of rises and falls.
Correlation distance groups activity profiles that rise and fall together despite different overall levels.
Cosine similarity
Cosine similarity is the normalized dot product of two nonzero vectors, comparing direction independently of their lengths.
Cosine similarity treats an article and a doubled copy of its word counts as matching directions.
Covariance matrix
A covariance matrix records feature variances and pairwise covariances, describing spread and linear relationships in a multivariate Gaussian.
A covariance matrix can represent the usual joint rise of CPU load and network traffic on a server.

D

Data leakage
Data leakage occurs when information reserved for evaluation influences fitting or model selection, making reported performance too optimistic.
Fitting cluster features on test observations creates data leakage even if their target labels remain hidden.
DBSCAN
DBSCAN forms clusters from connected dense neighborhoods and labels observations outside those regions as noise, without a preset count.
DBSCAN can follow a curved dense region that a nearest-centroid partition would cut across.
Dendrogram
A dendrogram is a tree drawing of hierarchical merges, with leaves for observations and merge heights for between-cluster dissimilarities.
A horizontal cut through a dendrogram identifies the groups present at that dissimilarity level.
Density threshold
A density threshold is the cutoff below which an observation's fitted density causes an anomaly flag in a fixed model and representation.
Raising the density threshold expands the set of flagged observations and can increase false alarms.
Density variation
Density variation means different regions have different local concentrations of observations, which can make one DBSCAN radius unsuitable.
Strong density variation can leave a sparse group as noise while a dense group's surroundings merge.
Distance metric
A distance metric is a nonnegative, symmetric dissimilarity that is zero exactly for identical vectors and satisfies the triangle inequality.
Euclidean distance is a distance metric, but its square can violate the triangle inequality.
Distortion
Distortion describes k-means squared-error cost; some conventions use total inertia and others divide that total by the observation count.
Average distortion and total inertia select the same best restart for a fixed set of observations.

E

Elbow method
The elbow method chooses a candidate cluster count near the bend where further k-means centers give much smaller reductions in inertia.
The elbow method suggests three groups when improvements become small after the third center is added.
eps
The eps parameter is the maximum distance for two observations to be neighbors in DBSCAN, expressed in the chosen distance units.
Increasing eps can connect core components, but eps does not bound a finished cluster's diameter.
Euclidean distance
Euclidean distance is the straight-line separation between vectors, calculated as the square root of their summed squared feature differences.
Euclidean distance compares two machines after their sensor features are placed on comparable scales.
External evaluation
External evaluation compares cluster memberships with an available reference grouping, such as known categories or expert labels.
External evaluation can reveal that clusters capture a different pattern from the existing machine classes.

F

F1 score
The F1 score is the harmonic mean of precision and recall, giving a balanced score that is low when either component is low.
Between two thresholds, the F1 score can prefer the one with fewer false alarms even when the other catches slightly more faults.
False negative
A false negative is a genuine anomaly that the detector fails to flag, representing a missed fault and reducing recall.
A faulty part passed without a flag counts as a false negative even if most normal parts were classified correctly.
False positive
A false positive is a normal observation incorrectly flagged as anomalous, contributing to the inspection burden and lowering precision.
A normal machine sent for inspection after an anomaly flag is a false positive in the detector evaluation.
Feature transformation
A feature transformation changes the representation of a measurement, such as using a logarithm to reduce strong positive skew.
A feature transformation turns values 1, 10, and 100 into 0, 1, and 2 under a base-10 logarithm.
Feature weight
A feature weight is a multiplier that changes a feature's contribution to a distance, expressing how much that aspect should count.
A feature weight of 2 multiplies that feature's contribution to squared Euclidean distance by 4.

G

Gap statistic
The gap statistic compares clustering cost with a reference cost expected from comparable data without cluster structure.
The gap statistic offers another criterion when an inertia curve has no clear bend to inspect.
Gaussian density
A Gaussian density is a symmetric bell-shaped density determined by its mean and variance, with its highest value at the mean.
A Gaussian density assigns a low score to a vibration reading far from the fitted normal mean.
Gower distance
Gower distance averages feature-level dissimilarities for mixed data, combining range-scaled numeric differences with categorical mismatches.
Gower distance combines a measured numeric feature and an unordered machine-type category in one comparison.

H

Haversine distance
Haversine distance measures great-circle angular separation on a sphere, using latitude and longitude expressed in radians.
Haversine distance requires a 1 km neighborhood radius to be divided by the chosen Earth radius.
HDBSCAN
HDBSCAN is a density-based clustering method designed to find groups across varying density levels without choosing one global eps.
HDBSCAN is an alternative to inspect when dense and sparse groups cannot share one useful DBSCAN radius.

I

Inertia
Inertia is the sum of squared Euclidean distances from observations to their assigned k-means centroids, across all clusters.
Lower inertia identifies the better restart when data, scaling, and cluster count are held fixed.
Internal evaluation
Internal evaluation judges a partition using its feature data and assignments, without requiring known target group labels.
Internal evaluation may compare silhouette scores for several cuts of the same dendrogram.

J

Jaccard similarity
Jaccard similarity is the number of shared presences divided by the number of binary positions with a presence in at least one observation.
Jaccard similarity compares purchased items without rewarding two customers for skipping the same items.

K

k-distance plot
A k-distance plot sorts each point's distance to a chosen neighbor rank, helping identify a DBSCAN radius near a sharp upward bend.
For a minimum count of 5 including self, the k-distance plot uses the fourth nearest other point.
k-means++
k-means++ is an initialization method that spreads centers by favoring points far from already selected centers, using squared distance.
k-means++ reduces poor starts but can still converge to a local minimum on a difficult data set.

L

Local minimum
A local minimum is a fitted solution that the ordinary assignment and mean-update operations cannot improve, though a better partition may exist.
A poor k-means start can reach a local minimum with much higher inertia than another start.
Log density
Log density is the logarithm of a fitted density score; independent feature log densities add instead of requiring many small multiplications.
Log density avoids underflow while preserving the ordering of observations from low to high fitted density.

M

Mahalanobis distance
Mahalanobis distance measures departure from a mean while accounting for feature scale and covariance in the normal data.
Mahalanobis distance can be large for an ordinary-looking pair that breaks a strong normal correlation.
Manhattan distance
Manhattan distance is the sum of absolute feature differences between two vectors, without squaring the individual differences.
Manhattan distance between (2, 1) and (5, 5) is 7, from the absolute differences 3 and 4.
Maximum-likelihood variance
Maximum-likelihood variance for a Gaussian feature is the mean squared deviation from its fitted mean, dividing by the training count.
Maximum-likelihood variance divides the sum 18 by 3 for three training values, giving 6.
min_samples
The min_samples parameter is the minimum neighborhood count for a DBSCAN core point, including the point itself in the unweighted case.
With min_samples set to 4, a point needs at least three other points within the radius to be core.
Min–max scaling
Min–max scaling subtracts the feature minimum and divides by its range, placing the fitted data between zero and one when the range is positive.
One extreme reading stretches the range in min–max scaling and compresses the other scaled readings.

N

Nested partition
A nested partition belongs to a hierarchy in which every higher-level cluster is a union of complete clusters from lower levels.
A higher nested partition cannot move one member out of a lower cluster while keeping its companions separate.
Noise point
A noise point is neither a DBSCAN core point nor within the selected radius of any core point, so it remains outside the clusters.
A noise point receives label −1 in scikit-learn and becomes a candidate for anomaly inspection.

O

One-hot encoding
One-hot encoding represents each category by a separate indicator column, avoiding an artificial numeric order among unordered categories.
One-hot encoding gives machine types separate 0/1 columns before combining them with numeric readings.
Operating mode
An operating mode is a distinct normal regime of a system, such as idle or full load, that can need its own normal-data model.
Pooling two operating modes into one bell curve can give their rarely visited gap a misleadingly high density.

P

Precision
Precision is the share of flagged observations that are genuine anomalies, measuring how reliable the detector's positive decisions are.
Precision is 0.75 when 9 of 12 flags correspond to real faults and the remaining flags are normal cases.
Probability density
Probability density is probability per unit of measurement along a continuous scale, so its height is not itself a probability.
A narrow probability density can peak above one while the total area under its curve remains one.
Product Gaussian model
A product Gaussian model multiplies separately fitted feature densities, treating the features as independent in the modeled joint density.
The product Gaussian model can flag jointly unusual magnitudes but cannot learn a CPU-to-traffic correlation.

R

Random restart
A random restart is a fresh k-means fit from another random initialization, used to reduce dependence on one set of starting centers.
Ten random restarts provide ten fitted candidates, and the lowest-inertia candidate is retained.
Random seed
A random seed fixes a pseudorandom sequence so that initialization choices can be repeated under the same fitting setup.
A fixed random seed reproduces one run; changing seeds checks whether the groups depend on the start.
Recall
Recall is the share of genuine anomalies that are flagged, measuring how much of the anomalous population the detector catches.
Recall is 0.6 when a detector catches 6 of the 10 faults present in the evaluated sample.
Robust scaling
Robust scaling subtracts a feature's median and divides by its interquartile range, reducing the influence of a few extreme observations.
Robust scaling helps limit an extreme sensor value's effect on the scale used for ordinary readings.

S

Separation
Separation describes how distinct a cluster is from competing groups under the chosen features and distance measure.
A point with small own-cluster distance and large nearest-group distance has strong separation.
Silhouette
A silhouette compares one point's mean own-cluster distance with its smallest mean distance to another cluster, on a scale from −1 to 1.
A negative silhouette suggests that a point is closer on average to another group than to its own.
Silhouette plot
A silhouette plot displays individual silhouette values sorted within clusters, revealing weak memberships and group-size differences.
A silhouette plot can expose one weak group that is hidden by a strong overall mean score.
Simple matching coefficient
The simple matching coefficient is the share of binary feature positions where two observations agree, counting both shared ones and shared zeros.
The simple matching coefficient counts a shared absence as well as a shared presence in binary records.
Single linkage
Single linkage defines between-cluster dissimilarity as the smallest distance from a member of one cluster to a member of the other.
Single linkage can join two broad regions through a narrow chain of nearby observations.
Singleton cluster
A singleton cluster contains exactly one observation and receives silhouette zero by convention because it has no other own-cluster member.
Splitting off a singleton cluster does not award the isolated point a silhouette of one.
Singular covariance
A singular covariance matrix lacks an ordinary inverse, as happens when one feature is an exact linear combination of the others.
Adding a duplicate feature creates singular covariance even when the original features had ample observations.
Stability
Stability is persistence of similar cluster memberships across reasonable changes in seeds, samples, or analysis settings.
Stability is stronger when shared observations remain grouped together across several random subsamples.
Standardization
Standardization expresses a value as its deviation from a fitted feature mean divided by the fitted standard deviation.
Standardization lets a temperature difference and a vibration difference contribute in standard-deviation units.
Supervised learning
Supervised learning learns a mapping from inputs to target labels using examples whose desired outputs are already known.
Supervised learning uses previously labeled faulty and normal parts to predict a new part's category.

U

Unsupervised learning
Unsupervised learning finds patterns in inputs without supplied target labels, as in grouping similar observations or detecting unusual ones.
An unsupervised learning model groups articles from their word profiles without receiving topic labels.
Update step
The update step is the k-means operation that replaces each nonempty cluster's centroid with the mean of its current members.
The update step moves a center after a newly assigned observation changes the group's average.

W

Ward's method
Ward's method merges the pair of clusters that produces the smallest increase in total within-cluster sum of squares.
Ward's method accounts for cluster sizes as well as the Euclidean distance between their means.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started