Learning outcomes

After this lesson, you will be able to:

Core idea. Discovered structure is a hypothesis to investigate, not automatically a true classification of the world.

1. What does unsupervised learning mean?

Unsupervised learning is a family of machine-learning methods that analyse data without predefined target labels for each training object and identify structure, similarity, compact representations, or unusual observations.

In the previous lesson, we used pairs (X, y): an object's features and a known answer that a model learns to predict. Here, the starting point is usually a feature matrix X without a target variable y to reproduce.

The absence of target labels does not mean the algorithm has no objective. The researcher defines the question: group similar energy-use profiles, compress many measurements into a few components, or find observations that differ sharply from typical behaviour.

Do not confuse this with self-supervised learning. In self-supervised learning, the training signal is created from the data itself: for example, a model may learn to reconstruct a hidden part of an input or predict the next part of a sequence. This approach is widely used for pretraining large models. It is often treated as a separate setting, although terminology varies across the literature. Semi-supervised learning, by contrast, combines a small labeled dataset with a larger unlabeled one.

Imagine operating records from hundreds of buildings: temperature, humidity, energy use, time of day, and equipment mode. An algorithm may discover recurring profiles such as night operation, working days, or peak load. A person assigns meaningful names only after inspecting the groups.

Finding structure in dataSupervised learning uses features and known answers. Unsupervised learning receives features and searches for structure without target labels.SupervisedX — featuresy — known answersPredict y for new XUnsupervisedX — featuresy is not providedFind structure in X
The key distinction is whether target answers are supplied during training. Both settings require meaningful data and validation.

2. Clustering: finding similar observations

Clustering groups observations so that objects within a group are similar under a chosen criterion, while objects in different groups are less similar. There is no single universal definition of similarity.

The algorithm does not know what “similar” means in your domain. Group buildings by annual energy use and you may get one structure; group them by daily load shape and you may get another. The result depends on selected features, their scale, the distance measure, and algorithm settings.

K-means: groups around centres

K-means requires the number of groups, k, in advance. It places centres, assigns each observation to the nearest centre, recomputes each centre as the mean of its assigned observations, and repeats until assignments stabilise. It is a useful baseline for numeric features, but works best for compact groups of roughly comparable scale.

You must choose k. Different initial centres can produce different solutions, so implementations use multiple initialisations. K-means is sensitive to feature scales and outliers: a feature with large numeric values can dominate the distance calculation.

Hierarchical clustering

Hierarchical methods build a tree of merges or splits. In the agglomerative approach, every observation starts in its own group; nearby groups are then merged step by step. The tree can be inspected at different levels of detail, but the distance metric and linkage rule change the result.

DBSCAN: groups by density

DBSCAN searches for dense regions, can find irregularly shaped groups, and may mark isolated points as noise. It does not require the number of clusters as a direct input, but is sensitive to neighbourhood radius and minimum-neighbour settings. It can struggle when group densities differ substantially.

Clusters with different shapesThree clusters have different geometric properties: a compact group, an elongated group, and an irregular group with uneven density. Grey points represent noise not assigned to a cluster.Compact clusterElongated clusterUneven densityNoiseShape and density affect clustering results
The diagram illustrates different data structures. DBSCAN can identify irregularly shaped groups and mark isolated observations as noise; results depend on parameters and density.

3. Evaluating clusters without correct labels

There may be no ground-truth labels against which to compare the result directly. Evaluation is therefore more difficult than calculating classification accuracy.

Important: a high silhouette score does not prove that clusters are true, useful, or causal. It measures a geometric property in the selected feature space.

4. Dimensionality reduction and PCA

Dimensionality reduction transforms data from a space with many features into one with fewer coordinates while aiming to preserve selected properties of the original structure.

If each object has 80 measurements, it is difficult to see the overall picture. Dimensionality-reduction methods create compact representations for visualisation, noise reduction, or further analysis.

