- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Clustering and Anomaly Detection
Clustering and Anomaly Detection
IntermediateLesson 8 of 9 in Machine Learning Course
What you will learn
- 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 dataDistinguish unsupervised from supervised learning, describe the three families of clustering methods, and recognize the choices that shape every clustering.
- Measure how alike two observations areCompute 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 clusteringShow how units and ranges distort distances, standardize or rescale features correctly, and decide which features and weights to use.
- Explain what clustering and anomaly detection do with unlabeled data
- 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 stepDefine 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 limitsAvoid 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.
- Run the k-means algorithm step by step
- 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 methodPlot 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 scoresCalculate 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 clustersDescribe clusters in the original units, test whether they are stable, compare them with known labels when available, and report the analysis honestly.
- Choose k with the elbow method
- 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 linkageCarry out agglomerative clustering by hand with single, complete, average and Ward linkage, and explain how the linkage shapes the clusters.
- Read and cut a dendrogramRead 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.
- Merge clusters with agglomerative clustering and linkage
- 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 noiseApply 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 methodSet 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.
- Classify points as core, border or noise
- 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 densitiesEstimate 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 detectorSplit 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 detectionDecide between anomaly detection and supervised learning, transform skewed features, add features that expose missed anomalies, and use the multivariate Gaussian for correlated features.
- Model normal data with Gaussian densities
Clustering and Anomaly Detection study guide
1Prepare 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
| Family | How groups form | Main choice |
|---|---|---|
| Centroid-based | Points join a nearby center | Number of groups |
| Hierarchical | Successive merges form a nested tree | Linkage and a tree cut |
| Density-based | Connected dense regions form clusters | Neighborhood 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:
For and , 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:
Vectors and 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 count shared ones, shared zeros, and mismatches. With :
| Measure | Similarity | Useful when |
|---|---|---|
| Simple matching | Ones and zeros both matter | |
| Jaccard | Shared absences add no evidence |
For the purchase vectors and , the counts are . 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 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:
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
| Scaling | Calculation | Main consideration |
|---|---|---|
| Standard | Mean and spread react to extremes | |
| Min–max | One extreme stretches the range | |
| Robust | Less 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 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.
2Group 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:
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:
- Assign: send each point to its nearest centroid.
- 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:
The cost becomes . 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 , 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 feature | Why k-means can struggle |
|---|---|
| Curved or ring-shaped groups | Nearest-center boundaries are flat |
| Very different group spreads | One broad group may split while others merge |
| Extreme observations | Squared deviations pull means strongly |
| A custom dissimilarity | The 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.
3Choose 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 count | Cost reduction |
|---|---|
| 1 to 2 | 480 |
| 2 to 3 | 310 |
| 3 to 4 | 30 |
| 4 to 5 | 20 |
| 5 to 6 | 15 |
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 , let 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 .
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 . The other-cluster distances are 5 and 6, so . Therefore .
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 and , 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 , invert it using the fitted feature mean and standard deviation:
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.
4Build 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 observations contains merges. Divisive clustering starts together and splits downward instead.
Define distance between groups
| Linkage | Dissimilarity used for the next merge |
|---|---|
| Single | Smallest cross-cluster point distance |
| Complete | Largest cross-cluster point distance |
| Average | Mean of all cross-cluster point distances |
| Centroid | Distance between cluster means |
| Ward | Increase 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 and means , the increase is
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 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 height | Groups |
|---|---|
| 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.
5Find 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_samplesobservations in its neighborhood. - A border point is not core but lies within
epsof a core point. - A noise point is neither core nor within
epsof 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.
| Value | Neighborhood count | Role |
|---|---|---|
| 1 | 2 | Border |
| 2 | 3 | Core |
| 3 | 3 | Core |
| 4.2 | 2 | Border |
| 10 | 2 | Border |
| 11 | 3 | Core |
| 11.6 | 2 | Border |
| 20 | 1 | Noise |
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 radians using a 6,371 km Earth radius.
Match the method to the purpose
| Need | Useful starting method |
|---|---|
| Large numeric sample; compact groups; assign new points | k-means |
| Small or medium sample; custom dissimilarity; nested structure | Hierarchical clustering |
| Irregular dense regions; isolated points should remain noise | DBSCAN |
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.
6Detect 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: .
Estimate each feature's bell curve
For a feature with mean and standard deviation , the Gaussian density is
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 training values, estimate
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:
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:
| Split | Normal | Faulty | Purpose |
|---|---|---|---|
| Training | 6,000 | 0 | Fit the density model |
| Validation | 2,000 | 10 | Choose the threshold |
| Test | 2,000 | 10 | Evaluate 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.
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 . 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 . 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:
Here is the mean vector, describes variances and covariances, and 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 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
1Decide what similar means
13 steps
- 1IntroductionStart 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.
- 2ExplanationInputs 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.
- 3ConnectionChoose 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.
- 4ChallengeWhat 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.
- 5ExampleWork a numeric distance
Compare vectors and . 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.
- 6ExplanationWhen direction matters more than length
Word-count vectors and 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.
- 7Key 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.
- 8ChallengeChoose 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.
- 9ExampleSee 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.
- 10ExplanationPut differences on useful scales
Standardization uses 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.
- 11TipReuse 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.
- 12ChallengeCombine 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.
- 13RecapTake 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.
2Follow k-means from a poor start
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionWatch the centers move
- 2ExampleState the starting fit
- 3ExampleMake the first assignment
- 4ExampleUpdate the means
- 5ExampleAssign again and finish the update
- 6Key InsightExplain the falling objective
- 7ChallengeCheck a proposed update
- 8ExplanationTry more than one starting arrangement
- 9TipMake Python choices explicit
- 10ConnectionRecognize a geometric mismatch
- 11ChallengeChoose between an easier fit and a different model
- 12RecapUse convergence as one piece of evidence
3Choose a count and defend the result
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBuild a case for the groups
- 2ExampleCompare costs at several counts
- 3TipKeep the comparison compatible
- 4ChallengeWhat if the bend is absent?
- 5ExampleFind own-cluster distance
- 6ExampleFind the competing-cluster mean
- 7ExampleCalculate and interpret the silhouette
- 8ChallengeCatch a negative membership
- 9Key InsightRead more than the mean
- 10ExampleDescribe the groups in original units
- 11ExplanationSeparate repeatability from stability
- 12ChallengeEvaluate a use of cluster features
- 13ChallengeCombine the checks in a report
- 14RecapState what each check contributes
4Merge a sample and read its tree
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBuild one tree from small values
- 2ExampleStart with the nearest pair
- 3ExampleCompare the next and final heights
- 4ExplanationUnderstand Ward’s extra criterion
- 5ChallengeTest the linkage distinction
- 6ExplanationRead where two branches first meet
- 7ExampleMake a horizontal cut
- 8ChallengeCheck a different cut
- 9TipHandle equal heights carefully
- 10ChallengeUse the hierarchy for the right task
- 11RecapRead the tree under its chosen rule
5Build DBSCAN clusters from neighborhoods
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLet local density define the groups
- 2ExplanationFix the two settings
- 3ExampleCount before attaching border points
- 4ExampleConnect core regions
- 5ChallengeCan a border chain extend a cluster?
- 6TipInterpret the fitted output
- 7ExplanationConstruct a neighbor-distance plot
- 8ChallengeKeep the rank consistent
- 9ExampleWatch groups change with radius
- 10Key InsightRecognize density mismatch
- 11ChallengeChoose a method for the same purpose
- 12RecapAudit neighborhoods before interpreting labels
6Fit normality and choose useful flags
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate a score from a decision
- 2ExampleFit the normal feature
- 3ExplanationCombine feature densities
- 4ExampleTurn one score into a flag
- 5ChallengeInterpret a height above one
- 6ExplanationGive each split its own job
- 7ExampleCount flags and missed faults
- 8ExampleCompare a second threshold
- 9ChallengeChoose evidence for the decision
- 10ExampleInspect the misses for a relationship
- 11ExplanationModel covariance when data supports it
- 12TipCheck that the model can be fitted
- 13ChallengeCan a bigger sample fix dependence?
- 14ConnectionChoose between learning normality and faults
- 15ChallengeCombine error analysis with independent evaluation
- 16RecapFinish with an evaluated detector
Clustering and Anomaly Detection practice questions
Set 1: Core ideas and first calculations10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Compare methods and interpret output10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
KMeans(n_clusters=4, n_init=12, random_state=7) request?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Adjusted Rand index
Agglomerative clustering
Anomaly
Assignment step
Average linkage
B
Border point
C
Centroid
Centroid linkage
Chaining
Cluster
Cluster count
Cluster label
Cluster profile
Cohesion
Color quantization
Complete linkage
Cophenetic correlation
Cophenetic distance
Core point
Correlation distance
Cosine similarity
Covariance matrix
D
Data leakage
DBSCAN
Dendrogram
Density threshold
Density variation
Distance metric
Distortion
E
Elbow method
eps
Euclidean distance
External evaluation
F
F1 score
False negative
False positive
Feature transformation
Feature weight
G
Gap statistic
Gaussian density
Gower distance
H
Haversine distance
HDBSCAN
I
Inertia
Internal evaluation
J
Jaccard similarity
K
k-distance plot
k-means++
L
Local minimum
Log density
M
Mahalanobis distance
Manhattan distance
Maximum-likelihood variance
min_samples
Min–max scaling
N
Nested partition
Noise point
O
One-hot encoding
Operating mode
P
Precision
Probability density
Product Gaussian model
R
Random restart
Random seed
Recall
Robust scaling
S
Separation
Silhouette
Silhouette plot
Simple matching coefficient
Single linkage
Singleton cluster
Singular covariance
Stability
Standardization
Supervised learning
U
Unsupervised learning
Update step
W
Ward's method
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.