Overview
Mapper draws a simplified skeleton of a data set. Choose a function that gives every point one number, called the filter or lens, such as a coordinate or the distance from the centre. Cut the range of that number into overlapping intervals and gather the points whose value falls in each one. Inside each slice, group nearby points into clusters. Every cluster becomes a node of a graph. Because the intervals overlap, a point can sit in two clusters from neighbouring slices, and whenever that happens the two nodes are joined by an edge. The result shows branches, loops and separate pieces of the data at a glance. A circle of points sliced by height becomes a ring of nodes.
A short history
Gurjeet Singh, Facundo Mémoli and Gunnar Carlsson introduced Mapper in 2007 at Stanford as a practical tool of topological data analysis. It is a discrete version of the Reeb graph from Morse theory: the data are covered by overlapping slices of a filter function, each slice is clustered, and overlapping clusters are joined. The result is a small graph whose branches and loops show structure that a scatter plot of two components can hide.
How it works
- Compute the filter value of every point: the configured
coordinate,normoreccentricity, or values you pass in yourself. - Cover the range of the filter with
n_intervalsintervals of equal length, each sharing the fractionoverlapwith the next. - For each interval, collect the points whose filter value lies inside it.
- Cluster those points by single linkage: two points share a cluster when a chain of steps no longer than
cluster_distanceconnects them. - Make one node per cluster, dropping clusters smaller than
min_cluster_size. - Join two nodes from different intervals with an edge when their clusters have at least one point in common.
- Read the graph: count connected components and independent loops, and colour nodes by their mean filter value.
Watch out for
- The graph depends strongly on the filter. A loop is seen only if the filter varies around it, so a poor filter can hide the structure you are looking for.
- Too few intervals or too much overlap merges everything into a line or a blob, and too many intervals with little overlap shatters the graph into fragments.
- A
cluster_distanceset too small makes every point its own node, and one set too large can bridge across a gap and erase a loop. - The output is a picture for exploration, not a test. Features should persist over a range of settings before you trust them.
- The template clusters with a full distance matrix per slice and one fixed threshold, which is a small version of Mapper suited to a few thousand points.
Use cases
When to use it
Exploring the overall shape of a data set, looking for branches, loops or distinct subgroups that a scatter plot of two principal components would flatten or hide.
In industry
- Cancer research
- Nicolau, Levine and Carlsson applied Mapper to breast tumour gene expression in 2011 and reported a subgroup of patients with very good survival that standard clustering had not separated.
- Sports analytics
- A widely cited analysis used Mapper on basketball player statistics to suggest more playing styles than the five traditional positions.
- Customer and risk analytics
- Analysts build Mapper graphs of customer or transaction features to find small, distinct segments that branch off from the main population.
Choosing it: what must hold
- A point cloud with a meaningful distance between points.
- A filter function that suits the question, such as a density estimate, an eccentricity measure or a principal component.
- Willingness to try several settings of the cover, overlap and clustering, since the graph depends on them.
- An exploratory goal; the output is a picture to interpret and follow up, not a test.
When to choose something else
| If | Use instead |
|---|---|
| You need a quantitative, parameter light summary of loops and voids | Persistent homology |
| You only want a two dimensional view of the data | t-SNE or UMAP from multivariate analysis |
| You only need a partition into groups | A clustering method such as k-means or DBSCAN |
Math foundations
The filter function
A function that gives each data point one number. The template offers a single coordinate, the distance from the centroid (
norm), and the mean distance to all other points (eccentricity).The cover
intervals of equal length , each starting a step after the previous one, so neighbours share a length . The length is chosen so that the last interval ends exactly at .
Slices and nodes
Each slice is the set of points whose filter value lies in interval . Clustering splits it into pieces , and each piece is one node of the graph.
Edges
Two nodes are linked when they share at least one data point. This construction is called the nerve of the cover: it records which pieces overlap and forgets everything else.
Loops in the graph
The number of independent cycles of a graph with nodes, edges and connected components. The template's
n_loopsuses exactly this.
Symbols
- the point cloud
- the filter function
- smallest and largest filter value
- number of intervals, n_intervals in the template
- overlap fraction between neighbouring intervals
- length of each interval
- interval i of the cover
- the points whose filter value lies in interval i
- cluster a found in slice i, one node of the graph
- the sets of nodes and edges
- number of connected components and of independent loops of the graph
Worked by hand
Filter values run from 0 to 10. Cover them with intervals and overlap . Then suppose the resulting graph has 6 nodes, 6 edges and 1 component.
Three intervals of length 5 that each share half their length with the next. A graph with 6 nodes, 6 edges and one component has exactly one loop.
Visual example
Loading the example.
Try this
- Click the four steps in order, then click nodes of the graph to see which points each one holds.
- Change the filter to distance from the centre and watch the ring's loop disappear from the graph.
- Lower the overlap to 0.05: neighbouring slices stop sharing points and the graph falls apart.
Code sample
import numpy as np
from impl import Mapper
from config import MapperConfig
angles = np.linspace(0, 2 * np.pi, 200, endpoint=False)
points = np.column_stack([np.cos(angles), np.sin(angles)]) # a circle
graph = Mapper(MapperConfig(n_intervals=6, overlap=0.3, cluster_distance=0.3)).fit(points)
print(len(graph["nodes"]), graph["edges"])
print(Mapper.n_components(graph), Mapper.n_loops(graph)) # 1 component, 1 loopRead the implementation (133 lines)
"""Mapper: a graph summary of the shape of a point cloud.
NumPy and the standard library only. Clustering is single linkage cut at a fixed distance, computed from the
full distance matrix of each slice, so the template suits clouds of up to a few thousand points.
"""
from __future__ import annotations
import numpy as np
try:
from .config import MapperConfig
except ImportError: # run from the template's own folder
from config import MapperConfig
def _pairwise(points: np.ndarray) -> np.ndarray:
"""Euclidean distance matrix (m, m) of points (m, d)."""
sq = np.sum(points * points, axis=1)
return np.sqrt(np.maximum(sq[:, None] + sq[None, :] - 2.0 * points @ points.T, 0.0))
class Mapper:
"""Builds the Mapper graph: nodes are clusters of slices of the data, edges join clusters that share points."""
def __init__(self, config: MapperConfig | None = None) -> None:
self.config = config or MapperConfig()
def filter_values(self, points: np.ndarray) -> np.ndarray:
"""The configured filter function evaluated at every point. points: (n, d), returns (n,)."""
kind = self.config.filter
if kind == "coordinate":
if self.config.coordinate >= points.shape[1]:
raise ValueError(f"coordinate {self.config.coordinate} is out of range for {points.shape[1]} columns")
return points[:, self.config.coordinate].copy()
if kind == "norm":
return np.linalg.norm(points - points.mean(axis=0), axis=1)
return _pairwise(points).sum(axis=1) / max(points.shape[0] - 1, 1)
def cover(self, low: float, high: float) -> np.ndarray:
"""The overlapping intervals covering [low, high], shape (n_intervals, 2).
All intervals have the same length, and each shares the fraction `overlap` of it with the next.
"""
k, g = self.config.n_intervals, self.config.overlap
span = high - low
length = span / (k - (k - 1) * g) if span > 0 else 1.0
starts = low + np.arange(k) * length * (1.0 - g)
intervals = np.column_stack([starts, starts + length])
intervals[-1, 1] = max(intervals[-1, 1], high) # guard the top end against rounding
return intervals
def cluster(self, points: np.ndarray) -> np.ndarray:
"""Single-linkage clusters at the configured distance. points: (m, d). Returns labels (m,), 0-based.
Two points share a cluster when a chain of points links them with every step at most
`cluster_distance`: the connected components of the neighbourhood graph.
"""
m = points.shape[0]
near = _pairwise(points) <= self.config.cluster_distance
labels = np.full(m, -1)
current = 0
for seed in range(m):
if labels[seed] >= 0:
continue
labels[seed] = current
frontier = [seed]
while frontier:
reached = np.flatnonzero(near[frontier].any(axis=0) & (labels < 0))
labels[reached] = current
frontier = reached.tolist()
current += 1
return labels
def fit(self, points, filter_values=None) -> dict:
"""Build the Mapper graph.
points: the data, shape (n, d).
filter_values: your own filter function evaluated at the points, shape (n,). When None, the
configured filter is used.
Returns a dict with
`nodes`: list of dicts {`interval`: index of the slice, `members`: sorted point indices,
`filter_mean`: mean filter value of the members},
`edges`: sorted list of (i, j), i < j, for nodes that share at least one point,
`intervals`: the cover, shape (n_intervals, 2),
`filter`: the filter values, shape (n,).
"""
points = np.asarray(points, dtype=float)
if points.ndim != 2 or points.shape[0] == 0:
raise ValueError(f"points must have shape (n, d) with n > 0, got {points.shape}")
if filter_values is None:
f = self.filter_values(points)
else:
f = np.asarray(filter_values, dtype=float).ravel()
if f.size != points.shape[0]:
raise ValueError("filter_values must have one value per point")
intervals = self.cover(float(f.min()), float(f.max()))
nodes = []
for k, (low, high) in enumerate(intervals):
inside = np.flatnonzero((f >= low) & (f <= high))
if inside.size == 0:
continue
labels = self.cluster(points[inside])
for label in range(labels.max() + 1):
members = inside[labels == label]
if members.size >= self.config.min_cluster_size:
nodes.append({"interval": k, "members": members, "filter_mean": float(f[members].mean())})
edges = []
for i in range(len(nodes)):
for j in range(i + 1, len(nodes)):
if nodes[i]["interval"] != nodes[j]["interval"] and np.intersect1d(
nodes[i]["members"], nodes[j]["members"], assume_unique=True).size:
edges.append((i, j))
return {"nodes": nodes, "edges": edges, "intervals": intervals, "filter": f}
@staticmethod
def n_components(graph: dict) -> int:
"""Number of connected components of the Mapper graph."""
parent = list(range(len(graph["nodes"])))
def find(i: int) -> int:
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
for i, j in graph["edges"]:
parent[find(i)] = find(j)
return len({find(i) for i in range(len(parent))})
@staticmethod
def n_loops(graph: dict) -> int:
"""Number of independent cycles of the graph: edges - nodes + components."""
return len(graph["edges"]) - len(graph["nodes"]) + Mapper.n_components(graph)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Sample 400 points on a unit circle with a little noise. Build Mapper(MapperConfig(n_intervals=6, overlap=0.5, cluster_distance=0.4)), call fit(points) and check that Mapper.n_components(graph) is 1 and Mapper.n_loops(graph) is 1. Then change overlap to 0 and, separately, cluster_distance to 3, and explain what each does to the graph.
Check on learning
- For points on a circle with the
coordinatefilter, the middle slices each give two nodes but the top and bottom slices give one. Why, and how does that produce a loop in the graph?A way to think about it
Picture a horizontal band cutting the circle. Near the middle it catches two separate arcs, near the top a single cap.
- With
overlapset to 0 the graph has no edges. Why does the algorithm need overlap at all?A way to think about it
An edge needs a point that belongs to two nodes from different slices. Ask where such a point could live.
- For the same circle, what graph would the
normfilter, distance from the centroid, produce? What does that teach about choosing a filter?A way to think about it
Every point on a circle is about the same distance from the centre, so think about how many slices actually contain points.
- You see a loop in the Mapper graph of real data. Name two checks that would raise your confidence that it is a feature of the data and not of the settings.
A way to think about it
Vary
n_intervals,overlapandcluster_distanceand see whether the loop survives. Also try a different filter or a random subsample of the points.