_reconstruction.rst 19.4 KB
Newer Older
1 2 3 4 5 6 7
Network reconstruction
----------------------

An important application of generative models is to be able to
generalize from observations and make predictions that go beyond what is
seen in the data. This is particularly useful when the network we
observe is incomplete, or contains errors, i.e. some of the edges are
8 9 10 11 12 13
either missing or are outcomes of mistakes in measurement, or is not
even observed at all. In this situation, we can use statistical
inference to reconstruct the original network. Following
[peixoto-reconstructing-2018]_, if :math:`\boldsymbol{\mathcal{D}}` is
the observed data, the network can be reconstructed according to the
posterior distribution,
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

.. math::

   P(\boldsymbol A, \boldsymbol b | \boldsymbol{\mathcal{D}}) =
   \frac{P(\boldsymbol{\mathcal{D}} | \boldsymbol A)P(\boldsymbol A, \boldsymbol b)}{P(\boldsymbol{\mathcal{D}})}

where the likelihood :math:`P(\boldsymbol{\mathcal{D}}|\boldsymbol A)`
models the measurement process, and for the prior :math:`P(\boldsymbol
A, \boldsymbol b)` we use the SBM as before. This means that when
performing reconstruction, we sample both the community structure
:math:`\boldsymbol b` and the network :math:`\boldsymbol A` itself from
the posterior distribution. From it, we can obtain the marginal probability
of each edge,

.. math::

   \pi_{ij} = \sum_{\boldsymbol A, \boldsymbol b}A_{ij}P(\boldsymbol A, \boldsymbol b | \boldsymbol{\mathcal{D}}).

Based on the marginal posterior probabilities, the best estimate for the
whole underlying network :math:`\boldsymbol{\hat{A}}` is given by the
maximum of this distribution,

.. math::

   \hat A_{ij} =
       \begin{cases}
           1 & \text{ if } \pi_{ij} > \frac{1}{2},\\
           0 & \text{ if } \pi_{ij} < \frac{1}{2}.\\
       \end{cases}

We can also make estimates :math:`\hat y` of arbitrary scalar network
properties :math:`y(\boldsymbol A)` via posterior averages,
      
.. math::
   \begin{align}
       \hat y &= \sum_{\boldsymbol A, \boldsymbol b}y(\boldsymbol A)P(\boldsymbol A, \boldsymbol b | \boldsymbol{\mathcal{D}}),\\
       \sigma^2_y &= \sum_{\boldsymbol A, \boldsymbol b}(y(\boldsymbol A)-\hat y)^2P(\boldsymbol A, \boldsymbol b | \boldsymbol{\mathcal{D}})
   \end{align}

with uncertainty given by :math:`\sigma_y`. This is gives us a complete
probabilistic reconstruction framework that fully reflects both the
information and the uncertainty in the measurement data. Furthermore,
the use of the SBM means that the reconstruction can take advantage of
the *correlations* observed in the data to further inform it, which
generally can lead to substantial improvements
59
[peixoto-reconstructing-2018]_ [peixoto-network-2019]_.
60 61 62 63 64 65 66 67 68 69 70
       
In graph-tool there is support for reconstruction with the above
framework for three measurement processes: 1. Repeated measurements with
uniform errors (via
:class:`~graph_tool.inference.uncertain_blockmodel.MeasuredBlockState`), 2. Repeated
measurements with heterogeneous errors (via
:class:`~graph_tool.inference.uncertain_blockmodel.MixedMeasuredBlockState`),
and 3. Extraneously obtained edge probabilities (via
:class:`~graph_tool.inference.uncertain_blockmodel.UncertainBlockState`),
which we describe in the following.

71 72 73
In addition, it is also possible to reconstruct networks from observed
dynamical, as described in :ref:`reconstruction_dynamics`.

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
Measured networks
+++++++++++++++++

This model assumes that the node pairs :math:`(i,j)` were measured
:math:`n_{ij}` times, and an edge has been recorded :math:`x_{ij}`
times, where a missing edge occurs with probability :math:`p` and a
spurious edge occurs with probability :math:`q`, uniformly for all node
pairs, yielding a likelihood

