Skip to content

Fix bc scale with k endpoints - #7908

Merged
rossbar merged 14 commits into
networkx:mainfrom
eriknw:fix_bc_scale_with_k_endpoints
Mar 26, 2025
Merged

rossbar merged 14 commits into
networkx:mainfrom
eriknw:fix_bc_scale_with_k_endpoints

Conversation

@eriknw

@eriknw eriknw commented Mar 14, 2025 •

Copy link
Copy Markdown
Contributor

Fix betweenness_centrality rescaling given k and endpoints=False.

Previously, normalizing could give values above 1:

>>> nx.betweenness_centrality(nx.star_graph(4), k=1, seed=1, endpoints=False)
{0: 1.25, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}

Odd behavior with rescaling was reported in cugraph by @zmahoor in rapidsai/cugraph#4941

Credit to @ChuckHastings for understanding the issue and identifying correct behavior. Are there any other tests you think should be added?

Note that betweenness_centrality_subset and bipartite.betweenness_centrality don't have k, so they don't have this issue. I haven't considered whether edge_betweenness_centrality could have a similar issue.

Edit:
Summary of fixes:

  • When k is not None and endpoints is False, scale by (n - 1) instead of n
  • When k is not None and normalized is False and directed graph
    • scale by n / k if endpoints is True
    • scale by (n - 1) / k if endpoints is False
  • Fix edge case when k=n and endpoints is False

eriknw added 2 commits March 14, 2025 13:43
Previously, normalizing could give values above 1:
```python
>>> nx.betweenness_centrality(nx.star_graph(4), k=1, seed=1, endpoints=False)
{0: 1.25, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
```
@eriknw

eriknw commented Mar 14, 2025

Copy link
Copy Markdown
Contributor Author

I'll look at how this changes existing tests.

Also, I suspect scaling may need modified for directed graphs when normalized=False.

In [1]: import networkx as nx

In [2]: G = nx.star_graph(4)

In [3]: D = G.to_directed()

In [4]: nx.betweenness_centrality(G, k=1, seed=1, endpoints=False, normalized=False)
Out[4]: {0: 6.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}

In [5]: nx.betweenness_centrality(D, k=1, seed=1, endpoints=False, normalized=False)  # Is this correct?
Out[5]: {0: 3.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}

In [6]: nx.betweenness_centrality(G, k=1, seed=1, endpoints=True, normalized=False)
Out[6]: {0: 10.0, 1: 10.0, 2: 2.5, 3: 2.5, 4: 2.5}

In [7]: nx.betweenness_centrality(D, k=1, seed=1, endpoints=True, normalized=False)  # Is this correct?
Out[7]: {0: 4.0, 1: 4.0, 2: 1.0, 3: 1.0, 4: 1.0}

@ChuckHastings

Copy link
Copy Markdown

Note that betweenness_centrality_subset and bipartite.betweenness_centrality don't have k, so they don't have this issue. I haven't considered whether edge_betweenness_centrality could have a similar issue.

edge_betweenness_centrality has no endpoints parameter, so the scaling logic is straightforward.

@eriknw

eriknw commented Mar 15, 2025

Copy link
Copy Markdown
Contributor Author

I found more worms in this can!

Question for everybody: is BC given k w/o normalization supposed to approximate the full BC or not?

Previously, when given k and normalized=False, the BC results would be rescaled using k only for undirected graphs (thereby giving an estimate of the full BC), but not for directed graphs (thereby computing BC for k samples), so one of these cases must be wrong.

So, assuming we want to compute or estimate the full BC, I expanded out to give the explicit scale factors for 12 of the 16 cases from the cartesian product of:

  • normalized : {True, False}
  • endpoints : {True, False}
  • k : {None, k}
  • directed : {True, False}

The missing 4 cases are b/c the scale factors are the same for normalized=True and directed={True|False}.

@ChuckHastings I know you are working on this as well in libcugraph. What do you think? Do our scale factors agree? What is generally desired when computing BC with k (full BC or BC for k samples; both seem reasonable to me)?

