Skip to main content

Unsupervised Learning

Code
import marimo as mo

Unsupervised learning

Motivation

INPE paper

Clustering

There are different kinds of methods and clustering algorithms that group data. Deep down, these algorithms share a similar structure: they bring together data points based on the characteristics that describe them. They work on a tabular data matrix, so if your data is, e.g., water quality data for multiple sites with different quality parameters, those parameters make up the tabular data matrix the algorithms use to compute the grouping (clustering).

Clustering is very useful because it doesn’t need labels! No data point needs an associated annotation for the algorithm to learn, as in supervised learning; the algorithms simply use other techniques under the hood to compute how close the points are.

Let’s break these techniques down more carefully.

Here are some of the most widely used clustering algorithms.

  • KMeans
  • DBSCAN
  • Mean Shift
  • Spectral Clustering
  • HDBSCAN
  • Hierarchical Clustering

KMeans Clustering

KMeans is the most popular clustering algorithm. Its goal is simple: it tries to minimize the within-cluster variance, so that similar observations fall into the same cluster, while at the same time maximizing the distance between different clusters. This criterion is also known as inertia.

KMeans depends on the initial choice of K (the number of clusters). It works as follows:

1 - Given a value of K, initialize K centroids randomly; the points closest to each centroid are assigned to its cluster \(c_i\). 2 - Compute the distance between each point and the centroids, and reassign the point to a new cluster if that centroid is closer than its current one. 3 - After reassigning the points, update each cluster’s centroid by computing the mean of the cluster’s data. 4 - Steps 2 and 3 are repeated until the algorithm has minimized the distance between the points and their centroids.

gif

KMeans algorithm explained visually

Code
import altair as alt
from drawdata import ScatterWidget
Code
widget = mo.ui.anywidget(ScatterWidget(height=400))
widget
Code
data = widget.data_as_pandas
Code
data
Code
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
Code
kmeans = KMeans(n_clusters=5,
               init="k-means++",
               )
Code
# fit
kmeans.fit(data[['x','y']])
Code

# assign each point to a cluster
clusters = kmeans.predict(data[['x','y']])
data['clusters'] = clusters
Code
alt.Chart(data).mark_circle(size=40).encode(
    x="x",
    y="y",
    color="clusters",
    tooltip = ["clusters"]
).interactive()

Drawbacks of KMeans

Since KMeans tries to minimize inertia, which is itself a measure of how internally coherent the clusters are, it suffers from some drawbacks.

  • Inertia assumes that clusters are convex and isotropic, so KMeans tends to perform poorly when clusters are elongated.
  • In high-dimensional spaces, Euclidean distances tend to become inflated (the curse of dimensionality). Reducing these high-dimensional spaces with PCA (principal component analysis) can alleviate the problem.
  • KMeans works very well for clusters that are roughly spherical with a Gaussian distribution.
  • It struggles when clusters are not the same size.

The remaining question is how to choose the right number of clusters K, which is usually done with silhouette analysis.

Code
x = data[['x','y']]
wcss =[]
for i in range(2,10):
    model = KMeans(n_clusters=i)
    y_kmeans = model.fit_predict(x)
    wcss.append(model.inertia_)
Code
import matplotlib.pyplot as plt
Code
plt.plot(range(2,10),wcss,'go--')
plt.xlabel('Number of cluster')
plt.ylabel('Within Cluster Sum of Squares - Inertia')
Code
from sklearn.cluster import DBSCAN

DBSCAN

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) follows a very different logic from KMeans: instead of minimizing the distance to centroids, it groups points that are densely connected in space. The core idea is that a cluster is a region with a high density of points, separated from other regions by areas of low density.

The algorithm depends on two parameters:

  • eps (ε): the neighborhood radius around each point.
  • min_samples: the minimum number of points that must exist within that radius for the region to be considered dense.

Based on this, each point is classified as one of three types:

1 - Core point: has at least min_samples neighbors within radius eps. 2 - Border point: is within radius eps of a core point, but doesn’t have enough neighbors to be a core point itself. 3 - Noise point: neither core nor border, i.e. it doesn’t belong to any cluster (it gets the label -1).

Unlike KMeans, DBSCAN doesn’t require us to set the number of clusters in advance: it figures that out from the density of the data. It can also identify clusters with arbitrary shapes (not just spherical) and naturally separates outliers as noise.

Visualizing the DBSCAN algorithm

