Commit d2cde4cb authored by Tiago Peixoto's avatar Tiago Peixoto
Browse files

Add network reconstruction to inference HOWTO

parent 57d7c7ec
......@@ -83,6 +83,8 @@ release = gt_version.split()[0]
# for source files.
exclude_trees = ['.build']
exclude_patterns = ['**/_*.rst']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
Background: Nonparametric statistical inference
A common task when analyzing networks is to characterize their
structures in simple terms, often by dividing the nodes into modules or
`"communities" <>`__.
A principled approach to perform this task is to formulate `generative
models <>`_ that include
the idea of "modules" in their descriptions, which then can be detected
by `inferring <>`_
the model parameters from data. More precisely, given the partition
:math:`\boldsymbol b = \{b_i\}` of the network into :math:`B` groups,
where :math:`b_i\in[0,B-1]` is the group membership of node :math:`i`,
we define a model that generates a network :math:`\boldsymbol G` with a
.. math::
:label: model-likelihood
P(\boldsymbol G|\boldsymbol\theta, \boldsymbol b)
where :math:`\boldsymbol\theta` are additional model parameters that
control how the node partition affects the structure of the
network. Therefore, if we observe a network :math:`\boldsymbol G`, the
likelihood that it was generated by a given partition :math:`\boldsymbol
b` is obtained via the `Bayesian
<>`_ posterior probability
.. math::
:label: model-posterior-sum
P(\boldsymbol b | \boldsymbol G) = \frac{\sum_{\boldsymbol\theta}P(\boldsymbol G|\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)}{P(\boldsymbol G)}
where :math:`P(\boldsymbol\theta, \boldsymbol b)` is the `prior
probability <>`_ of the
model parameters, and
.. math::
:label: model-evidence
P(\boldsymbol G) = \sum_{\boldsymbol\theta,\boldsymbol b}P(\boldsymbol G|\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)
is called the `evidence`, and corresponds to the total probability of
the data summed over all model parameters. The particular types of model
that will be considered here have "hard constraints", such that there is
only one choice for the remaining parameters :math:`\boldsymbol\theta`
that is compatible with the generated network, such that
Eq. :eq:`model-posterior-sum` simplifies to
.. math::
:label: model-posterior
P(\boldsymbol b | \boldsymbol G) = \frac{P(\boldsymbol G|\boldsymbol\theta, \boldsymbol b)P(\boldsymbol\theta, \boldsymbol b)}{P(\boldsymbol G)}
with :math:`\boldsymbol\theta` above being the only choice compatible with
:math:`\boldsymbol G` and :math:`\boldsymbol b`. The inference procedures considered
here will consist in either finding a network partition that maximizes
Eq. :eq:`model-posterior`, or sampling different partitions according
its posterior probability.
As we will show below, this approach also enables the comparison of
`different` models according to statistical evidence (a.k.a. `model
Minimum description length (MDL)
We note that Eq. :eq:`model-posterior` can be written as
.. math::
P(\boldsymbol b | \boldsymbol G) = \frac{\exp(-\Sigma)}{P(\boldsymbol G)}
.. math::
:label: model-dl
\Sigma = -\ln P(\boldsymbol G|\boldsymbol\theta, \boldsymbol b) - \ln P(\boldsymbol\theta, \boldsymbol b)
is called the **description length** of the network :math:`\boldsymbol
G`. It measures the amount of `information
<>`_ required to
describe the data, if we `encode
<>`_ it using the
particular parametrization of the generative model given by
:math:`\boldsymbol\theta` and :math:`\boldsymbol b`, as well as the
parameters themselves. Therefore, if we choose to maximize the posterior
distribution of Eq. :eq:`model-posterior` it will be fully equivalent to
the so-called `minimum description length
method. This approach corresponds to an implementation of `Occam's razor
<>`_, where the `simplest`
model is selected, among all possibilities with the same explanatory
power. The selection is based on the statistical evidence available, and
therefore will not `overfit
<>`_, i.e. mistake stochastic
fluctuations for actual structure. In particular this means that we will
not find modules in networks if they could have arisen simply because of
stochastic fluctuations, as they do in fully random graphs
The stochastic block model (SBM)
The `stochastic block model
<>`_ is arguably
the simplest generative process based on the notion of groups of
nodes [holland-stochastic-1983]_. The `microcanonical
<>`_ formulation
[peixoto-nonparametric-2017]_ of the basic or "traditional" version takes
as parameters the partition of the nodes into groups
:math:`\boldsymbol b` and a :math:`B\times B` matrix of edge counts
:math:`\boldsymbol e`, where :math:`e_{rs}` is the number of edges
between groups :math:`r` and :math:`s`. Given these constraints, the
edges are then placed randomly. Hence, nodes that belong to the same
group possess the same probability of being connected with other
nodes of the network.
An example of a possible parametrization is given in the following
.. testcode:: sbm-example
import os
except FileNotFoundError:
g = gt.load_graph("")
gt.graph_draw(g, pos=g.vp.pos, vertex_size=10,,
edge_gradient=g.new_ep("vector<double>", val=[0]),
ers =
from pylab import *
xlabel("Group $r$")
ylabel("Group $s$")
.. table::
:class: figure
|.. figure:: sbm-example-ers.svg |.. figure:: sbm-example.svg |
| :width: 300px | :width: 300px |
| :align: center | :align: center |
| | |
| Matrix of edge counts | Generated network. |
| :math:`\boldsymbol e` between | |
| groups. | |
.. note::
We emphasize that no constraints are imposed on what `kind` of
modular structure is allowed, as the matrix of edge counts :math:`e`
is unconstrained. Hence, we can detect the putatively typical pattern
of `"community structure"
<>`_, i.e. when
nodes are connected mostly to other nodes of the same group, if it
happens to be the most likely network description, but we can also
detect a large multiplicity of other patterns, such as `bipartiteness
<>`_, core-periphery,
and many others, all under the same inference framework.
Although quite general, the traditional model assumes that the edges are
placed randomly inside each group, and because of this the nodes that
belong to the same group tend to have very similar degrees. As it turns
out, this is often a poor model for many networks, which possess highly
heterogeneous degree distributions. A better model for such networks is
called the `degree-corrected` stochastic block model
[karrer-stochastic-2011]_, and it is defined just like the traditional
model, with the addition of the degree sequence :math:`\boldsymbol k =
\{k_i\}` of the graph as an additional set of parameters (assuming again
a microcanonical formulation [peixoto-nonparametric-2017]_).
The nested stochastic block model
The regular SBM has a drawback when applied to large networks. Namely,
it cannot be used to find relatively small groups, as the maximum number
of groups that can be found scales as
:math:`B_{\text{max}}=O(\sqrt{N})`, where :math:`N` is the number of
nodes in the network, if Bayesian inference is performed
[peixoto-parsimonious-2013]_. In order to circumvent this, we need to
replace the noninformative priors used by a hierarchy of priors and
hyperpriors, which amounts to a `nested SBM`, where the groups
themselves are clustered into groups, and the matrix :math:`e` of edge
counts are generated from another SBM, and so on recursively
[peixoto-hierarchical-2014]_, as illustrated below.
.. figure:: nested-diagram.*
:width: 400px
:align: center
Example of a nested SBM with three levels.
With this model, the maximum number of groups that can be inferred
scales as :math:`B_{\text{max}}=O(N/\log(N))`. In addition to being able
to find small groups in large networks, this model also provides a
multilevel hierarchical description of the network. With such a
description, we can uncover structural patterns at multiple scales,
representing different levels of coarse-graining.
.. _weights:
Edge weights and covariates
Very often networks cannot be completely represented by simple graphs,
but instead have arbitrary "weights" :math:`x_{ij}` on the edges. Edge
weights can be continuous or discrete numbers, and either strictly
positive or positive or negative, depending on context. The SBM can be
extended to cover these cases by treating edge weights as covariates
that are sampled from some distribution conditioned on the node
partition [aicher-learning-2015]_ [peixoto-weighted-2017]_, i.e.
.. math::
P(\boldsymbol x,\boldsymbol G|\boldsymbol b) =
P(\boldsymbol x|\boldsymbol G,\boldsymbol b) P(\boldsymbol G|\boldsymbol b),
where :math:`P(\boldsymbol G|\boldsymbol b)` is the likelihood of the
unweighted SBM described previously, and :math:`P(\boldsymbol
x|\boldsymbol G,\boldsymbol b)` is the integrated likelihood of the edge
.. math::
P(\boldsymbol x|\boldsymbol G,\boldsymbol b) =
\prod_{r\le s}\int P({\boldsymbol x}_{rs}|\gamma)P(\gamma)\,\mathrm{d}\gamma,
where :math:`P({\boldsymbol x}_{rs}|\gamma)` is some model for the weights
:math:`{\boldsymbol x}_{rs}` between groups :math:`(r,s)`, conditioned on
some parameter :math:`\gamma`, sampled from its prior
:math:`P(\gamma)`. A hierarchical version of the model can also be
implemented by replacing this prior by a nested sequence of priors and
hyperpriors, as described in [peixoto-weighted-2017]_. The posterior
partition distribution is then simply
.. math::
P(\boldsymbol b | \boldsymbol G,\boldsymbol x) =
\frac{P(\boldsymbol x|\boldsymbol G,\boldsymbol b) P(\boldsymbol G|\boldsymbol b)
P(\boldsymbol b)}{P(\boldsymbol G,\boldsymbol x)},
which can be sampled from, or maximized, just like with the unweighted
case, but will use the information on the weights to guide the partitions.
A variety of weight models is supported, reflecting different kinds of
edge covariates:
.. csv-table::
:header: "Name", "Domain", "Bounds", "Shape"
:widths: 10, 5, 5, 5
:delim: |
:align: center
``"real-exponential"`` | Real :math:`(\mathbb{R})` | :math:`[0,\infty]` | `Exponential <>`_
``"real-normal"`` | Real :math:`(\mathbb{R})` | :math:`[-\infty,\infty]` | `Normal <>`_
``"discrete-geometric"`` | Natural :math:`(\mathbb{N})` | :math:`[0,\infty]` | `Geometric <>`_
``"discrete-binomial"`` | Natural :math:`(\mathbb{N})` | :math:`[0,M]` | `Binomial <>`_
``"discrete-poisson"`` | Natural :math:`(\mathbb{N})` | :math:`[0,\infty]` | `Poisson <>`_
In fact, the actual model implements `microcanonical
<>`_ versions of
these distributions that are asymptotically equivalent, as described in
[peixoto-weighted-2017]_. These can be combined with arbitrary weight
transformations to achieve a large family of associated
distributions. For example, to use a `log-normal
<>`_ weight model
for positive real weights :math:`\boldsymbol x`, we can use the
transformation :math:`y_{ij} = \ln x_{ij}` together with the
``"real-normal"`` model for :math:`\boldsymbol y`. To model weights that
are positive or negative integers in :math:`\mathbb{Z}`, we could either
subtract the minimum value, :math:`y_{ij} = x_{ij} - x^*`, with
:math:`x^*=\operatorname{min}_{ij}x_{ij}`, and use any of the above
models for non-negative integers in :math:`\mathbb{N}`, or
alternatively, consider the sign as an additional covariate,
i.e. :math:`s_{ij} = [\operatorname{sign}(x_{ij})+1]/2 \in \{0,1\}`,
using the Binomial distribution with :math:`M=1` (a.k.a. the `Bernoulli
distribution <>`_),
and any of the other discrete distributions for the magnitude,
:math:`y_{ij} = \operatorname{abs}(x_{ij})`.
The support for weighted networks is activated by passing the parameters
``recs`` and ``rec_types`` to
:class:`~graph_tool.inference.blockmodel.BlockState` (or
that specify the edge covariates (an edge
:class:`~graph_tool.PropertyMap`) and their types (a string from the
table above), respectively. Note that these parameters expect *lists*,
so that multiple edge weights can be used simultaneously.
For example, let us consider a network of suspected terrorists involved
in the train bombing of Madrid on March 11, 2004
[hayes-connecting-2006]_. An edge indicates that a connection between
the two persons have been identified, and the weight of the edge (an
integer in the range :math:`[0,3]`) indicates the "strength" of the
connection. We can apply the weighted SBM, using a Binomial model for
the weights, as follows:
.. testsetup:: weighted-model
import os
except FileNotFoundError:
.. testcode:: weighted-model
g = gt.collection.konect_data["moreno_train"]
# This network contains an internal edge property map with name
# "weight" that contains the strength of interactions. The values
# integers in the range [0, 3].
state = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[g.ep.weight],
state.draw(edge_color=g.ep.weight, ecmap=(, .6),
eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1),
edge_gradient=[], output="moreno-train-wsbm.svg")
.. figure:: moreno-train-wsbm.*
:align: center
:width: 350px
Best fit of the Binomial-weighted degree-corrected SBM for a network
of terror suspects, using the strength of connection as edge
covariates. The edge colors and widths correspond to the strengths.
Model selection
In order to select the best weighted model, we proceed in the same
manner as described in Sec. :ref:`model_selection`. However, when using
transformations on continuous weights, we must include the associated
scaling of the probability density, as described in
For example, consider a `food web
<>`_ between species in south
Florida [ulanowicz-network-2005]_. A directed link exists from species
:math:`i` to :math:`j` if a energy flow exists between them, and a
weight :math:`x_{ij}` on this edge indicates the magnitude of the energy
flow (a positive real value, i.e. :math:`x_{ij}\in [0,\infty]`). One
possibility, therefore, is to use the ``"real-exponential"`` model, as
.. testsetup:: food-web
import os
except FileNotFoundError:
.. testcode:: food-web
g = gt.collection.konect_data["foodweb-baywet"]
# This network contains an internal edge property map with name
# "weight" that contains the biomass flow between species. The values
# are continuous in the range [0, infinity].
state = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[g.ep.weight],
state.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(, .6),
eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
edge_gradient=[], output="foodweb-wsbm.svg")
.. figure:: foodweb-wsbm.*
:align: center
:width: 350px
Best fit of the exponential-weighted degree-corrected SBM for a food
web, using the biomass flow as edge covariates (indicated by the edge
colors and widths).
Alternatively, we may consider a transformation of the type
.. math::
:label: log_transform
y_{ij} = \ln x_{ij}
so that :math:`y_{ij} \in [-\infty,\infty]`. If we use a model
``"real-normal"`` for :math:`\boldsymbol y`, it amounts to a `log-normal
<>`_ model for
:math:`\boldsymbol x`. This can be a better choice if the weights are
distributed across many orders of magnitude, or show multi-modality. We
can fit this alternative model simply by using the transformed weights:
.. testcode:: food-web
# Apply the weight transformation
y = g.ep.weight.copy()
y.a = log(y.a)
state_ln = gt.minimize_nested_blockmodel_dl(g, state_args=dict(recs=[y],
state_ln.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(, .6),
eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
edge_gradient=[], output="foodweb-wsbm-lognormal.svg")
.. figure:: foodweb-wsbm-lognormal.*
:align: center
:width: 350px
Best fit of the log-normal-weighted degree-corrected SBM for a food
web, using the biomass flow as edge covariates (indicated by the edge
colors and widths).
At this point, we ask ourselves which of the above models yields the
best fit of the data. This is answered by performing model selection via
posterior odds ratios just like in Sec. :ref:`model_selection`. However,
here we need to take into account the scaling of the probability density
incurred by the variable transformation, i.e.
.. math::
P(\boldsymbol x | \boldsymbol G, \boldsymbol b) =
P(\boldsymbol y(\boldsymbol x) | \boldsymbol G, \boldsymbol b)
In the particular case of Eq. :eq:`log_transform`, we have
.. math::
= \prod_{ij}\frac{1}{x_{ij}^{A_{ij}}}.
Therefore, we can compute the posterior odds ratio between both models as:
.. testcode:: food-web
L1 = -state.entropy()
L2 = -state_ln.entropy() - log(g.ep.weight.a).sum()
print(u"ln \u039b: ", L2 - L1)
.. testoutput:: food-web
ln Λ: -70.145685...
A value of :math:`\Lambda \approx \mathrm{e}^{-70} \approx 10^{-30}` in
favor the exponential model indicates that the log-normal model does not
provide a better fit for this particular data. Based on this, we
conclude that the exponential model should be preferred in this case.
Posterior sampling
The procedure to sample from the posterior distribution is identical to
what is described in Sec. :ref:`sampling`, but with the appropriate
initialization, i.e.
.. testcode:: weighted-model
state = gt.BlockState(g, B=20, recs=[g.ep.weight], rec_types=["discrete-poisson"])
or for the nested model
.. testcode:: weighted-model
state = gt.NestedBlockState(g, bs=[np.random.randint(0, 20, g.num_vertices())] + [zeros(1)] * 10,
Layered networks
The edges of the network may be distributed in discrete "layers",
representing distinct types if interactions
[peixoto-inferring-2015]_. Extensions to the SBM may be defined for such
data, and they can be inferred using the exact same interface shown
above, except one should use the
class, instead of
:class:`~graph_tool.inference.blockmodel.BlockState`. This class takes
two additional parameters: the ``ec`` parameter, that must correspond to
an edge :class:`~graph_tool.PropertyMap` with the layer/covariate values
on the edges, and the Boolean ``layers`` parameter, which if ``True``
specifies a layered model, otherwise one with categorical edge
covariates (not to be confused with the weighted models in
Sec. :ref:`weights`).
If we use :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl`, this can
be achieved simply by passing the option ``layers=True`` as well as the
appropriate value of ``state_args``, which will be propagated to
:class:`~graph_tool.inference.layered_blockmodel.LayeredBlockState`'s constructor.
As an example, let us consider a social network of tribes, where two
types of interactions were recorded, amounting to either friendship or
enmity [read-cultures-1954]_. We may apply the layered model by
separating these two types of interactions in two layers:
.. testsetup:: layered-model
import os
except FileNotFoundError:
.. testcode:: layered-model
g = gt.collection.konect_data["ucidata-gama"]
# The edge types are stored in the edge property map "weights".
# Note the different meanings of the two 'layers' parameters below: The
# first enables the use of LayeredBlockState, and the second selects
# the 'edge layers' version (instead of 'edge covariates').
state = gt.minimize_nested_blockmodel_dl(g, layers=True,
state_args=dict(ec=g.ep.weight, layers=True))
state.draw(edge_color=g.ep.weight, edge_gradient=[],
ecmap=(, .6), edge_pen_width=5,
.. figure:: tribes-sbm-edge-layers.*
:align: center
:width: 350px
Best fit of the degree-corrected SBM with edge layers for a network
of tribes, with edge layers shown as colors. The groups show two
enemy tribes.
It is possible to perform model averaging of all layered variants
exactly like for the regular SBMs as was shown above.
Inferring the best partition
The simplest and most efficient approach is to find the best
partition of the network by maximizing Eq. :eq:`model-posterior`
according to some version of the model. This is obtained via the
functions :func:`~graph_tool.inference.minimize.minimize_blockmodel_dl` or
:func:`~graph_tool.inference.minimize.minimize_nested_blockmodel_dl`, which
employs an agglomerative multilevel `Markov chain Monte Carlo (MCMC)
<>`_ algorithm
We focus first on the non-nested model, and we illustrate its use with a
network of American football teams, which we load from the
:mod:`~graph_tool.collection` module:
.. testsetup:: football
import os
except FileNotFoundError:
.. testcode:: football
g =["football"]
which yields
.. testoutput:: football
<Graph object, undirected, with 115 vertices and 613 edges at 0x...>
we then fit the degree-corrected model by calling
.. testcode:: football
state = gt.minimize_blockmodel_dl(g)
This returns a :class:`~graph_tool.inference.blockmodel.BlockState` object that
includes the inference results.
.. note::
The inference algorithm used is stochastic by nature, and may return
a different answer each time it is run. This may be due to the fact
that there are alternative partitions with similar probabilities, or
that the optimum is difficult to find. Note that the inference
problem here is, in general, `NP-Hard
<>`_, hence there is no
efficient algorithm that is guaranteed to always find the best
Because of this, typically one would call the algorithm many times,
and select the partition with the largest posterior probability of