PCA (Principal Component Analysis) creates new axes—principal components—that are linear combinations of the original features. The first component points in the direction of greatest variance; subsequent components explain as much remaining variance as possible while being orthogonal to previous components. PCA does not select the “most important original features” and does not guarantee preservation of rare but important events.

t-SNE and UMAP are often used to visualise complex representations in two dimensions. Distances and group sizes on such maps can depend on parameters and randomness. Do not automatically interpret separated islands as objective classes.

Dimensionality reductionMany original features are transformed into fewer components.Original datamany featuresTransforme.g. PCAnew axesCompactrepresentationfewer coordinatesCompression inevitably loses some information
Dimensionality reduction simplifies representation but does not automatically preserve every property of the original data.

5. Anomaly detection

Anomaly detection searches for objects or events that differ substantially from expected behaviour or the bulk of observations in a chosen data representation.

Examples include an unusual building energy profile, a rare combination of equipment temperature and vibration, or an atypical sequence of user actions. An anomaly is not necessarily an error or a fault: it is a signal to investigate.

Isolation Forest attempts to isolate rare observations through random partitions. Local Outlier Factor compares a point’s local density with the density of its neighbours. Simple threshold rules can also help when physical limits or operating requirements define meaningful boundaries.

Distinguish a data outlier from a meaningful rare event. An unusual value may be a sensor error, an operating-mode change, a real fault, or a new but valid state. Do not automatically delete anomalies; first investigate their origin.

6. Worked example: building operating modes

Suppose we have hourly building records: outdoor temperature, energy use, humidity, occupancy, and time of day. The goal is to understand recurring operating modes—not to predict a predefined class.

  1. Frame the question. Find typical hourly or daily profiles.
  2. Choose the observation unit. For example, one building-day. Do not mix hourly and daily records without an explicit aggregation rule.
  3. Select features. Mean and peak load, night-time consumption, temperature range, and share of operating hours. Each measure needs units and a calculation period.
  4. Prepare features. Check missing values, duplicates, time zones, and scales. Scaling is especially important for distance-based methods.
  5. Compare methods. Start with K-means, then check whether hierarchical clustering or DBSCAN changes the conclusion.
  6. Validate the result. Inspect group profiles, stability, internal metrics, and domain interpretation.
  7. State a cautious conclusion. “Three recurring profiles were found in this dataset” is safer than “there are exactly three types of buildings”.

Practice task

Propose two feature sets for one task: (a) grouping buildings by consumption scale; (b) grouping them by daily load shape. For each, state the observation unit, a scaling approach, and one risk of misinterpretation. Explain why results may differ even though the buildings are the same.

Good-answer criterion: show that clusters depend on the research question and data representation; do not declare one result uniquely correct.

7. Limitations and a review checklist

Remember. Unsupervised learning helps explore data when target answers are unavailable. Its value is not that the algorithm “discovers the truth”, but that it proposes a testable structure which we compare with the original data, the task, and domain knowledge.

8. Python practice: K-means

This example creates synthetic points. The generator also returns teaching labels, but we discard them: the clustering algorithm receives only the feature matrix X.

from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# Create synthetic features; discard the generated reference labels.
X, _ = make_blobs(
    n_samples=300,
    centers=3,
    cluster_std=1.2,
    random_state=42
)

X_scaled = StandardScaler().fit_transform(X)
model = KMeans(n_clusters=3, n_init=10, random_state=42)
cluster_ids = model.fit_predict(X_scaled)

# Measure geometric separation, not semantic correctness.
score = silhouette_score(X_scaled, cluster_ids)
print("Silhouette score:", round(score, 3))
print("Cluster IDs:", sorted(set(cluster_ids)))

Explanation: make_blobs creates points; StandardScaler puts features on comparable scales; KMeans searches for three groups; silhouette_score measures geometric separation. Cluster IDs are technical identifiers: cluster 0 is not better or more important than cluster 1.

Environment: Python 3.9+ and a current scikit-learn release. Install with python -m pip install scikit-learn. In real projects, fit transformations only on data permitted for that stage of analysis.