Code
eps_slider = mo.ui.slider(start=1, stop=100, step=1, value=20, label="eps")
min_samples_slider = mo.ui.slider(start=1, stop=20, step=1, value=5, label="min_samples")
mo.hstack([eps_slider, min_samples_slider])
Code
dbscan = DBSCAN(eps=eps_slider.value, 
                min_samples=min_samples_slider.value
               )
dbscan_labels = dbscan.fit_predict(data[['x', 'y']])
data['dbscan_cluster'] = dbscan_labels
Code
alt.Chart(data).mark_circle(size=40).encode(
    x="x",
    y="y",
    color="dbscan_cluster:N",
    tooltip=["dbscan_cluster"]
).interactive()

Drawbacks of DBSCAN

  • Choosing eps and min_samples is not trivial and strongly affects the result. Wrong values can lump everything into a single cluster or label almost everything as noise.
  • DBSCAN assumes all clusters have similar density. When the data has clusters with very different densities, it tends to fail: either it treats the sparser clusters as noise, or it merges nearby dense clusters.
  • In high-dimensional spaces, the notion of density (distance) also suffers from the curse of dimensionality, just as with KMeans.

HDBSCAN exists precisely to solve the problem of varying density.

HDBSCAN

HDBSCAN (Hierarchical DBSCAN) extends DBSCAN into a hierarchical method, removing the need to choose a fixed eps. Instead of a single radius applied to the whole dataset, HDBSCAN builds a hierarchy of clusters across varying densities and then “condenses” that hierarchy, extracting the clusters that are most stable across that variation.

In short, the algorithm:

1 - Builds a distance graph based on a density metric (mutual reachability distance), which shrinks distances between points in dense regions and stretches them in sparse regions.

2 - Builds a minimum spanning tree over this graph.

3 - Converts this tree into a cluster hierarchy (dendrogram).

4 - “Condenses” the hierarchy, keeping only the cluster splits that persist the longest (the most stable), and extracts the final clusters from this condensed tree.

The main parameter is now min_cluster_size, much more intuitive than eps. As a result, HDBSCAN handles clusters of different densities well while keeping DBSCAN’s advantages: no K needed in advance, and it identifies noise (-1) naturally.

Code
from sklearn.cluster import HDBSCAN
Code
min_cluster_size_slider = mo.ui.slider(start=2, stop=50, step=1, value=5, label="min_cluster_size")
min_cluster_size_slider
Code
hdbscan_model = HDBSCAN(min_cluster_size=min_cluster_size_slider.value)
hdbscan_labels = hdbscan_model.fit_predict(data[['x', 'y']])
data['hdbscan_cluster'] = hdbscan_labels
Code
alt.Chart(data).mark_circle(size=40).encode(
    x="x",
    y="y",
    color="hdbscan_cluster:N",
    tooltip=["hdbscan_cluster"]
).interactive()

Spectral Clustering

Spectral Clustering approaches the grouping problem in a completely different way from the previous algorithms. Instead of working directly on the original coordinates of the data, it treats the problem as a graph theory problem.

Its logic goes something like this:

1 - Build a similarity graph between the points (for example, using k-nearest neighbors or a Gaussian kernel function), where each point is a node and the edges represent how “close” or similar two points are.

2 - From this graph, compute the Laplacian matrix.

3 - Compute the eigenvectors of this Laplacian matrix associated with the smallest eigenvalues (a lot of linear algebra here); this is the “dimensionality reduction” step that gives the method its name (spectrum = set of eigenvalues).

4 - These eigenvectors form a new representation space for the data, in which clusters that originally had complex, non-convex shapes become much more separable.

5 - Apply a simple algorithm, such as KMeans, in this new space to get the final clusters.

So, like KMeans, Spectral Clustering still requires us to set the number of clusters (n_clusters) in advance; the difference is that it can capture non-convex structures (spirals, moons, rings) that KMeans can’t, precisely because it works on the similarity between points rather than the direct distance to a centroid. On the other hand, it is computationally more expensive, since it relies on the spectral decomposition of a matrix that grows with the number of samples.

Code
spectral_k_slider = mo.ui.slider(start=2, stop=10, step=1, value=4, label="n_clusters")
spectral_k_slider
Code
from sklearn.cluster import SpectralClustering
Code
spectral_model = SpectralClustering(
    n_clusters=spectral_k_slider.value,
    affinity="nearest_neighbors",
    random_state=42,
)
spectral_labels = spectral_model.fit_predict(data[['x', 'y']])
data['spectral_cluster'] = spectral_labels
Code
alt.Chart(data).mark_circle(size=40).encode(
    x="x",
    y="y",
    color="spectral_cluster:N",
    tooltip=["spectral_cluster"]
).interactive()