.. math::

   P(\boldsymbol x | \boldsymbol n, \boldsymbol A, p, q) =
   \prod_{i<j}{n_{ij}\choose x_{ij}}\left[(1-p)^{x_{ij}}p^{n_{ij}-x_{ij}}\right]^{A_{ij}}
   \left[q^{x_{ij}}(1-q)^{n_{ij}-x_{ij}}\right]^{1-A_{ij}}.

In general, :math:`p` and :math:`q` are not precisely known *a priori*,
so we consider the integrated likelihood

.. math::

   P(\boldsymbol x | \boldsymbol n, \boldsymbol A, \alpha,\beta,\mu,\nu) =
   \int P(\boldsymbol x | \boldsymbol n, \boldsymbol A, p, q) P(p|\alpha,\beta) P(q|\mu,\nu)\;\mathrm{d}p\,\mathrm{d}q

where :math:`P(p|\alpha,\beta)` and :math:`P(q|\mu,\nu)` are `Beta
distributions <https://en.wikipedia.org/wiki/Beta_distribution>`__, which
specify the amount of prior knowledge we have on the noise
parameters. An important special case, which is the default unless
otherwise specified, is when we are completely agnostic *a priori* about
the noise magnitudes, and all hyperparameters are unity,

.. math::

   P(\boldsymbol x | \boldsymbol n, \boldsymbol A) \equiv
   P(\boldsymbol x | \boldsymbol n, \boldsymbol A, \alpha=1,\beta=1,\mu=1,\nu=1).

In this situation the priors :math:`P(p|\alpha=1,\beta=1)` and
:math:`P(q|\mu=1,\nu=1)` are uniform distribution in the interval :math:`[0,1]`.

.. note::

   It is important to emphasize that since this approach makes use of
   the *correlations* between edges to inform the reconstruction, as
   described by the inferred SBM, this means it can also be used when
   only single measurements have been performed, :math:`n_{ij}=1`, and
   the error magnitudes :math:`p` and :math:`q` are unknown. Since every
   arbitrary adjacency matrix can be cast in this setting, this method
   can be used to reconstruct networks for which no error assessments of
   any kind have been provided.

Below, we illustrate how the reconstruction can be performed with a
simple example, using
:class:`~graph_tool.inference.uncertain_blockmodel.MeasuredBlockState`:
      
.. testsetup:: measured

   import os
   try:
      os.chdir("demos/inference")
   except FileNotFoundError:
       pass
   np.random.seed(42)
   gt.seed_rng(44)

.. testcode:: measured

   g = gt.collection.data["lesmis"].copy()

   # pretend we have measured and observed each edge twice

   n = g.new_ep("int", 2)   # number of measurements
   x = g.new_ep("int", 2)   # number of observations

   e = g.edge(11, 36)
   x[e] = 1                 # pretend we have observed edge (11, 36) only once

   e = g.add_edge(15, 73)
   n[e] = 2                 # pretend we have measured non-edge (15, 73) twice,
   x[e] = 1                 # but observed it as an edge once.

   bs = [g.get_vertices()] + [zeros(1)] * 5  # initial hierarchical partition

   # We inititialize MeasuredBlockState, assuming that each non-edge has
   # been measured only once (as opposed to twice for the observed
   # edges), as specified by the 'n_default' and 'x_default' parameters.

   state = gt.MeasuredBlockState(g, n=n, n_default=1, x=x, x_default=0,
                                 state_args=dict(bs=bs))

   # We will first equilibrate the Markov chain
   gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))

   # Now we collect the marginals for exactly 100,000 sweeps, at
   # intervals of 10 sweeps:

   u = None              # marginal posterior edge probabilities
   pv = None             # marginal posterior group membership probabilities
   cs = []               # average local clustering coefficient

   def collect_marginals(s):
      global pv, u, cs
      u = s.collect_marginal(u)
      bstate = s.get_block_state()
      pv = bstate.levels[0].collect_vertex_marginals(pv)
      cs.append(gt.local_clustering(s.get_graph()).fa.mean())

   gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
                       callback=collect_marginals)

   eprob = u.ep.eprob
   print("Posterior probability of edge (11, 36):", eprob[u.edge(11, 36)])
   print("Posterior probability of non-edge (15, 73):", eprob[u.edge(15, 73)])
   print("Estimated average local clustering: %g ± %g" % (np.mean(cs), np.std(cs)))


Which yields the following output:
   
.. testoutput:: measured

