Repository navigation
Implement Leiden Community Detection Algorithm - #8509
Conversation
Co-authored-by: Dan Schult <[email protected]>
Co-authored-by: Dan Schult <[email protected]>
Co-authored-by: Dan Schult <[email protected]>
Co-authored-by: Dan Schult <[email protected]>
…some minor style changes
…ity_add_cost, rather than using quality_function directly. By default it still uses the underlying quality functions, but these can be easily swapped for optimised expressions for specific quality functions.
|
@dschult following the discussion around quality deltas in #8505, I have been thinking more about this and I have changed the approach here so that If we move a node The new functions compute these values and so we have:
The quantity These functions will be specific to the quality function used, and the new method sets this up at the beginning of
I think this method gives a good trade-off in terms of allowing leiden to accept any quality function, whilst also allowing for optimised delta functions. |
…algorithm when computing cpm deltas as nodes are moved between communities.
…es to tests to reflect this. Also removed the allow_partial parameter from cpm, as it will no longer be required for leiden
…nclude self-loops in tests to ensure cancellations of terms in partial evaluations are correct
This has brought the test run-time from ~35 seconds down to ~11 seconds. @jtorrents I think combined with your other optimisation you've managed to get about x10 speedup (so far!) |
Thanks for this, I've removed the expensive bipartite check and I've put in a placeholder function for the barber modularity quality function to be defined inline. |
|
@dschult thanks for the latest round of comments. I will work through refactoring the new tests to incorporate your suggestions e.g. using parameterisation. Two things I want to highlight that I think require some further discussion: First, how to handle the old tests -- in some cases there are simple tweaks to make these work (e.g. changing resolution value), but I haven't touched these at all as I don't know exactly what the knock-on effects will be for other backends. Second, regarding the tests for expected partitions -- these are not based on any "ground truth" as the probabilistic nature of the algorithm (node visit order, and theta in refine partition) means we cannot check on a known input/output. The test here is useful for checking that the algorithm doesn't change when the code is modified (i.e. introducing unexpected behaviour changes), except of course when a minor change does affect the randomness in some way that alters the output, in which case the I did some initial comparison with the leidenalg implementation, and it seems our nx version is far less stable and more varied in the partitions it output for different seeds. I can only think this is due to the fact we shuffle the nodes before visiting, rather than relying on theta alone to control the randomness, but I haven't looked into the implementation details of leidenalg on this. However, the outputs do seem to "look about right" in comparison i.e. similar community sizes and membership overlap. One way to make this precise would be to compare the probability distributions of results i.e. for two implementations |
For a general approach we should tweak the test to make it work. Then we will have to rely on the backends to verify that this works for their setup as well. I will try to get someone to help us with that. Can we come up with a good way to make this PR mergable while leaving the exploration of these tests for a follow-up PR? Adding the
It's too bad that we don't have ground truths. It seems like there should be publications with reported communities for e.g. karate_club_graph and e.g. resolution=1. I'm not looking for what the leiden algorithm should produce -- I'm looking for an answer we can compare our "approximate value" to -- since Leiden is only expecting to approximate the optimal solution. This is also probably best left for a follow-up PR. I think we want to stay away from analysis of probability distributions of produced solutions. That is well beyond the unit test approach. :} So let's just focus on getting the PR mergable -- in a good state for us... and easy to parse for the backend folks. Specifically, let's put off consideration of the following:
|
|
@dk-gh where do you stand on this now? Thanks! |
I think if we are happy the core algorithm is in a good place then I think it would be good to create separate issues for any other specific improvements/changes. Very much welcome your thoughts on what the concrete next steps should be i.e. what is still to do in this PR, and what are the followup PRs (e.g. backend compatibility, optimisation, support for additional quality functions, ground truth examples, improved tests, revisiting louvain) |
* ENH: Add Barber's bipartite modularity quality function
Add `bipartite.modularity` implementing Barber's Q_B (2007) as a
quality function for bipartite community partitions. The
implementation uses the community-sum form
Q_B = sum_c [ L_c/m - gamma * k_c * d_c / m^2 ]
where k_c and d_c are the degree sums of the red and blue nodes in
community c. This mirrors the per-community form used by
`nx.community.modularity` but with a bipartite null model: the
product of two distinct degree sums rather than the square of a
single one.
Suggested by @dk-gh in PR review.
* ENH: Add partial-evaluation delta helpers for bipartite modularity
Add _bipartite_modularity_delta_partial_eval_{remove,add}, the
bipartite modularity counterpart to the CPM delta helpers introduced
in #8507. They compute the change in Barber's Q_B for moving a single
node between communities without recomputing Q_B over the whole
partition. The invariant
q_rem + q_add == Q_B(P') - Q_B(P)
is validated against the full quality function over unweighted,
weighted, and random-graph moves. The composition property
q_rem == -add(u, A\{u}) is also tested, confirming compatibility
with the single quality_delta pattern used in #8509.
* ENH: Add bipartite modularity merge-delta helper
Add a private helper `_bipartite_modularity_merge_delta` that computes
Q_B(P') - Q_B(P) when two disjoint communities A and B are merged:
merge_delta(A, B) = E(A, B) / m
- gamma * (k_A d_B + k_B d_A) / m**2
where k_C and d_C are sums of per-node `red_degree` and `blue_degree`
attributes over the nodes of C, and E(A, B) is the cross-community
edge weight.
The helper reads red/blue degree contributions from node attributes
rather than inferring them from bipartite-set membership. On an
original bipartite graph each node carries its degree in one attribute
and zero in the other; on an aggregated super-node graph (as built by
multilevel optimizers such as Louvain/Leiden) both attributes can be
nonzero and represent the summed contributions of the super-node's
constituents.
Self-loops on aggregated super-nodes are possible: they encode
intra-community edges and are correctly excluded from E(A, B) by the
`v in community_b` filter. `m` is passed in as a graph-level invariant
preserved across aggregation.
* Speed up bipartite modularity merge-delta inner loop
Compute the red/blue degree sums for A and B by iterating over the
community members and looking up node attributes directly, rather than
scanning all of G.nodes and filtering with `v in community`. The
complexity of the degree-sum step drops from O(|V|) to O(|A| + |B|).
This matters because _bipartite_modularity_merge_delta is designed to
run in the inner loop of multilevel optimizers (Louvain/Leiden), where
candidate communities are typically much smaller than the graph and
the helper is invoked many times per node visit.
* DOC: Add new module/fn to ref guide.
---------
Co-authored-by: Ross Barnowski <[email protected]>
Co-authored-by: Dan Schult <[email protected]>
Co-authored-by: evk <[email protected]>
dschult
left a comment
There was a problem hiding this comment.
I approve this PR.
The basics are good and we should get this merged so others can work with it:
- nx-cugraph backend will need to adapt to it.
- bipartitie and overlapping community tools can use ideas and code from this.
- Other items that follow-ups can improve:
- optimization
- parametrizing tests and unifying approach so other versions/quality measures can reuse tests
- develop some "ground truth" results that community detection can use generally
- revisit Louvain with respect to the more general approach taken here.
Co-authored-by: Dan Schult <[email protected]>
|
For what it's worth, I'm also +1 on merging this. Very good work @dk-gh ! |
|
Thanks all, and particular thanks to @dschult for all the effort in review. |
|
I am going to go ahead and merge this. We can get feedback from the backend maintainers and adjust what is here if needed in further PRs. Thanks everyone! |
This PR is related to the larger PR #8505 which has been split up into (at least three) smaller PRs.
This PR follows from PR #8507 which implemented the Constant Potts Model, which is a measure of the quality of a partition of a graph. The leiden algorithm uses Constant Potts Model by default. In principle another measure of quality could be used, for example, modularity, however the existing implementation of modularity will not work in its current form (see PR #8505 for further details).
This implementation of leiden is an adaptation of the existing louvain implementation, and closely follows the pseudocode from the original leiden paper [1]. One difference from the paper is this implementation allows arbitrary weights on nodes, and the weight of a node in the aggregated graphs is the sum of the weights of the nodes it contains (rather than just being a count of the number of nodes).
Because the leiden algorithm is probabilistic (randomness both in the order that nodes are visited,in
_move_nodes_fastand also in how communities are chosen in the_refine_partitionstage), it is not possible to verify the correctness simply using known inputs and expected outputs (some further discussion of this in PR #8505).Therefore I think the main goal at this stage needs to be verifying the correctness of the algorithm. Once correctness is verified then further tests can be written for specific inputs and their expected outputs, and then improvements (e.g. performance) made without changing the behaviour.
I haven't done any serious profiling or benchmarking for performance -- this would be a subsequent step once the correctness of the algorithm has been verified.
Note on file changes
Changes to the following files have been merged in from PR #8507, which has already been reviewed:
quality.py
test_quality.py
This PR is specifically focused on the leiden algorithm and corresponding tests which are found it:
leiden.py
test_leiden.py
[1] "From Louvain to Leiden: guaranteeing well-connected communities" Vincent Traag, Ludo Waltman, Nees Jan van Eck https://arxiv.org/abs/1810.08473