In this notebook we explore a few of the core features included in giotto-tda
's implementation of the Mapper algorithm.
If you are looking at a static version of this notebook and would like to run its contents, head over to GitHub and download the source.
License: AGPLv3
# Data wrangling
import numpy as np
import pandas as pd # Not a requirement of giotto-tda, but is compatible with the gtda.mapper module
# Data viz
from gtda.plotting import plot_point_cloud
# TDA magic
from gtda.mapper import (
CubicalCover,
make_mapper_pipeline,
Projection,
plot_static_mapper_graph,
plot_interactive_mapper_graph,
MapperInteractivePlotter
)
# ML tools
from sklearn import datasets
from sklearn.cluster import DBSCAN
from sklearn.decomposition import PCA
As a simple example, let's generate a two-dimensional point cloud of two concentric circles. The goal will be to examine how Mapper can be used to generate a topological graph that captures the salient features of the data.
data, _ = datasets.make_circles(n_samples=5000, noise=0.05, factor=0.3, random_state=42)
plot_point_cloud(data)
Given a dataset ${\cal D}$ of points $x \in \mathbb{R}^n$, the basic steps behind Mapper are as follows:
giotto-tda
, you can import a variety of filter functions as follows:from gtda.mapper.filter import FilterFunctionName
from gtda.mapper.cover import CoverName
scikit-learn
's clustering methods or an implementation of agglomerative clustering in giotto-tda
:# scikit-learn method
from sklearn.cluster import ClusteringAlgorithm
# giotto-tda method
from gtda.mapper.cluster import FirstSimpleGap
giotto-tda
.These four steps are implemented in the MapperPipeline
object that mimics the Pipeline
class from scikit-learn
. We provide a convenience function make_mapper_pipeline
that allows you to pass the choice of filter function, cover, and clustering algorithm as arguments. For example, to project our data onto the $x$- and $y$-axes, we could setup the pipeline as follows:
# Define filter function – can be any scikit-learn transformer
filter_func = Projection(columns=[0, 1])
# Define cover
cover = CubicalCover(n_intervals=10, overlap_frac=0.3)
# Choose clustering algorithm – default is DBSCAN
clusterer = DBSCAN()
# Configure parallelism of clustering step
n_jobs = 1
# Initialise pipeline
pipe = make_mapper_pipeline(
filter_func=filter_func,
cover=cover,
clusterer=clusterer,
verbose=False,
n_jobs=n_jobs,
)
With the Mapper pipeline at hand, it is now a simple matter to visualise it. To warm up, let's examine the graph in two-dimensions using the default arguments of giotto-tda
's plotting function:
fig = plot_static_mapper_graph(pipe, data)
fig.show(config={'scrollZoom': True})
By default, nodes are coloured according to the average row index of the data points they represent.
From the figure we can see that we have captured the salient topological features of our underlying data, namely two holes!
In this example, it is more instructive to colour by the average values of the $x$- and $y$-coordinates. This can be achieved by passing the input data again as the keyword argument color_data
. In general, any numpy
array or pandas
dataframe explicitly passed as color_data
will be used to calculate one colouring per column present. A dropdown menu is automatically created if color_data
has more than one column, to easily switch between column-based colourings.
At the same time, let's configure the choice of colorscale:
plotly_params = {"node_trace": {"marker_colorscale": "Blues"}}
fig = plot_static_mapper_graph(
pipe, data, color_data=data, plotly_params=plotly_params
)
fig.show(config={'scrollZoom': True})
Even finer control over the colouring can be achieved by making use of the additional keyword arguments color_features
and node_color_statistic
. The former can be a scikit-learn
transformer or a list of indices or column names to select from the data. For example, coloring by a PCA component can be neatly implemented as follows:
# Initialise estimator to color graph by
pca = PCA(n_components=1)
fig = plot_static_mapper_graph(
pipe, data, color_data=data, color_features=pca
)
fig.show(config={'scrollZoom': True})
node_color_statistic
refers to the function used to extract single colour values for each node, starting from the values of color_features
at each data point. The default, as we have seen, is np.mean
. But any other callable is acceptable which sends column vectors to scalars:
fig = plot_static_mapper_graph(
pipe, data, color_data=data, color_features=pca, node_color_statistic=lambda x: np.mean(x) / 2
)
fig.show(config={'scrollZoom': True})
If you prefer to just input custom node colours directly, you can do so by passing a numpy
array or pandas
dataframe of the correct length as node_color_statistic
. For example (see "Run the Mapper pipeline" below), the Mapper nodes for this particular Mapper pipeline would be as follows:
graph = pipe.fit_transform(data)
node_elements = graph.vs["node_elements"]
print(f"There are {len(node_elements)} nodes.\nThe first node consists of row indices {node_elements[0]}.")
Let us try this:
fig = plot_static_mapper_graph(
pipe, data, node_color_statistic=np.arange(len(node_elements))
)
fig.show(config={'scrollZoom': True})
It is also possible to feed plot_static_mapper_graph
a pandas DataFrame:
df = pd.DataFrame(data, columns=["x", "y"])
df.head()
Before plotting we need to update the Mapper pipeline to know about the projection onto the column names. This can be achieved using the set_params
method as follows:
pipe.set_params(filter_func=Projection(columns=["x", "y"]));
fig = plot_static_mapper_graph(pipe, df, color_data=df)
fig.show(config={'scrollZoom': True})
Often one has a dataset of observations, each belonging to a category (e.g. a country or region name). It can be very useful to visualize the distributions of each category in the nodes of the Mapper graph. As a trivial example, let us add a categorical column to our dataframe, with value equal to "A"
for the outer circle, and "B"
for the inner one:
df["Circle"] = df["x"] ** 2 + df["y"] ** 2 < 0.25
df["Circle"] = df["Circle"].replace([False, True], ["A", "B"])
To visualize the proportions of data points in each Mapper node belonging to either circle, we can create a dataframe of one-hot encodings of the categorical variable "Circle"
, and pass it to plot_static_mapper_graph
as color_data
:
color_data = pd.get_dummies(df["Circle"], prefix="Circle")
fig = plot_static_mapper_graph(pipe, df[["x", "y"]], color_data=color_data)
fig.show(config={'scrollZoom': True})
The dropdown menu allows us to quickly switch colourings according to each category, without needing to recompute the underlying graph.
By default, plot_static_mapper_graph
uses the Kamada–Kawai algorithm for the layout; however any of the layout algorithms defined in python-igraph are supported (see here for a list of possible layouts). For example, we can switch to the Fruchterman–Reingold layout as follows:
# Reset back to numpy projection
pipe.set_params(filter_func=Projection(columns=[0, 1]));
fig = plot_static_mapper_graph(
pipe, data, layout="fruchterman_reingold", color_data=data
)
fig.show(config={'scrollZoom': True})
It is also possible to visualise the Mapper graph in 3 dimensions by configuring the layout_dim
argument:
fig = plot_static_mapper_graph(pipe, data, layout_dim=3, color_data=data)
fig.show(config={'scrollZoom': True})
In general, node sizes are proportional to the number of dataset elements contained in the nodes. Sometimes, however, the default scale leads to graphs which are difficult to decipher, due to e.g. excessively small nodes. The node_scale
parameter can be used to configure this scale.
node_scale = 30
fig = plot_static_mapper_graph(pipe, data, layout_dim=3, node_scale=node_scale)
fig.show(config={'scrollZoom': True})
Behind the scenes of plot_static_mapper_graph
is a MapperPipeline
object pipe
that can be used like a typical scikit-learn
estimator. For example, to extract the underlying graph data structure we can do the following:
graph = pipe.fit_transform(data)
The resulting graph is a python-igraph object which stores node metadata in the form of attributes. We can access this data as follows:
graph.vs.attributes()
Here 'pullback_set_label'
and 'partial_cluster_label'
refer to the interval and cluster sets described above. 'node_elements'
refers to the indices of our original data that belong to each node. For example, to find which points belong to the first node of the graph we can access the desired data as follows:
node_id = 0
node_elements = graph.vs["node_elements"]
print(f"""
Node ID: {node_id}
Node elements: {node_elements[node_id]}
Data points: {data[node_elements[node_id]]}
""")
In some cases, the list of filter functions provided in gtda.mapper.filter.py
or scikit-learn
may not be sufficient for the task at hand. In such cases, one can pass any callable to the pipeline that acts row-wise on the input data. For example, we can project by taking the sum of the $(x,y)$ coordinates as follows:
filter_func = np.sum
pipe = make_mapper_pipeline(
filter_func=filter_func,
cover=cover,
clusterer=clusterer,
verbose=True,
n_jobs=n_jobs,
)
fig = plot_static_mapper_graph(pipe, data)
fig.show(config={'scrollZoom': True})
In general, building useful Mapper graphs requires some iteration through the various parameters in the cover and clustering algorithm. To simplify that process, giotto-tda
provides an interactive figure that can be configured in real time by tweaking the pipeline hyperparameters. You can produce it in two ways, namely:
plot_interactive_mapper_graph
function in a similar same way as plot_static_mapper_graph
;pipe = make_mapper_pipeline()
# Generate interactive widget
plot_interactive_mapper_graph(pipe, data, color_data=data)
giotto-tda
0.5.0) in an object-oriented way, by instantiating a MapperInteractivePlotter
onject and then calling its plot
method to create the widget.# Create the plotter object
MIP = MapperInteractivePlotter(pipe, data)
# Generate interactive widget
MIP.plot(color_data=data)
The advantage of using the class API with MapperInteractivePlotter
is that, once you are done tweaking the hyperparameters, you can inspect the latest state of the objects (graph, colours, pipeline, inner figure) which got changed during the interactive session.
print("Attributes created by `.plot` and updated during the interactive session:\n",
[attr for attr in dir(MIP) if attr.endswith("_") and attr[0] != "_"])
In the widgets, if invalid parameters are selected, the Show logs checkbox can be used to see what went wrong.
To see the interactive outputs above, please download the notebook from GitHub and execute it locally.