192 193 194
   Posterior probability of edge (11, 36): 0.890889...
   Posterior probability of non-edge (15, 73): 0.056005...
   Estimated average local clustering: 0.572758 ± 0.003998...
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

We have a successful reconstruction, where both ambiguous adjacency
matrix entries are correctly recovered. The value for the average
clustering coefficient is also correctly estimated, and is compatible
with the true value :math:`0.57313675`, within the estimated error.

Below we visualize the maximum marginal posterior estimate of the
reconstructed network:

.. testcode:: measured

   # The maximum marginal posterior estimator can be obtained by
   # filtering the edges with probability larger than .5

   u = gt.GraphView(u, efilt=u.ep.eprob.fa > .5)

   # Mark the recovered true edges as red, and the removed spurious edges as green
   ecolor = u.new_ep("vector<double>", val=[0, 0, 0, .6])
   for e in u.edges():
       if g.edge(e.source(), e.target()) is None or (e.source(), e.target()) == (11, 36):
           ecolor[e] = [1, 0, 0, .6]
   for e in g.edges():
       if u.edge(e.source(), e.target()) is None:
           ne = u.add_edge(e.source(), e.target())
           ecolor[ne] = [0, 1, 0, .6]

   # Duplicate the internal block state with the reconstructed network
   # u, for visualization purposes.

   bstate = state.get_block_state()
   bstate = bstate.levels[0].copy(g=u)

   pv = u.own_property(pv)
   edash = u.new_ep("vector<double>")
   edash[u.edge(15, 73)] = [.1, .1, 0]
   bstate.draw(pos=u.own_property(g.vp.pos), vertex_shape="pie", vertex_pie_fractions=pv,
               edge_color=ecolor, edge_dash_style=edash, edge_gradient=None,
               output="lesmis-reconstruction-marginals.svg")

.. figure:: lesmis-reconstruction-marginals.*
   :align: center
   :width: 450px

   Reconstructed network of characters in the novel Les Misérables,
   assuming that each edge has been measured and recorded twice, and
   each non-edge has been measured only once, with the exception of edge
   (11, 36), shown in red, and non-edge (15, 73), shown in green, which
   have been measured twice and recorded as an edge once. Despite the
   ambiguity, both errors are successfully corrected by the
   reconstruction. The pie fractions on the nodes correspond to the
   probability of being in group associated with the respective color.

Heterogeneous errors
^^^^^^^^^^^^^^^^^^^^

In a more general scenario the measurement errors can be different for
each node pair, i.e. :math:`p_{ij}` and :math:`q_{ij}` are the missing
252
and spurious edge probabilities for node pair :math:`(i,j)`. The
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
measurement likelihood then becomes

.. math::

   P(\boldsymbol x | \boldsymbol n, \boldsymbol A, \boldsymbol p, \boldsymbol q) =
   \prod_{i<j}{n_{ij}\choose x_{ij}}\left[(1-p_{ij})^{x_{ij}}p_{ij}^{n_{ij}-x_{ij}}\right]^{A_{ij}}
   \left[q_{ij}^{x_{ij}}(1-q_{ij})^{n_{ij}-x_{ij}}\right]^{1-A_{ij}}.


Since the noise magnitudes are *a priori* unknown, we consider the
integrated likelihood

.. math::

   P(\boldsymbol x | \boldsymbol n, \boldsymbol A, \alpha,\beta,\mu,\nu) =
   \prod_{i<j}\int P(x_{ij} | n_{ij}, A_{ij}, p_{ij}, q_{ij}) P(p_{ij}|\alpha,\beta) P(q_{ij}|\mu,\nu)\;\mathrm{d}p_{ij}\,\mathrm{d}q_{ij}

where :math:`P(p_{ij}|\alpha,\beta)` and :math:`P(q_{ij}|\mu,\nu)` are
`Beta prior distributions
<https://en.wikipedia.org/wiki/Beta_distribution>`__, like
before. Instead of pre-specifying the hyperparameters, we include them
from the posterior distribution

.. math::

   P(\boldsymbol A, \boldsymbol b, \alpha,\beta,\mu,\nu | \boldsymbol x, \boldsymbol n) =
   \frac{P(\boldsymbol x | \boldsymbol n, \boldsymbol A, \alpha,\beta,\mu,\nu)P(\boldsymbol A, \boldsymbol b)P(\alpha,\beta,\mu,\nu)}{P(\boldsymbol x| \boldsymbol n)},