Hierarchical Clustering

Hierarchical Clustering builds a hierarchy of clusters instead of a single partition of the data. The most common variant is agglomerative (bottom-up):

1 - Each point starts as its own cluster.

2 - At each step, the two “closest” clusters are merged into a single cluster.

3 - Step 2 repeats until only one cluster containing all the points remains.

The result is a dendrogram: a tree that records the order and distance at which clusters were merged. The big advantage is that we don’t need to decide the number of clusters before running the algorithm. We build the hierarchy first and decide afterwards, by “cutting” the dendrogram at the desired height, how many clusters we want to extract.

The way we measure the distance between two clusters (not just between two points) is called linkage, and there are a few common choices:

  • single: distance between the closest points of each cluster (tends to create elongated/chained clusters).
  • complete: distance between the farthest points of each cluster (tends to create more compact clusters).
  • average: mean of the distances between all pairs of points of the two clusters.
  • ward: minimizes the increase in within-cluster variance when merging two clusters; usually the most used in practice, and the closest in spirit to KMeans inertia.
Code
from scipy.cluster.hierarchy import dendrogram, linkage
Code
linkage_matrix = linkage(data[['x', 'y']], method="ward")
Code
plt.figure(figsize=(10, 5))
dendrogram(linkage_matrix)
plt.title("Dendrogram. Hierarchical Clustering")
plt.xlabel("Samples")
plt.ylabel("Distance")

Looking at the dendrogram, we can choose where to “cut” the tree (a horizontal line). The lower the cut, the more clusters we get; the higher, the fewer (and more heterogeneous) clusters. In practice we use scikit-learn’s AgglomerativeClustering, passing the desired number of clusters directly, and it makes the cut for us internally.

Code
from sklearn.cluster import AgglomerativeClustering
Code
hier_n_clusters_slider = mo.ui.slider(start=2, stop=10, step=1, value=4, label="n_clusters")
hier_n_clusters_slider
Code
hier_model = AgglomerativeClustering(n_clusters=hier_n_clusters_slider.value, linkage="ward")
hier_labels = hier_model.fit_predict(data[['x', 'y']])
data['hier_cluster'] = hier_labels
Code
alt.Chart(data).mark_circle(size=40).encode(
    x="x",
    y="y",
    color="hier_cluster:N",
    tooltip=["hier_cluster"]
).interactive()

Drawbacks of Hierarchical Clustering

  • High computational cost: the classic implementation is O(n²) in memory and O(n² log n) to O(n³) in time, which makes it unfeasible for very large datasets (unlike KMeans/DBSCAN, which scale better).
  • Once two points are merged into a cluster, that decision is final: the algorithm never undoes earlier merges, so a grouping mistake early in the process propagates.
  • The choice of linkage and distance metric strongly affects the shape of the clusters found (just like eps in DBSCAN).
  • On the plus side, the dendrogram is a very rich visualization and interpretation tool, useful when we want to understand the similarity structure of the data at multiple scales, not just get a single partition.
Code
import plotly.express as px

Application: Spatial Clustering of Water Quality Stations

At the start we mentioned the example of water quality data collected at multiple sites; now let’s build that use case for real, combining clustering with geospatial data.

Scenario: a network of water quality monitoring stations spread across a watershed. Each station has a location (lat, lon) and measurements of quality parameters such as turbidity and dissolved oxygen. Some stations are physically close because they monitor the same stretch of river or the same sub-basin, while others are isolated.

The question we want to answer with clustering is: do stations that are geographically close also have similar water quality? Or are there sub-regions, within the same geographic area, that behave very differently (for example, because of a point source of pollution)?

Let’s compare two approaches:

1 - Clustering using only geographic coordinates (lat/lon): groups stations purely by spatial proximity. 2 - Clustering using coordinates + water quality parameters (standardized): groups stations that are similar both in space and in measured water quality.

This shows in practice why the choice of which features go into the data matrix completely changes the clustering result, even with the same algorithm.

Note: to keep things simple, we treat lat/lon with Euclidean distance. In a real application, for larger geographic areas, you should use an appropriate distance metric (e.g. haversine) or project the coordinates to a metric CRS before computing distances, a topic we covered in the GIS and RS fundamentals module.

Code
_rng = np.random.default_rng(42)

_cluster_centers = [
    (-15.72, -47.93),  # zone 1 - upper course
    (-15.79, -47.88),  # zone 2 - urban stretch
    (-15.74, -47.80),  # zone 3 - rural stretch
]
_turbidity_means = [8, 45, 12]
_oxygen_means = [8.5, 4.0, 7.8]

