Skip to content
GitLab
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
Malte R
graphtool
Commits
d2cde4cb
Commit
d2cde4cb
authored
Jun 28, 2018
by
Tiago Peixoto
Browse files
Add network reconstruction to inference HOWTO
parent
57d7c7ec
Changes
12
Expand all
Hide whitespace changes
Inline
Sidebyside
doc/conf.py
View file @
d2cde4cb
...
...
@@ 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
...
...
doc/demos/inference/_background.rst
0 → 100644
View file @
d2cde4cb
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"
<
https
://
en
.
wikipedia
.
org
/
wiki
/
Community_structure
>`
__
.
A
principled
approach
to
perform
this
task
is
to
formulate
`
generative
models
<
https
://
en
.
wikipedia
.
org
/
wiki
/
Generative_model
>`
_
that
include
the
idea
of
"modules"
in
their
descriptions
,
which
then
can
be
detected
by
`
inferring
<
https
://
en
.
wikipedia
.
org
/
wiki
/
Statistical_inference
>`
_
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
probability
..
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
<
https
://
en
.
wikipedia
.
org
/
wiki
/
Bayesian_inference
>`
_
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
<
https
://
en
.
wikipedia
.
org
/
wiki
/
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
selection
`).
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
)}
where
..
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
<
https
://
en
.
wikipedia
.
org
/
wiki
/
Information_theory
>`
_
required
to
describe
the
data
,
if
we
`
encode
<
https
://
en
.
wikipedia
.
org
/
wiki
/
Entropy_encoding
>`
_
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
<
https
://
en
.
wikipedia
.
org
/
wiki
/
Minimum_description_length
>`
_
method
.
This
approach
corresponds
to
an
implementation
of
`
Occam
's razor
<https://en.wikipedia.org/wiki/Occam%27s_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
<https://en.wikipedia.org/wiki/Overfitting>`_, 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
[guimeramodularity2004]_.
The stochastic block model (SBM)