where :math:`P(\alpha,\beta,\mu,\nu)\propto 1` is a uniform hyperprior.

Operationally, the inference with this model works similarly to the one
with uniform error rates, as we see with the same example:

.. testcode:: measured

   state = gt.MixedMeasuredBlockState(g, n=n, n_default=1, x=x, x_default=0,
                                      state_args=dict(bs=bs))

   # We will first equilibrate the Markov chain
   gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))

   # Now we collect the marginals for exactly 100,000 sweeps, at
   # intervals of 10 sweeps:

   u = None              # marginal posterior edge probabilities
   pv = None             # marginal posterior group membership probabilities
   cs = []               # average local clustering coefficient

   gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
                       callback=collect_marginals)

   eprob = u.ep.eprob
   print("Posterior probability of edge (11, 36):", eprob[u.edge(11, 36)])
   print("Posterior probability of non-edge (15, 73):", eprob[u.edge(15, 73)])
   print("Estimated average local clustering: %g ± %g" % (np.mean(cs), np.std(cs)))

Which yields:
   
.. testoutput:: measured

313 314 315
   Posterior probability of edge (11, 36): 0.515651...
   Posterior probability of non-edge (15, 73): 0.009000...
   Estimated average local clustering: 0.571673 ± 0.003228...
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

The results are very similar to the ones obtained with the uniform model
in this case, but can be quite different in situations where a large
number of measurements has been performed (see
[peixoto-reconstructing-2018]_ for details).
    
Extraneous error estimates
++++++++++++++++++++++++++

In some situations the edge uncertainties are estimated by means other
than repeated measurements, using domain-specific models. Here we
consider the general case where the error estimates are extraneously
provided as independent edge probabilities :math:`\boldsymbol Q`,

.. math::

   P_Q(\boldsymbol A | \boldsymbol Q) = \prod_{i<j}Q_{ij}^{A_{ij}}(1-Q_{ij})^{1-A_{ij}},

where :math:`Q_{ij}` is the estimated probability of edge
:math:`(i,j)`. Although in principle we could reconstruct networks
directly from the above distribution, we can also incorporate it with
SBM inference to take advantage of large-scale structures present in the
data. We do so by employing Bayes' rule to extract the noise model from
the provided values [martin-structural-2015]_
[peixoto-reconstructing-2018]_,

.. math::

   \begin{align}
       P_Q(\boldsymbol Q | \boldsymbol A) &= \frac{P_Q(\boldsymbol A | \boldsymbol Q)P_Q(\boldsymbol Q)}{P_Q(\boldsymbol A)},\\
       & = P_Q(\boldsymbol Q) \prod_{i<j} \left(\frac{Q_{ij}}{\bar Q}\right)^{A_{ij}}\left(\frac{1-Q_{ij}}{1-\bar Q}\right)^{1-A_{ij}},
   \end{align}

where :math:`\bar Q = \sum_{i<j}Q_{ij}/{N\choose 2}` is the estimated
network density, and :math:`P_Q(\boldsymbol Q)` is an unknown prior for
:math:`\boldsymbol Q`, which can remain unspecified as it has no effect
on the posterior distribution. With the above, we can reconstruct the
network based on the posterior distribution,

.. math::

   P(\boldsymbol A, \boldsymbol b | \boldsymbol Q) = \frac{P_Q(\boldsymbol Q | \boldsymbol A)P(\boldsymbol A, \boldsymbol b)}{P(\boldsymbol Q)}

where :math:`P(\boldsymbol A, \boldsymbol b)` is the joint SBM
distribution used before. Note that this reconstruction will be
different from the one obtained directly from the original estimation, i.e.

.. math::

   P(\boldsymbol A | \boldsymbol Q) = \sum_{\boldsymbol b}P(\boldsymbol A, \boldsymbol b | \boldsymbol Q) \neq P_Q(\boldsymbol A | \boldsymbol Q).

This is because the posterior :math:`P(\boldsymbol A | \boldsymbol Q)`
will take into consideration the correlations found in the data, as
captured by the inferred SBM structure, as further evidence for the
existence and non-existence of edges. We illustrate this with an example
similar to the one considered previously, where two adjacency matrix
entries with the same ambiguous edge probability :math:`Q_{ij}=1/2` are
correctly reconstructed as edge and non-edge, due to the joint SBM
inference:
   