_rows = []
for _zone, ((_lat_c, _lon_c), _turb_m, _ox_m) in enumerate(
    zip(_cluster_centers, _turbidity_means, _oxygen_means)
):
    for _ in range(15):
        _rows.append({
            "lat": _lat_c + _rng.normal(0, 0.006),
            "lon": _lon_c + _rng.normal(0, 0.006),
            "turbidity": max(0, _rng.normal(_turb_m, 3)),
            "oxygen": max(0, _rng.normal(_ox_m, 0.6)),
            "zone": f"zona_{_zone + 1}",
        })

# isolated / anomalous stations (e.g. faulty sensor or point source of pollution)
for _ in range(5):
    _rows.append({
        "lat": _rng.uniform(-15.82, -15.70),
        "lon": _rng.uniform(-47.97, -47.76),
        "turbidity": _rng.random(60, 90),
        "oxygen": _rng.random(1.5, 3.0),
        "zone": "anomalia",
    })

stations = pd.DataFrame(_rows)
stations["station_id"] = [f"st_{_i:02d}" for _i in range(len(stations))]
Code
stations
Code
px.scatter_map(
    stations,
    lat="lat",
    lon="lon",
    color="turbidity",
    size="turbidity",
    hover_name="station_id",
    hover_data=["oxygen", "zone"],
    zoom=10,
    map_style="open-street-map",
    title="Monitoring stations (color = turbidity)",
)

Clustering by location only

Here we use HDBSCAN considering only lat and lon.

Code
geo_min_cluster_slider = mo.ui.slider(start=2, stop=15, step=1, value=4, label="min_cluster_size (geo)")
geo_min_cluster_slider
Code
geo_model = HDBSCAN(min_cluster_size=geo_min_cluster_slider.value)
stations["geo_cluster"] = geo_model.fit_predict(stations[["lat", "lon"]])
Code
px.scatter_map(
    stations,
    lat="lat",
    lon="lon",
    color="geo_cluster",
    hover_name="station_id",
    hover_data=["turbidity", "oxygen", "zone"],
    zoom=10,
    map_style="open-street-map",
    title="Clusters by location (lat/lon)",
)

Clustering by location + water quality

Now we add turbidity and dissolved oxygen to the data matrix. Since these variables are on very different scales from lat/lon (and from each other), we need to standardize them (StandardScaler) before computing distances.

We’ll deal with standardization a lot from here on, because it is essential for our ML algorithms to converge. If we don’t standardize, the variable with the largest magnitude dominates the calculation.

Code
from sklearn.preprocessing import StandardScaler
Code
combined_min_cluster_slider = mo.ui.slider(start=2, stop=15, step=1, value=4, label="min_cluster_size (combined)")
combined_min_cluster_slider
Code
combined_features = stations[["lat", "lon", "turbidity", "oxygen"]]
combined_scaled = StandardScaler().fit_transform(combined_features)

combined_model = HDBSCAN(min_cluster_size=combined_min_cluster_slider.value)
stations["combined_cluster"] = combined_model.fit_predict(combined_scaled)
Code
px.scatter_map(
    stations,
    lat="lat",
    lon="lon",
    color="combined_cluster",
    hover_name="station_id",
    hover_data=["turbidity", "oxygen", "zone"],
    zoom=10,
    map_style="open-street-map",
    title="Clusters by location + water quality",
)

Water quality variables only

Code
water_features = stations[["turbidity", "oxygen"]]
water_scaled = StandardScaler().fit_transform(water_features)

water_model = HDBSCAN(min_cluster_size=5)
stations["water_cluster"] = water_model.fit_predict(water_scaled)
Code
px.scatter_map(
    stations,
    lat="lat",
    lon="lon",
    color="water_cluster",
    hover_name="station_id",
    hover_data=["turbidity", "oxygen", "zone"],
    zoom=10,
    map_style="open-street-map",
    title="Clusters by water quality only",
)

What changes between the two approaches?

  • In geographic clustering, physically close stations end up in the same group regardless of water quality. Even the scattered “anomalous” stations tend to become noise (-1) because they are spatially isolated.
  • In combined clustering, the urban zone (high turbidity, low oxygen) tends to separate from the rural/upper-course zone even when they are geographically close, and stations with extreme water quality values (even near a “normal” geographic cluster) can become noise, flagging possible faulty sensors or pollution points to investigate.
  • This comparison is exactly the kind of exploratory analysis clustering enables: discovering structure in data without ready-made labels, whether to plan new monitoring stations, identify risk zones, or flag sensors for inspection.

References