The `stochastic block model
<https://en.wikipedia.org/wiki/Stochastic_block_model>`_ is arguably
the simplest generative process based on the notion of groups of
nodes [hollandstochastic1983]_. The `microcanonical
<https://en.wikipedia.org/wiki/Microcanonical_ensemble>`_ formulation
[peixotononparametric2017]_ 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
figure.
.. testcode:: sbmexample
:hide:
import os
try:
os.chdir("demos/inference")
except FileNotFoundError:
pass
g = gt.load_graph("blockmodelexample.gt.gz")
gt.graph_draw(g, pos=g.vp.pos, vertex_size=10, vertex_fill_color=g.vp.bo,
vertex_color="#333333",
edge_gradient=g.new_ep("vector<double>", val=[0]),
output="sbmexample.svg")
ers = g.gp.w
from pylab import *
figure()
matshow(log(ers))
xlabel("Group $r$")
ylabel("Group $s$")
gca().xaxis.set_label_position("top")
savefig("sbmexampleers.svg")
.. table::
:class: figure
+++
.. figure:: sbmexampleers.svg .. figure:: sbmexample.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"
<https://en.wikipedia.org/wiki/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
<https://en.wikipedia.org/wiki/Bipartite_graph>`_, coreperiphery,
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 `degreecorrected` stochastic block model
[karrerstochastic2011]_, 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 [peixotononparametric2017]_).
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
[peixotoparsimonious2013]_. 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
[peixotohierarchical2014]_, as illustrated below.
.. figure:: nesteddiagram.*
: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 coarsegraining.
doc/demos/inference/_edge_weights.rst
0 → 100644
View file @
d2cde4cb
.. _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 [aicherlearning2015]_ [peixotoweighted2017]_, 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
weights
.. 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 [peixotoweighted2017]_. 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:
.. csvtable::
:header: "Name", "Domain", "Bounds", "Shape"
:widths: 10, 5, 5, 5
:delim: 
:align: center
``"realexponential"``  Real :math:`(\mathbb{R})`  :math:`[0,\infty]`  `Exponential <https://en.wikipedia.org/wiki/Exponential_distribution>`_
``"realnormal"``  Real :math:`(\mathbb{R})`  :math:`[\infty,\infty]`  `Normal <https://en.wikipedia.org/wiki/Normal_distribution>`_
``"discretegeometric"``  Natural :math:`(\mathbb{N})`  :math:`[0,\infty]`  `Geometric <https://en.wikipedia.org/wiki/Geometric_distribution>`_
``"discretebinomial"``  Natural :math:`(\mathbb{N})`  :math:`[0,M]`  `Binomial <https://en.wikipedia.org/wiki/Binomial_distribution>`_
``"discretepoisson"``  Natural :math:`(\mathbb{N})`  :math:`[0,\infty]`  `Poisson <https://en.wikipedia.org/wiki/Poisson_distribution>`_
In fact, the actual model implements `microcanonical
<https://en.wikipedia.org/wiki/Microcanonical_ensemble>`_ versions of
these distributions that are asymptotically equivalent, as described in
[peixotoweighted2017]_. These can be combined with arbitrary weight
transformations to achieve a large family of associated
distributions. For example, to use a `lognormal
<https://en.wikipedia.org/wiki/Lognormal_distribution>`_ weight model
for positive real weights :math:`\boldsymbol x`, we can use the
transformation :math:`y_{ij} = \ln x_{ij}` together with the
``"realnormal"`` 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 nonnegative 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 <https://en.wikipedia.org/wiki/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
:class:`~graph_tool.inference.overlap_blockmodel.OverlapBlockState`),
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
[hayesconnecting2006]_. 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:: weightedmodel
import os
try:
os.chdir("demos/inference")
except FileNotFoundError:
pass
gt.seed_rng(42)
.. testcode:: weightedmodel
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],
rec_types=["discretebinomial"]))
state.draw(edge_color=g.ep.weight, ecmap=(matplotlib.cm.inferno, .6),
eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1),
edge_gradient=[], output="morenotrainwsbm.svg")
.. figure:: morenotrainwsbm.*
:align: center
:width: 350px
Best fit of the Binomialweighted degreecorrected 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
[peixotoweighted2017]_.
For example, consider a `food web
<https://en.wikipedia.org/wiki/Food_web>`_ between species in south
Florida [ulanowicznetwork2005]_. 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 ``"realexponential"`` model, as
follows:
.. testsetup:: foodweb
import os
try:
os.chdir("demos/inference")
except FileNotFoundError:
pass
gt.seed_rng(44)
.. testcode:: foodweb
g = gt.collection.konect_data["foodwebbaywet"]
# 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],
rec_types=["realexponential"]))
state.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(matplotlib.cm.inferno, .6),
eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
edge_gradient=[], output="foodwebwsbm.svg")
.. figure:: foodwebwsbm.*
:align: center
:width: 350px
Best fit of the exponentialweighted degreecorrected 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
``"realnormal"`` for :math:`\boldsymbol y`, it amounts to a `lognormal
<https://en.wikipedia.org/wiki/Lognormal_distribution>`_ model for
:math:`\boldsymbol x`. This can be a better choice if the weights are
distributed across many orders of magnitude, or show multimodality. We
can fit this alternative model simply by using the transformed weights:
.. testcode:: foodweb
# 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],
rec_types=["realnormal"]))
state_ln.draw(edge_color=gt.prop_to_size(g.ep.weight, power=1, log=True), ecmap=(matplotlib.cm.inferno, .6),
eorder=g.ep.weight, edge_pen_width=gt.prop_to_size(g.ep.weight, 1, 4, power=1, log=True),
edge_gradient=[], output="foodwebwsbmlognormal.svg")
.. figure:: foodwebwsbmlognormal.*
:align: center
:width: 350px
Best fit of the lognormalweighted degreecorrected 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)
\prod_{ij}\left[\frac{\mathrm{d}y_{ij}}{\mathrm{d}x_{ij}}(x_{ij})\right]^{A_{ij}}.
In the particular case of Eq. :eq:`log_transform`, we have
.. math::
\prod_{ij}\left[\frac{\mathrm{d}y_{ij}}{\mathrm{d}x_{ij}}(x_{ij})\right]^{A_{ij}}
= \prod_{ij}\frac{1}{x_{ij}^{A_{ij}}}.
Therefore, we can compute the posterior odds ratio between both models as:
.. testcode:: foodweb
L1 = state.entropy()
L2 = state_ln.entropy()  log(g.ep.weight.a).sum()
print(u"ln \u039b: ", L2  L1)
.. testoutput:: foodweb
:options: +NORMALIZE_WHITESPACE
ln Λ: 70.145685...
A value of :math:`\Lambda \approx \mathrm{e}^{70} \approx 10^{30}` in
favor the exponential model indicates that the lognormal 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:: weightedmodel
state = gt.BlockState(g, B=20, recs=[g.ep.weight], rec_types=["discretepoisson"])
or for the nested model
.. testcode:: weightedmodel
state = gt.NestedBlockState(g, bs=[np.random.randint(0, 20, g.num_vertices())] + [zeros(1)] * 10,
state_args=dict(recs=[g.ep.weight],
rec_types=["discretepoisson"]))
doc/demos/inference/_layers.rst
0 → 100644
View file @
d2cde4cb
Layered networks

The edges of the network may be distributed in discrete "layers",
representing distinct types if interactions
[peixotoinferring2015]_. 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:`~graph_tool.inference.layered_blockmodel.LayeredBlockState`
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 [readcultures1954]_. We may apply the layered model by
separating these two types of interactions in two layers:
.. testsetup:: layeredmodel
import os
try:
os.chdir("demos/inference")
except FileNotFoundError:
pass
gt.seed_rng(42)
.. testcode:: layeredmodel
g = gt.collection.konect_data["ucidatagama"]
# 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=(matplotlib.cm.coolwarm_r, .6), edge_pen_width=5,
output="tribessbmedgelayers.svg")
.. figure:: tribessbmedgelayers.*
:align: center
:width: 350px
Best fit of the degreecorrected 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.
doc/demos/inference/_minimization.rst
0 → 100644
View file @
d2cde4cb
Inferring the best partition

The simplest and most efficient approach is to find the best
partition of the network by maximizing Eq. :eq:`modelposterior`
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)
<https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo>`_ algorithm
[peixotoefficient2014]_.
We focus first on the nonnested 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
try:
os.chdir("demos/inference")
except FileNotFoundError:
pass
gt.seed_rng(7)
.. testcode:: football
g = gt.collection.data["football"]
print(g)
which yields
.. testoutput:: football
<Graph object, undirected, with 115 vertices and 613 edges at 0x...>
we then fit the degreecorrected 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, `NPHard
<https://en.wikipedia.org/wiki/NPhardness>`_, hence there is no
efficient algorithm that is guaranteed to always find the best
answer.
Because of this, typically one would call the algorithm many times,
and select the partition with the largest posterior probability of