Learning without labels
Supervised learning needs a label for every example. In engineering, labels are expensive: A geologist must interpret each metre of a well, a technician must confirm each fault, and many rare events have never been observed. Unsupervised learning works with the inputs alone. Clustering groups similar records, dimensionality reduction summarises many correlated variables with a few, and anomaly detection flags records that differ from the bulk of the data [1, 2]. The results are hypotheses that domain experts must interpret: A cluster is not a rock type, and an anomaly is not a fault, until someone checks.
k-means and the choice of k
k-means represents each cluster by a centre and alternates two steps: assign every point to its nearest centre, then move every centre to the mean of its points. Each step lowers the sum of squared distances, so the procedure converges, although only to a local optimum [3, 4]. The k-means++ initialisation spreads the initial centres out and improves both speed and quality [5]. Because k-means uses Euclidean distance, inputs with large numerical ranges dominate unless they are scaled; gamma-ray counts in API units would otherwise swamp a photoelectric factor.
The number of clusters is a modelling choice. The within-cluster sum of squares always falls as k grows, so the elbow of its curve is only a rough guide. The silhouette of a point compares its mean distance to its own cluster with that to the nearest other cluster, and the average silhouette over all points is highest for well-separated, compact clusters [6]. Neither criterion knows the physics; well logs may form five clear clusters although geologists distinguish nine facies.
Animation: The two steps of k-means
Press Step to alternate between assigning points to the nearest centre and moving each centre to the mean of its points. Try several restarts: Different initial centres can end in different solutions.
Check your understanding. Why must the inputs usually be standardised before k-means?
Formulas: The k-means objective, k-means++ and the silhouette
k-means divides points into clusters with centres and minimises the within-cluster sum of squares [3, 4]:
The double bars denote the Euclidean length of a vector, so is the squared distance. The algorithm alternates two steps, each of which can only lower : The assignment step gives every point to its nearest centre, and the update step moves every centre to the mean of its points,
k-means++ chooses the first centre at random and every further centre with a probability proportional to the squared distance of a point to the nearest centre chosen so far [5]:
The silhouette of a point compares its mean distance to the other points of its cluster with its mean distance to the points of the nearest other cluster [6]:
Values near 1 mark points deep inside their cluster, values near 0 points between clusters, and negative values points that sit closer to another cluster.
Worked example: One iteration of k-means
Six points, A , B , C , D , E and F , are clustered with , starting from and .
Step 1. Assignment. The squared distances to the two centres, for example and :
| Point | Coordinates | To | To | Cluster |
|---|---|---|---|---|
| A | 0 | 52 | 1 | |
| B | 1.25 | 37.25 | 1 | |
| C | 10.25 | 16.25 | 1 | |
| D | 52 | 0 | 2 | |
| E | 22.25 | 6.25 | 2 | |
| F | 28.25 | 4.25 | 2 |
The sum of the smaller squared distances is .
Step 2. Update.
Step 3. The new objective. For A, , and in the same way the squared distances to the new centres are 2.055556, 0.138889, 3.138889 in cluster 1 and 2.222222, 1.138889, 0.472222 in cluster 2, so
much less than 22. A second assignment step leaves every point in its cluster, so the algorithm has converged.
Worked example: Seeding with k-means++ and two silhouettes
Step 1. The second centre. With A as the first centre, the squared distances of the other points are B 1.25, C 10.25, D 52, E 22.25, F 28.25, which add up to 114. The probabilities are B 0.011, C 0.0899, D 0.4561, E 0.1952, F 0.2478, with the cumulative values 0.011, 0.1009, 0.557, 0.7522, 1. A random number of 0.6 falls in the interval of E, which becomes the second centre; the far points D, E and F together had a probability of 0.8991.
Step 2. The silhouette of A. from the distances to B and C, and from the distances to D, E and F, so
Step 3. The silhouette of C. and , so
C belongs to cluster 1 by its distance to the centres, yet on average it lies closer to the points of cluster 2. Its negative silhouette marks it as a point between clusters, which an expert should inspect. Part A of the interactive lab computes all these quantities for any points.
Principal component analysis
Principal component analysis finds orthogonal directions along which the data vary most [7, 8]. The first component is the direction of largest variance, the second the largest remaining variance orthogonal to the first, and so on. The explained variance ratio of each component shows how much information a projection keeps, and the loadings show how each original variable contributes. In well logging, the first components often combine porosity and density logs, which respond to the same rock properties. PCA serves visualisation, compression, noise reduction and the detection of anomalies as points that the leading components reconstruct poorly.
Formulas: Principal components from the covariance matrix
The observations of variables are first centred by subtracting each variable's mean. The covariance matrix collects the variances on its diagonal and the covariances off it [8]:
The principal components are the eigenvectors of , the directions that only stretches, , and the eigenvalue is the variance of the data along [7]. For two variables the eigenvalues solve a quadratic equation in the trace and the determinant :
and the first row of gives the direction , scaled to length one. The explained variance ratio of component is . A centred observation has the score on the first component, its reconstruction from that component alone is , and the reconstruction error serves as an anomaly score.
Worked example: Two porosity logs
Five depth samples give a density porosity of 8, 9, 10, 11, 12 percent and a neutron porosity of 10.5, 11, 12, 12.5, 14 percent.
Step 1. Centring. The means are 10 and 12, so the centred values are −2, −1, 0, 1, 2 and −1.5, −1, 0, 0.5, 2.
Step 2. The covariance matrix.
Step 3. Eigenvalues. and :
so and .
Step 4. The first direction. , and the length of is , so .
Step 5. Explained variance. : The first component keeps 99.1 percent of the variance, because both logs respond to the same porosity.
Step 6. Score and reconstruction of the last sample. For the centred sample :
A sample whose logs disagree, for example because of a washed-out borehole, would lie far from the first direction and show a much larger error. Part B of the interactive lab computes these steps for any data.
Density-based clustering
Clusters in engineering data are not always round. Earthquakes line up along faults, defects form streaks on a web of fabric, and traffic accidents gather along roads. DBSCAN defines clusters as regions of high density: A point with at least a minimum number of neighbours within a radius eps is a core point, clusters grow by connecting core points that are neighbours, and points that belong to no cluster are labelled noise [9]. DBSCAN finds clusters of arbitrary shape and does not need the number of clusters, but eps and the minimum number of points must fit the density of the data. For epicentres, distances should be measured on the sphere, for example with the haversine formula, rather than in degrees.
Check your understanding. Aftershocks form an elongated band along a fault, surrounded by scattered background events. Which method suits this pattern best?
Formulas: DBSCAN and distances on the sphere
DBSCAN uses two parameters, a radius and a minimum number of points [9]. The -neighbourhood of a point , which includes itself, is
A point is a core point when . A cluster is grown from a core point by adding its neighbours and, recursively, the neighbours of every core point among them. A point that is not a core point but lies in the neighbourhood of one is a border point, and every remaining point is noise. Epicentres are given by latitude and longitude on a sphere of radius km, and the great-circle distance between two of them follows from the haversine formula, with all angles in radians:
A degree of latitude is always km long, while a degree of longitude shrinks with , so distances computed directly in degrees are wrong in the east-west direction.
Worked example: Core, border and noise points
Eight points on a map, in kilometres, are clustered with km and . The distance between P1 and P4 is , so they are not neighbours, while P4 and P5 are 1 km apart:
| Point | Coordinates | Neighbourhood | Size | Type |
|---|---|---|---|---|
| P1 | P1, P2, P3 | 3 | core | |
| P2 | P1, P2, P4 | 3 | core | |
| P3 | P1, P3, P4 | 3 | core | |
| P4 | P2, P3, P4, P5 | 4 | core | |
| P5 | P4, P5 | 2 | border | |
| P6 | P6, P7 | 2 | noise | |
| P7 | P6, P7 | 2 | noise | |
| P8 | P8 | 1 | noise |
P1 to P4 are core points and form one cluster. P5 has only two points in its neighbourhood but lies next to the core point P4, so it joins the cluster as a border point. P6 and P7 are close to each other, but neither has three points in its neighbourhood, so both are noise, as is the isolated P8. With , P6 and P7 would form a second cluster: The parameters must match the density of the data. Part C of the interactive lab places points by clicking and compares k-means with DBSCAN on the same data.
Worked example: The distance between two epicentres
Two epicentres lie at N, E and N, E.
Step 1. Differences in radians. and .
Step 2. The haversine term.
Step 3. The distance. , so km.
Step 4. The error of degrees. Treating degrees as a flat grid gives km, close here because the separation is mostly north-south. For two points one degree apart in longitude at N, however, the true distance is about km, while degrees would give 111.195 km, an error of 27 percent that would distort every -neighbourhood. Part D of the interactive lab clusters epicentres with haversine distances.
Signals in the frequency domain
Many engineering sensors produce time series sampled at a fixed rate: accelerometers on machines, microphones, current transducers, seismometers. The discrete Fourier transform expresses a sampled signal as a sum of sinusoids, and the fast Fourier transform computes it efficiently [10]. The sampling rate fs limits the highest frequency that can be represented to fs / 2, the Nyquist frequency, and a record of duration T resolves frequencies that differ by 1 / T. Rotating machines produce peaks at the shaft frequency and its harmonics, and faults add their own frequencies.
A rolling-element bearing with a damaged outer race produces an impact every time a rolling element passes the damage. The ball pass frequency of the outer race is BPFO = (n / 2) fr (1 - (d / D) cos phi), with n rolling elements of diameter d, pitch diameter D, contact angle phi and shaft frequency fr. The impacts excite structural resonances at high frequency, so the fault frequency often appears not in the raw spectrum but in the spectrum of the signal's envelope, obtained after demodulation. Envelope analysis is the benchmark technique of bearing diagnostics [11], and the Case Western Reserve University data are the standard test set for it [12]. Simple condition indicators complement spectra: the root mean square (RMS) measures vibration energy, kurtosis measures impulsiveness, and the crest factor compares the peak with the RMS.
Check your understanding. A bearing has 9 balls, d / D = 0.2034, contact angle zero, and the shaft turns at 30 Hz. What is the BPFO?
Formulas: The discrete Fourier transform, bearing frequencies and condition indicators
A signal sampled at the rate gives values over the duration . The discrete Fourier transform writes it as a sum of complex sinusoids with the coefficients [10]
where is the imaginary unit and . Coefficient belongs to the frequency , so neighbouring bins are apart, and the highest frequency that can be represented is the Nyquist frequency . The mean of the signal is , and a sinusoid that falls exactly on bin has the amplitude . For a bearing with rolling elements of diameter on the pitch diameter , with contact angle and shaft frequency , the characteristic frequencies are [11]
for the outer race, the inner race, the cage and the spin of a rolling element. The impacts at these rates modulate a high-frequency resonance; envelope analysis takes the magnitude of the analytic signal, , where H denotes the Hilbert transform, and the fault frequencies appear in the spectrum of this envelope. Three simple indicators summarise a record:
A Gaussian signal has a kurtosis of 3; impacts raise it.
Worked example: A four-point Fourier transform
The samples are taken at Hz.
Step 1. The rotating factors. For and , takes the values , , and for ; for the values ; for the values .
Step 2. The coefficients.
Step 3. Interpretation. The bins are Hz apart. The mean is , and bin 1, at 250 Hz, holds a sinusoid of amplitude : Indeed . Bin 3 mirrors bin 1, as for every real signal, and lies above the Nyquist frequency of 500 Hz. Part E of the interactive lab computes the Fourier coefficients of any short signal term by term.
Worked example: Bearing frequencies and indicators
Step 1. Fault frequencies. For , , and Hz, as in the knowledge check:
At the 1797 rpm of the Case Western Reserve data, Hz, and the BPFO is Hz [12].
Step 2. Resolution. A record sampled at 12 kHz for one second gives Hz, fine enough to separate BPFO from its neighbours, and a Nyquist frequency of 6000 Hz.
Step 3. Indicators of a short record. The samples 0.5, −0.4, 0.3, 3, −0.6, 0.4, −0.5, 0.3 contain one impact. Their squares add up to 10.36, so and the crest factor is . The mean is ; the squared deviations from it add up to 9.235, so the variance is 1.154375, and the fourth powers add up to 49.331641, so and
well above 3, which flags the impulsive content. Part F of the interactive lab computes the frequencies for any bearing and the indicators for any record, and Part G synthesises the vibration of a bearing and shows its waveform, spectrum and envelope spectrum.
Anomaly detection
An anomaly detector learns what normal data look like and scores how unusual a new record is [2]. Statistical rules flag values far from the mean in units of standard deviation. Reconstruction-based methods flag records that a PCA model or an autoencoder reconstructs poorly. Isolation forests grow random trees that split the data at random thresholds; anomalies are isolated after few splits, so the average path length to isolate a point becomes its score [13]. In condition monitoring, detectors are usually trained on data from normal operation, because faults are rare and diverse. The alarm threshold, as in Week 8, depends on the costs of false alarms and missed faults, and a detector must be re-examined when operating conditions change, since a new load or speed can look like an anomaly [14].

