Source code for graph_tool.inference.label_propagation

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2026 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from .. import _get_rng, _check_prop_scalar
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_inference as libinference")

__all__ = ["label_propagation", "harmonic_function",
           "local_and_global_consistency"]

[docs] def label_propagation(g, weight=None, b=None, fixed=None, mode="total", variant="dominance", max_niter=None): r"""Find communities with the label propagation heuristic. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be used. weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``) Edge weights. If not given, every edge has unit weight. b : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``) Initial labels. Negative values mean that the vertex is unlabeled. If not given, every vertex starts with a distinct label. fixed : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``) Boolean vertex property map marking the vertices whose labels do not change. Unlabeled vertices cannot be fixed. mode : ``str`` (optional, default: ``"total"``) For directed graphs, the neighbors whose labels are taken into account: ``"in"`` (labels propagate along the edges), ``"out"``, or ``"total"`` (both). variant : ``str`` (optional, default: ``"dominance"``) Variant of the algorithm: ``"dominance"``, ``"retention"``, or ``"fast"`` (see below). max_niter : ``int`` (optional, default: ``None``) If given, the maximum number of sweeps over the vertices. Returns ------- b : :class:`~graph_tool.VertexPropertyMap` The labels, numbered consecutively from zero in order of first appearance (or ``-1`` for the vertices that remain unlabeled). See Also -------- harmonic_function: Label prediction with the harmonic function local_and_global_consistency: Local and global consistency method ModularityState: Modularity maximization minimize_blockmodel_dl: Inference of the stochastic block model Notes ----- In the `label propagation algorithm <https://en.wikipedia.org/wiki/Label_propagation_algorithm>`_ of Raghavan, Albert, and Kumara [raghavan-near-2007]_, every vertex starts with its own label (or with the label given in ``b``) and repeatedly adopts a label with the largest total edge weight among its neighbors, i.e. one of the "dominant" labels .. math:: D_v = \underset{r}{\operatorname{arg\,max}}\sum_{u\in\partial v} w_{uv}\delta_{b_u,r}, where :math:`\partial v` are the neighbors of :math:`v` selected by ``mode`` and :math:`w_{uv}` the edge weights (summed over parallel edges), with ties broken uniformly at random, until every vertex has a dominant label, :math:`b_v\in D_v`. The labels then define the communities. Unlabeled vertices do not take part in the vote (and remain unlabeled if none of their neighbors is labeled), and the labels of the vertices marked in ``fixed`` never change, which allows semi-supervised classification. Self-loops are ignored. The variants differ in how the end is reached. With ``"dominance"``, sweeps that only check whether all labels are dominant, in which case the algorithm stops, alternate with update sweeps over the vertices in random order, in which every vertex takes a label from :math:`D_v` uniformly at random (even if its current one is dominant), as in the original algorithm. With ``"retention"``, the vertices are updated in sweeps in random order, a vertex keeps its label if it is in :math:`D_v`, and otherwise takes one from :math:`D_v` uniformly at random, and the algorithm stops after a sweep without changes. With ``"fast"`` [traag-large-2023]_, a queue of vertices, initially all vertices in random order, is processed instead of whole sweeps: every vertex taken from the queue gets a label from :math:`D_v` uniformly at random, and, when its label changes to :math:`r`, those of its neighbors that are influenced by it, not fixed, not already in the queue, and with a label other than :math:`r` are appended to the queue, which is several times faster. With ``max_niter``, the fast variant stops after ``max_niter`` times as many vertex updates as there are vertices that are not fixed. Every sweep takes time :math:`O(V + E)`, and the number of sweeps is typically small and grows slowly with the size of the network. The algorithm optimizes no objective function: different runs give different partitions, and it often finds a single community in networks without a strong structure, so that its results are mostly useful as a fast baseline. Principled alternatives, which also determine the number of groups, are given by :func:`~graph_tool.inference.minimize_blockmodel_dl` and the other inference methods in this module. Examples -------- .. testcode:: :hide: gt.seed_rng(42) >>> g = gt.collection.data["football"] >>> b = gt.label_propagation(g) >>> print(b.a.max() + 1, gt.modularity(g, b)) 9 0.5988373... For semi-supervised classification, we can fix the labels of two vertices of the karate club network and leave the others unlabeled, which gives the classes shown in the figure below: >>> g = gt.collection.data["karate"] >>> labels = g.new_vp("int", val=-1) >>> labels[0] = 0 >>> labels[33] = 1 >>> fixed = g.new_vp("bool", vals=labels.a >= 0) >>> b = gt.label_propagation(g, b=labels, fixed=fixed) >>> fill = g.new_vp("string", vals=np.array(["#9bbedc", "#f28c8e"])[b.a]) >>> shape = g.new_vp("string", vals=np.where(fixed.a, "square", "circle")) >>> gt.graph_draw(g, pos=g.vp.pos, vertex_fill_color=fill, ... vertex_shape=shape, vertex_halo=fixed, ... vertex_halo_color="#555555", vertex_halo_size=1.4, ... output="label-propagation-karate.pdf") <...> .. testcleanup:: conv_png("label-propagation-karate.pdf") .. figure:: label-propagation-karate.png :align: center :width: 60% Labels of the vertices of the karate club network found by label propagation from the fixed labels of vertices 0 and 33 (squares with a dark halo). The vertex colors indicate the labels. References ---------- .. [raghavan-near-2007] Usha Nandini Raghavan, Réka Albert and Soundar Kumara, "Near linear time algorithm to detect community structures in large-scale networks", Physical Review E 76, 036106 (2007), :DOI:`10.1103/PhysRevE.76.036106`, :arxiv:`0709.2938` .. [traag-large-2023] Vincent A. Traag and Lovro Šubelj, "Large network community detection by fast label propagation", Scientific Reports 13, 2701 (2023), :DOI:`10.1038/s41598-023-29610-z`, :arxiv:`2209.13338` """ modes = {"total": 0, "in": 1, "out": 2} variants = {"dominance": 0, "retention": 1, "fast": 2} if mode not in modes: raise ValueError(f"invalid mode: {mode}") if variant not in variants: raise ValueError(f"invalid variant: {variant}") if b is None: lb = g.new_vp("int64_t") else: _check_prop_scalar(b, name="b") lb = b.copy("int64_t") if fixed is None: fx = g.new_vp("bool") else: fx = fixed.copy("bool") if weight is None: w = g.new_ep("double", val=1) else: w = weight.copy("double") ret = g.new_vp("int32_t", val=-1) libinference.label_propagation(g, w, lb, b is not None, fx, ret, modes[mode], variants[variant], 0 if max_niter is None else max_niter, _get_rng()) return ret
def _propagate(g, labels, weight, harmonic, alpha, max_iter): if g.is_directed(): raise ValueError("The graph must be undirected.") _check_prop_scalar(labels, name="labels") lab = labels.copy("int64_t") if not (lab.fa >= 0).any(): raise ValueError("No vertex is labeled.") if weight is None: w = g.new_ep("double", val=1) else: _check_prop_scalar(weight, name="weight") w = weight.copy("double") pred = g.new_vp("int64_t", val=-1) libinference.propagate_labels(g, w, lab, harmonic, alpha, max_iter, pred) return pred
[docs] def harmonic_function(g, labels, weight=None, max_iter=30): r"""Predict the labels of the unlabeled vertices with the harmonic function. Parameters ---------- g : :class:`~graph_tool.Graph` Undirected graph. labels : :class:`~graph_tool.VertexPropertyMap` Integer labels of the vertices, with negative values for the unlabeled ones. weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``) Edge weights. max_iter : ``int`` (optional, default: ``30``) Number of iterations. Returns ------- pred : :class:`~graph_tool.VertexPropertyMap` The label of every vertex (the given ones for the labeled vertices). See Also -------- local_and_global_consistency: Local and global consistency method label_propagation: Label propagation heuristic Notes ----- The method of Zhu, Ghahramani, and Lafferty [zhu-semi-supervised-2003]_ finds, for every class, the harmonic function that is one at the vertices with this label, zero at the vertices with other labels, and equal to the weighted average of its neighbors at the unlabeled vertices (the absorption probability of a `random walk <https://en.wikipedia.org/wiki/Random_walk>`_); every unlabeled vertex gets the class with the largest value. It is approximated by ``max_iter`` iterations of :math:`F \leftarrow PF + B`, starting from :math:`F = 0`, where :math:`F_{vc}` is the score of class :math:`c` at vertex :math:`v`, :math:`P = D^{-1}A` is the transition matrix of the random walk, with the rows of the labeled vertices set to zero, :math:`A` the weighted adjacency matrix (with self-loops counted twice), :math:`D` the diagonal matrix of the weighted degrees (set to one for isolated vertices), and :math:`B_{vc} = 1` if vertex :math:`v` has the label :math:`c`, and zero otherwise. Every vertex is then given the class :math:`\operatorname{arg\,max}_c F_{vc}`, with ties broken in favor of the class that first appears among the vertices, in the order of their indices. This takes time :math:`O(E)` per iteration and class. Examples -------- >>> g = gt.collection.data["karate"] >>> labels = g.new_vp("int", val=-1) >>> labels[0] = 0 >>> labels[33] = 1 >>> pred = gt.harmonic_function(g, labels) >>> print(pred.a) [0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1] The predicted classes are shown in the figure below, which is obtained with >>> colors = np.array(["#9bbedc", "#f28c8e"]) >>> fill = g.new_vp("string", vals=colors[pred.a]) >>> seed = g.new_vp("bool", vals=labels.a >= 0) >>> shape = g.new_vp("string", vals=np.where(seed.a, "square", "circle")) >>> gt.graph_draw(g, pos=g.vp.pos, vertex_fill_color=fill, ... vertex_shape=shape, vertex_halo=seed, ... vertex_halo_color="#555555", vertex_halo_size=1.4, ... output="harmonic-function-karate.pdf") <...> .. testcleanup:: conv_png("harmonic-function-karate.pdf") .. figure:: harmonic-function-karate.png :align: center :width: 60% Classes of the vertices of the karate club network predicted with the harmonic function from the labels of vertices 0 and 33 (squares with a dark halo). The vertex colors indicate the classes. References ---------- .. [zhu-semi-supervised-2003] Xiaojin Zhu, Zoubin Ghahramani and John Lafferty, "Semi-supervised learning using Gaussian fields and harmonic functions", Proceedings of the 20th International Conference on Machine Learning, 912-919 (2003), https://aaai.org/papers/icml03-118-semi-supervised-learning-using-gaussian-fields-and-harmonic-functions/ """ return _propagate(g, labels, weight, True, 1., max_iter)
[docs] def local_and_global_consistency(g, labels, alpha=0.99, weight=None, max_iter=30): r"""Predict the labels of the unlabeled vertices with the local and global consistency method. Parameters ---------- g : :class:`~graph_tool.Graph` Undirected graph. labels : :class:`~graph_tool.VertexPropertyMap` Integer labels of the vertices, with negative values for the unlabeled ones. alpha : ``float`` (optional, default: ``0.99``) Fraction of the score that each vertex takes from its neighbors. weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``) Edge weights. max_iter : ``int`` (optional, default: ``30``) Number of iterations. Returns ------- pred : :class:`~graph_tool.VertexPropertyMap` The predicted label of every vertex (also for the labeled ones, which may change). See Also -------- harmonic_function: Label prediction with the harmonic function label_propagation: Label propagation heuristic Notes ----- The method of Zhou et al. [zhou-learning-2004]_ iterates :math:`F \leftarrow \alpha SF + (1 - \alpha)B` ``max_iter`` times, starting from :math:`F = 0`, where :math:`F_{vc}` is the score of class :math:`c` at vertex :math:`v`, :math:`\alpha` is ``alpha``, :math:`S = D^{-1/2} A D^{-1/2}` is the symmetrically normalized adjacency matrix, with :math:`A` the weighted adjacency matrix (with self-loops counted twice) and :math:`D` the diagonal matrix of the weighted degrees (set to one for isolated vertices), and :math:`B_{vc} = 1` if vertex :math:`v` has the label :math:`c`, and zero otherwise. Every vertex is then given the class :math:`\operatorname{arg\,max}_c F_{vc}`, with ties broken in favor of the class that first appears among the vertices, in the order of their indices. The time is :math:`O(E)` per iteration and class. Examples -------- >>> g = gt.collection.data["karate"] >>> labels = g.new_vp("int", val=-1) >>> labels[0] = 0 >>> labels[33] = 1 >>> pred = gt.local_and_global_consistency(g, labels) >>> print(pred.a) [0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1] The predicted classes are shown in the figure below, which is obtained with >>> colors = np.array(["#9bbedc", "#f28c8e"]) >>> fill = g.new_vp("string", vals=colors[pred.a]) >>> seed = g.new_vp("bool", vals=labels.a >= 0) >>> shape = g.new_vp("string", vals=np.where(seed.a, "square", "circle")) >>> gt.graph_draw(g, pos=g.vp.pos, vertex_fill_color=fill, ... vertex_shape=shape, vertex_halo=seed, ... vertex_halo_color="#555555", vertex_halo_size=1.4, ... output="local-and-global-consistency-karate.pdf") <...> .. testcleanup:: conv_png("local-and-global-consistency-karate.pdf") .. figure:: local-and-global-consistency-karate.png :align: center :width: 60% Classes of the vertices of the karate club network predicted with the local and global consistency method from the labels of vertices 0 and 33 (squares with a dark halo). The vertex colors indicate the classes. References ---------- .. [zhou-learning-2004] Dengyong Zhou, Olivier Bousquet, Thomas N. Lal, Jason Weston and Bernhard Schölkopf, "Learning with local and global consistency", Advances in Neural Information Processing Systems 16, 321-328 (2004) """ return _propagate(g, labels, weight, False, alpha, max_iter)