Code
import marimo as moUnsupervised learning
Motivation
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 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.

KMeans algorithm explained visually
Since KMeans tries to minimize inertia, which is itself a measure of how internally coherent the clusters are, it suffers from some drawbacks.
The remaining question is how to choose the right number of clusters K, which is usually done with silhouette analysis.
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:
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
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.HDBSCAN exists precisely to solve the problem of varying density.
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.
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.
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:
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.
eps in DBSCAN).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/lonwith 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.
_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))]Here we use HDBSCAN considering only lat and lon.
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.