Check your understanding. An isolation forest was trained on vibration features from a pump at 50 percent load. After the load is raised to 90 percent, alarms rise sharply although the pump is healthy. What is the most likely explanation?
Formulas: Statistical rules and the isolation forest
A simple rule flags a value whose standardised distance from the mean of normal data exceeds a limit, often 3: . Reconstruction-based methods flag records with a large error , as in the PCA example. An isolation forest grows random trees on subsamples of points, splitting on a random feature at a random value, and records the number of edges from the root to the leaf that isolates a point. Its anomaly score normalises the mean path length over all trees by the average path length of an unsuccessful search in a binary tree [13]:
with the harmonic number , where the constant is Euler's constant. Scores close to 1 mark anomalies, scores well below 0.5 normal points, and a score of 0.5 means that .
Worked example: Two detectors
Step 1. A three-sigma rule. A bearing temperature has and in normal operation. A reading of gives , beyond 3, so it is flagged.
Step 2. The normalising constant. With subsamples of points, as recommended by Liu and colleagues:
Step 3. Two scores. A point isolated after 4 splits on average scores , an anomaly. A point that needs 14 splits scores , a normal point. Few splits isolate a point when it lies far from the others, which is the idea of the method. Part H of the interactive lab isolates points with random splits.
Python step 9: Signals, features and clustering with NumPy
The Python step of this week is part of the Colab notebook, where every explanation stands next to a cell that runs it and the step closes with a quick check and exercises with immediate feedback. The printable lecture notes contain the same step together with the outputs of its code. The Colab button below opens the notebook at the step. Run the setup cell just above the step first, since the exercises use its check function.
Review cards
Select a card to turn it over.
Continue the week
The week continues with the simulation and the self-assessment of the interactive lab and with the Python step and the hands-on work of the Colab notebook. The week overview lists the discipline challenges, the weekly task and the research assignment.
Interactive lab Colab notebook Self-assessment Week overview and tasks
References
[1] Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd ed.). Springer. https://doi.org/10.1007/978-0-387-84858-7
[2] Chandola, V., Banerjee, A., & Kumar, V. (2009). Anomaly detection: A survey. ACM Computing Surveys, 41(3), 15. https://doi.org/10.1145/1541880.1541882
[3] Lloyd, S. (1982). Least squares quantization in PCM. IEEE Transactions on Information Theory, 28(2), 129-137. https://doi.org/10.1109/TIT.1982.1056489
[4] MacQueen, J. (1967). Some methods for classification and analysis of multivariate observations. In Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, Vol. 1 (pp. 281-297). University of California Press.
[5] Arthur, D., & Vassilvitskii, S. (2007). k-means++: The advantages of careful seeding. In Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete Algorithms (pp. 1027-1035). SIAM.
[6] Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53-65. https://doi.org/10.1016/0377-0427(87)90125-7
[7] Pearson, K. (1901). On lines and planes of closest fit to systems of points in space. The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science, 2(11), 559-572. https://doi.org/10.1080/14786440109462720
[8] Jolliffe, I. T., & Cadima, J. (2016). Principal component analysis: A review and recent developments. Philosophical Transactions of the Royal Society A, 374(2065), 20150202. https://doi.org/10.1098/rsta.2015.0202
[9] Ester, M., Kriegel, H.-P., Sander, J., & Xu, X. (1996). A density-based algorithm for discovering clusters in large spatial databases with noise. In Proceedings of the Second International Conference on Knowledge Discovery and Data Mining (KDD-96) (pp. 226-231). AAAI Press.
[10] Cooley, J. W., & Tukey, J. W. (1965). An algorithm for the machine calculation of complex Fourier series. Mathematics of Computation, 19(90), 297-301. https://doi.org/10.1090/S0025-5718-1965-0178586-1
[11] Randall, R. B., & Antoni, J. (2011). Rolling element bearing diagnostics: A tutorial. Mechanical Systems and Signal Processing, 25(2), 485-520. https://doi.org/10.1016/j.ymssp.2010.07.017
[12] Smith, W. A., & Randall, R. B. (2015). Rolling element bearing diagnostics using the Case Western Reserve University data: A benchmark study. Mechanical Systems and Signal Processing, 64-65, 100-131. https://doi.org/10.1016/j.ymssp.2015.04.021
[13] Liu, F. T., Ting, K. M., & Zhou, Z.-H. (2008). Isolation forest. In 2008 Eighth IEEE International Conference on Data Mining (pp. 413-422). https://doi.org/10.1109/ICDM.2008.17
[14] Lei, Y., Yang, B., Jiang, X., Jia, F., Li, N., & Nandi, A. K. (2020). Applications of machine learning to machine fault diagnosis: A review and roadmap. Mechanical Systems and Signal Processing, 138, 106587. https://doi.org/10.1016/j.ymssp.2019.106587