.. testsetup:: uncertain

   import os
   try:
      os.chdir("demos/inference")
   except FileNotFoundError:
       pass
   np.random.seed(48)
   gt.seed_rng(48)


.. testcode:: uncertain

   g = gt.collection.data["lesmis"].copy()

   N = g.num_vertices()
   E = g.num_edges()

   q = g.new_ep("double", .98)   # edge uncertainties

   e = g.edge(11, 36)
   q[e] = .5                     # ambiguous true edge

   e = g.add_edge(15, 73)
   q[e] = .5                     # ambiguous spurious edge
   
   bs = [g.get_vertices()] + [zeros(1)] * 5  # initial hierarchical partition

   # We inititialize UncertainBlockState, assuming that each non-edge
   # has an uncertainty of q_default, chosen to preserve the expected
   # density of the original network:

   q_default = (E - q.a.sum()) / ((N * (N - 1))/2 - E)
   
   state = gt.UncertainBlockState(g, q=q, q_default=q_default, state_args=dict(bs=bs))

   # We will first equilibrate the Markov chain
   gt.mcmc_equilibrate(state, wait=2000, mcmc_args=dict(niter=10))

   # Now we collect the marginals for exactly 100,000 sweeps, at
   # intervals of 10 sweeps:

   u = None              # marginal posterior edge probabilities
   pv = None             # marginal posterior group membership probabilities
   cs = []               # average local clustering coefficient
   
   def collect_marginals(s):
      global pv, u, cs
      u = s.collect_marginal(u)
      bstate = s.get_block_state()
      pv = bstate.levels[0].collect_vertex_marginals(pv)
      cs.append(gt.local_clustering(s.get_graph()).fa.mean())

   gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
                       callback=collect_marginals)

   eprob = u.ep.eprob
   print("Posterior probability of edge (11, 36):", eprob[u.edge(11, 36)])
   print("Posterior probability of non-edge (15, 73):", eprob[u.edge(15, 73)])
   print("Estimated average local clustering: %g ± %g" % (np.mean(cs), np.std(cs)))

The above yields the output:
   
.. testoutput:: uncertain

441 442 443
   Posterior probability of edge (11, 36): 0.951195...
   Posterior probability of non-edge (15, 73): 0.020702...
   Estimated average local clustering: 0.538731 ± 0.017645...
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

The reconstruction is accurate, despite the two ambiguous entries having
the same measurement probability. The reconstructed network is visualized below.
    
.. testcode:: uncertain

   # The maximum marginal posterior estimator can be obtained by
   # filtering the edges with probability larger than .5

   u = gt.GraphView(u, efilt=u.ep.eprob.fa > .5)
                       
   # Mark the recovered true edges as red, and the removed spurious edges as green
   ecolor = u.new_ep("vector<double>", val=[0, 0, 0, .6])
   edash = u.new_ep("vector<double>")
   for e in u.edges():
       if g.edge(e.source(), e.target()) is None or (e.source(), e.target()) == (11, 36):
           ecolor[e] = [1, 0, 0, .6]
       
   for e in g.edges():
       if u.edge(e.source(), e.target()) is None:
           ne = u.add_edge(e.source(), e.target())
           ecolor[ne] = [0, 1, 0, .6]
           if (e.source(), e.target()) == (15, 73):
               edash[ne] = [.1, .1, 0]

   bstate = state.get_block_state()
   bstate = bstate.levels[0].copy(g=u)
   pv = u.own_property(pv)
   bstate.draw(pos=u.own_property(g.vp.pos), vertex_shape="pie", vertex_pie_fractions=pv,
               edge_color=ecolor, edge_dash_style=edash, edge_gradient=None,
               output="lesmis-uncertain-reconstruction-marginals.svg")

.. figure:: lesmis-uncertain-reconstruction-marginals.*
   :align: center
   :width: 450px

   Reconstructed network of characters in the novel Les Misérables,
   assuming that each edge as a measurement probability of
   :math:`.98`. Edge (11, 36), shown in red, and non-edge (15, 73),
   shown in green, both have probability :math:`0.5`. Despite the
   ambiguity, both errors are successfully corrected by the
   reconstruction. The pie fractions on the nodes correspond to the
   probability of being in group associated with the respective color.
487 488

.. include:: _reconstruction_dynamics.rst