Repository navigation
perf: replace built-in sum() with np.sum() in pagerank and katz - #8561
Conversation
|
So... does this make an improvement in the performance of the code? |
Maybe. I added the following code (between ...
for _ in range(max_iter):
xlast = x
# begin
start = time.perf_counter()
sum1 = np.sum(x[is_dangling])
sum_time1 = time.perf_counter() - start
start = time.perf_counter()
sum2 = sum(x[is_dangling])
sum_time2 = time.perf_counter() - start
start = time.perf_counter()
sum3 = sum(x[is_dangling])
sum_time3 = time.perf_counter() - start
start = time.perf_counter()
sum4 = np.sum(x[is_dangling])
sum_time4 = time.perf_counter() - start
# end
print(f"Sum Time: {sum_time1:.10f} seconds, {sum_time2:.10f} seconds, {sum_time3:.10f} seconds, {sum_time4:.10f} seconds")
x = alpha * (x @ A + x[is_dangling].sum() * dangling_weights) + (1 - alpha) * p
...I then ran the following code: pagerank = nx.pagerank(
G,
alpha=0.85,
personalization=None,
max_iter=100,
tol=1e-06,
nstart=None,
dangling=None,
)On this dataset: https://snap.stanford.edu/data/web-Google.html, I obtained: (the first and fourth numbers are So I also tested on this dataset: https://snap.stanford.edu/data/ego-Twitter.html, and got: Again, |
|
I mean... not which |
The To get a more visible comparison, I deliberately adjusted the parameters ( for _ in range(10):
start = time.perf_counter()
pagerank = nx.pagerank(
G,
alpha=0.99,
personalization=None,
max_iter=10000,
tol=1e-12,
nstart=None,
dangling=None,
)
elapsed = time.perf_counter() - start
print(f"Time: {elapsed:.10f} seconds")On the dataset at https://snap.stanford.edu/data/ego-Twitter.html, the algorithm runs for 1135 iterations. Here are the timings: There is indeed a measurable performance improvement, even though it is not very large. |
rossbar
left a comment
There was a problem hiding this comment.
Seems fine to me - AFAICT everything being summed here is already a numpy array so np.sum can be used without having to worry about asarray overheads or issues with generators.
This pull request makes minor improvements to two centrality algorithms in the NetworkX library by replacing the built-in
sumfunction with NumPy'snp.sumfor better performance and consistency with NumPy arrays.Algorithm consistency and performance improvements:
networkx/algorithms/centrality/katz.py: Updated the normalization step in thekatz_centrality_numpyfunction to usenp.suminstead ofsumwhen calculating the sign of the centrality vector.networkx/algorithms/link_analysis/pagerank_alg.py: Modified the power iteration step in the_pagerank_scipyfunction to usenp.suminstead ofsumfor aggregating dangling node values.