Comment on lines +292 to +310
("normalized", "endpoints", "is_directed", "k", "expected"),
[
(True, True, True, None, {0: 1.0, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}),
(True, True, True, 1, {0: 1.0, 1: 1.0, 2: 0.25, 3: 0.25, 4: 0.25}),
(True, True, False, None, {0: 1.0, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}),
(True, True, False, 1, {0: 1.0, 1: 1.0, 2: 0.25, 3: 0.25, 4: 0.25}),
(True, False, True, None, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, True, 1, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, False, None, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, False, 1, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, True, True, None, {0: 20.0, 1: 8.0, 2: 8.0, 3: 8.0, 4: 8.0}),
(False, True, True, 1, {0: 20.0, 1: 20.0, 2: 5.0, 3: 5.0, 4: 5.0}),
(False, True, False, None, {0: 10.0, 1: 4.0, 2: 4.0, 3: 4.0, 4: 4.0}),
(False, True, False, 1, {0: 10.0, 1: 10.0, 2: 2.5, 3: 2.5, 4: 2.5}),
(False, False, True, None, {0: 12.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, True, 1, {0: 12.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, False, None, {0: 6.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, False, 1, {0: 6.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
],

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DO NOT MERGE

The diff in this comment shows the results from the main branch. Results only change when integer k is used:

Suggested change
("normalized", "endpoints", "is_directed", "k", "expected"),
[
(True, True, True, None, {0: 1.0, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}),
(True, True, True, 1, {0: 1.0, 1: 1.0, 2: 0.25, 3: 0.25, 4: 0.25}),
(True, True, False, None, {0: 1.0, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}),
(True, True, False, 1, {0: 1.0, 1: 1.0, 2: 0.25, 3: 0.25, 4: 0.25}),
(True, False, True, None, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, True, 1, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, False, None, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, False, 1, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, True, True, None, {0: 20.0, 1: 8.0, 2: 8.0, 3: 8.0, 4: 8.0}),
(False, True, True, 1, {0: 20.0, 1: 20.0, 2: 5.0, 3: 5.0, 4: 5.0}),
(False, True, False, None, {0: 10.0, 1: 4.0, 2: 4.0, 3: 4.0, 4: 4.0}),
(False, True, False, 1, {0: 10.0, 1: 10.0, 2: 2.5, 3: 2.5, 4: 2.5}),
(False, False, True, None, {0: 12.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, True, 1, {0: 12.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, False, None, {0: 6.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, False, 1, {0: 6.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
],
("normalized", "endpoints", "is_directed", "k", "expected"),
[
(True, True, True, None, {0: 1.0, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}),
(True, True, True, 1, {0: 1.0, 1: 1.0, 2: 0.25, 3: 0.25, 4: 0.25}),
(True, True, False, None, {0: 1.0, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}),
(True, True, False, 1, {0: 1.0, 1: 1.0, 2: 0.25, 3: 0.25, 4: 0.25}),
(True, False, True, None, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, True, 1, {0: 1.25, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, False, None, {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(True, False, False, 1, {0: 1.25, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, True, True, None, {0: 20.0, 1: 8.0, 2: 8.0, 3: 8.0, 4: 8.0}),
(False, True, True, 1, {0: 4.0, 1: 4.0, 2: 1.0, 3: 1.0, 4: 1.0}),
(False, True, False, None, {0: 10.0, 1: 4.0, 2: 4.0, 3: 4.0, 4: 4.0}),
(False, True, False, 1, {0: 10.0, 1: 10.0, 2: 2.5, 3: 2.5, 4: 2.5}),
(False, False, True, None, {0: 12.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, True, 1, {0: 3.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, False, None, {0: 6.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
(False, False, False, 1, {0: 7.5, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}),
],

@ChuckHastings ChuckHastings left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we're on the same page now.

@dschult

dschult commented Mar 19, 2025

Copy link
Copy Markdown
Member

@eriknw can you summarize what this changes? The logic is rewritten but it seems like much remains the same.
IIUC for the old system, the scaling factor should be 1/(n*(n-1)) but when endpoints is True n should be shifted to n-1 in that formula. when directed is False it should be multiplied by 0.5 and when k != len(G) it should be multiplied by n/k. And the discussion makes me think that something was off in the n/k factor.
Is the difference that we now use (k-1)/n when endpoints is True?

@eriknw

eriknw commented Mar 19, 2025

Copy link
Copy Markdown
Contributor Author

@dschult here is the minimal diff from main that passes the tests in this PR:

diff --git a/networkx/algorithms/centrality/betweenness.py b/networkx/algorithms/centrality/betweenness.py
index 42e09771d..c90ccd910 100644
--- a/networkx/algorithms/centrality/betweenness.py
+++ b/networkx/algorithms/centrality/betweenness.py
@@ -127,6 +127,8 @@ def betweenness_centrality(
        https://doi.org/10.2307/3033543
     """
     betweenness = dict.fromkeys(G, 0.0)  # b[v]=0 for v in G
+    if k == len(G):
+        k = None
     if k is None:
         nodes = G
     else:
@@ -372,12 +374,16 @@ def _rescale(betweenness, n, normalized, directed=False, k=None, endpoints=False
         if not directed:
             scale = 0.5
         else:
-            scale = None
+            scale = 1
     if scale is not None:
         if k is not None:
-            scale = scale * n / k
-        for v in betweenness:
-            betweenness[v] *= scale
+            if endpoints:
+                scale *= n / k
+            else:
+                scale *= (n - 1) / k
+        if scale != 1:
+            for v in betweenness:
+                betweenness[v] *= scale
     return betweenness

I explicitly expanded out the different cases to make it easier to see and consider each case. This helped me and @ChuckHastings communicate and understand each case (@ChuckHastings is updating cugraph in rapidsai/cugraph#4974, and we're now in agreement--thanks @ChuckHastings!).

I just added some code comments to explain rescaling, because it's actually kind of nuanced, but straightforward if given careful thought of the definition of BC. If you prefer the minimal diff just above, I can update the PR. Computing scale in two passes with some state ("why do we set scale = 1?!") seems more difficult to understand, because a reader will need to unravel the procedural logic to understand what is happening for a particular case. Having a single pass if-else is a little longer, but clearer IMHO.

Summary of fixes:

  • When k is not None and endpoints is False, scale by (n - 1) instead of n
  • When k is not None and normalized is False and directed graph
    • scale by n / k if endpoints is True
    • scale by (n - 1) / k if endpoints is False
  • Fix edge case when k=n and endpoints is False

rapids-bot Bot pushed a commit to rapidsai/cugraph that referenced this pull request Mar 20, 2025
Betweenness Centrality normalization is not quite right if you specify not including endpoints and use approximate betweenness.

This PR temporarily disables some of the python tests that compare results with networkx, since the networkx to update the normalization scores is not yet merged.  Once networkx/networkx#7908 is merged we should be able to create another PR to enable those tests.  Each of the disabled tests is skipped with a link to that PR as the reason.

Closes #4941

Authors:
  - Chuck Hastings (https://github.com/ChuckHastings)

Approvers:
  - Erik Welch (https://github.com/eriknw)
  - Joseph Nke (https://github.com/jnke2016)
  - Seunghwa Kang (https://github.com/seunghwak)

URL: #4974
@eriknw eriknw added this to the 3.5 milestone Mar 21, 2025
@dschult

dschult commented Mar 23, 2025

Copy link
Copy Markdown
Member

In terms of simplifying the code: we could take advantage of the various places we replace n with n-1. That reduces the number of checks for endpoints. Something like:

def _rescale(betweenness, n, normalized, directed=False, k=None, endpoints=False):
    N = n if endpoints else n - 1  # could put this in the call arg 'n' to _rescale and remove endpoints kwarg 
    if N <= 1:
        return betweenness
    if normalized:
        scale = 1 / (N * (N - 1))
    else:
        scale = 1 if directed else 0.5

    if k is not None and k < N:
        scale *= N / k
    if scale != 1:
        for v in betweenness:
            betweenness[v] *= scale
    return betweenness

Also, we might consider k==n as a mistake and raise an exception indicating that this isn't a sample -- it is the whole population. Making the special case k==n raise an exception might(?) be better for reducing mistakes by users. But that can be a separate PR for sure.

I'm shooting for some code that describes the following ideas rather than going through every combination of vars. The ideas feel orthogonal -- but that may be just me:

  • endpoints reduces the effective size of scaling from using n to n-1.
  • normalized divides by n*(n-1) -- i.e. the number of possible pairs.
  • unnormalized undirected counts need to be divided by 2
  • scale up the sample to full BC using factor n/k

@eriknw

eriknw commented Mar 24, 2025

Copy link
Copy Markdown
Contributor Author

Certainly @dschult, and it's not just you. I find the expanded cases were useful for development and careful review, but I'm also inclined to simplify and condense the logic before merging. The previous two commits take steps to condense the logic similar to your suggestions; you may look at them both.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice -- thanks for breaking this out into comment-able chunks. And commenting them! :}

The case with k < n and endpoints is False still confuses me. It seems like the number of valid (s, t) node pairs that could have a path through v where s != t should depend on whether node v was in the sample or not in the sample. The largest possible count for nodes in the sample (when endpoints is False) is (k-1)*(n-2), but for nodes not in the sample the count can be k*(n-2). Why are we using k*(n-2) for all the nodes?

Also, I still don't like the final scale computation because it requires learning 4 new values no matter what your particular case is. What do you think of adjusting scale after each comment paragraph under the conditions stated in that paragraph. For example after the undirected correct is discussed we could end with:

    # should be counted only once. Dividing by 2 corrects for this.
    if not normalized and not directed:
        scale /= 2

Then to figure out scale for any given case we check the if-conditions to see the various impacts of different paragraphs. I'm hoping that is simpler than trying to hold and construct 4 values in my head. But that could just be me...

I also have one wording tweak: may -> must
Thanks!

# This is for performance and correctness. When `endpoints` is False
# and k is given, k == n is a special case that would violate the
# assumption that node `v` is not one of the (s, t) node pairs.
# Should this warn or raise instead?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked at this a bunch too. It turns out that the seed.sample call below raises when k > len(G). I didn't check the error message. But it feels better to me to raise an error when k > len(G). I also lean toward raising when sampling with k == len(G). But that is not backward compatible -- and we actually have tests that check that situation. I'm guessing that those tests were only designed to check that the k input didn't blow up. But that's hard to know for sure. One test goes so far as to check k=3 and k=2 for a graph with 3 nodes.

The math-y part of me says we should probably raise when a sample is requested that includes the entire population. The dev-y part of me says it's a corner case and we know what they probably meant to do so just do it. So I'm conflicted... :)

@eriknw

eriknw commented Mar 25, 2025

Copy link
Copy Markdown
Contributor Author

Thanks for the helpful review @dschult!

The case with k < n and endpoints is False still confuses me. It seems like the number of valid (s, t) node pairs that could have a path through v where s != t should depend on whether node v was in the sample or not in the sample. The largest possible count for nodes in the sample (when endpoints is False) is (k-1)(n-2), but for nodes not in the sample the count can be k(n-2). Why are we using k*(n-2) for all the nodes?

Yeah, this is a great question. I need to think on it more carefully. The original code didn't do this either, so I usually try to minimize the changes done in a PR.

Also, I still don't like the final scale computation because it requires learning 4 new values no matter what your particular case is. What do you think of adjusting scale after each comment paragraph under the conditions stated in that paragraph.

Alright, I rearranged things again. I think it's about as simple and straightforward as it can be now 🤞 (but suggestions are still welcome!). The computer scientist in me is loathe to compute a floating point number and then update the floating point number (as was originally done) when we can compute it in one go.

@dschult

dschult commented Mar 25, 2025

Copy link
Copy Markdown
Member

Yeah, this is a great question. I need to think on it more carefully. The original code didn't do this either, so I usually try to minimize the changes done in a PR.

Agreed! That's a bigger question and should be in another PR. I'll raise a separate issue.

The code looks quite readable now (at least to me)! Thank you!!

I believe the only question remaining is whether to allow k>n by setting k = None in that case, or to only set k = None for the k==n case and have sample raise for k>n case. The previous code raised for k > n. I have a slight preference for raising when the sample is larger than the population size. I'm fine going ahead and computing the population value when the k=n. That is what the previous code did.

Sorry for making this take so long -- I have learned a bunch, but slowed this down for sure...

@eriknw

eriknw commented Mar 25, 2025

Copy link
Copy Markdown
Contributor Author

Sorry for making this take so long -- I have learned a bunch, but slowed this down for sure...

Nonsense! The code was begging for a "simplicity shakedown", so thanks for being on the journey for me :D . And what better time to learn about these changes than when it's fresh in my mind? I've learned a lot too.

I believe the only question remaining is whether to allow k>n by setting k = None in that case, or to only set k = None for the k==n case and have sample raise for k>n case. The previous code raised for k > n. I have a slight preference for raising when the sample is larger than the population size. I'm fine going ahead and computing the population value when the k=n. That is what the previous code did.

Updated to raise for out of bounds. I don't recall why I changed that recently; it must have been late and I was thoughtless. I added tests to guard against such thoughtlessness in the future.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks great! Thanks @eriknw and @ChuckHastings!

I approve this PR

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks so much @eriknw @ChuckHastings and @dschult for the iterations and helpful discussion. This is indeed a nuanced issue! The updates LGTM and the computations were clearer than before, so let's get this in! As noted in the discussion, any additional followups (e.g. k==n corner cases etc.) can be handled in different PRs for a more focused discussion.

Thanks again!

Comment on lines +130 to +131
if k == len(G):
# This is for performance and correctness. When `endpoints` is False

@Schefflera-Arboricola Schefflera-Arboricola Mar 27, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, I'm chiming in a bit late.

Maybe we should have deprecated k's behaviour (i.e. k cannot be equal to n anymore) instead of silently adding this condition because we do (TODO: update the docs!) state in the documentation that k <= n and it doesn't make sense to allow k=n and then just set k to None. Isn't it better to just not allow it at all? I'm suggesting deprecation because betweenness_centrality is a widely used algorithm and this will break or give different results for the previously written code, and it doesn't seem right to me that we(networkx) don't even communicate to the users about it. Thoughts?

Thanks!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was one of the things earmarked for follow-up, so don't hesitate to open an issue/PR for it!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to close the loop on this comment/PR-discussion:

The previous behavior for k<=n and endpoints=False was incorrect. So we should not deprecate these changes. But we should add a paragraph to the release notes talking about it. The problem was our scaling up from a sample of k nodes to the full BC values. This PR almost corrects everything. The next PR #7949 fixes the adjustment for whether a node is in the sample or not. That fix makes k=n work fine -- it could create a sample tha includes every single node and the result would be the same as k=None. Even so, we still change k==n to k=None there because the resulting bc values are identical either way, and k=None is faster because we know we have to do all the nodes (so no setup of a sample or special scaling up to full results at the end).

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

5 participants