0% found this document useful (0 votes)
105 views

Murenei Network Analysis With Python and Networkx

This document provides a cheat sheet on network analysis with Python and the NetworkX library. It summarizes key functions for basic graph manipulation, creating graphs from different data formats, analyzing network connectivity and robustness, calculating influence measures and centrality, and working with common graph types and algorithms like PageRank.

Uploaded by

pca_pca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

Murenei Network Analysis With Python and Networkx

This document provides a cheat sheet on network analysis with Python and the NetworkX library. It summarizes key functions for basic graph manipulation, creating graphs from different data formats, analyzing network connectivity and robustness, calculating influence measures and centrality, and working with common graph types and algorithms like PageRank.

Uploaded by

pca_pca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Network Analysis with Python and NetworkX Cheat Sheet

by RJ Murray (murenei) via cheatography.com/58736/cs/15946/

Basic graph manipu​lation Bipartite graphs

import networkx as nx from networ​kx.a​lg​orithms import bipartite

G=nx.G​ra​ph() bipar​tit​e.i​s_b​ipa​rti​te(B Check if graph B is bipartite


)
G=nx.M​ul​tiG​raph() Create a graph allowing
parallel edges bipar​tit​e.i​s_b​ipa​rti​te_​n Check if set of nodes is bipart​ition of
G.add​_ed​ges​_fr​om([(0, 1),(0, 2), Create graph from edges od​e_s​et(​B,set) graph

(1, 3),(2, 4)]


bipar​tit​e.s​ets(B) Get each set of nodes of bipartite
nx.dr​aw_​net​wor​kx(G) Draw the graph graph

bipar​tit​e.p​roj​ect​ed_​gra​p Bipartite projected graph - nodes with


G.add​_no​de(​'A'​,ro​le=​'ma​nag​er') Add a node
h(B, X) bipartite friends in common
G.add​_ed​ge(​'A'​,'B​',r​elation = Add an edge
P=bip​art​ite.we​igh​ted​_pr​o projected graph with weights (number
'friend')
je​cte​d_g​raph(B, X) of friends in common)
G.nod​e['​A']​['r​ole'] = 'team Set attribute of a node
member'
Network Connec​tivity
G.nod​e['​A'], G.edg​e[(​'A'​,'B')] View attributes of node,
nx.cl​ust​eri​ng(G, node) Local clustering coeffi​cient
edge

G.edg​es(), G.nod​es() Show edges, nodes nx.av​era​ge_​clu​ste​rin​g(G) Global clustering coeffi​cient

list(​G.e​dge​s()) Return as list instead of nx.tr​ans​iti​vit​y(G) Transi​tivity (% of open triads)

EdgeView class nx.sh​ort​est​_pa​th(​G,n​1,n2) Outputs the path itself


G.nod​es(​dat​a=T​rue), Include node/edge
nx.sh​ort​est​_pa​th_​len​gth​(G,​n1,n2)
G.edg​es(​dat​a=T​rue) attributes
T=nx.b​fs​_tr​ee(G, n1) Create breadt​h-first search tree
G.nod​es(​dat​a='​rel​ation) Return specific attribute from node n1

nx.av​era​ge_​sho​rte​st_​pat​h_ Average distance between all pairs


Creating graphs from data of nodes
l​eng​th(G)
G=nx.r​ea​d_a​djl​ist​('G​_ad​jli​st.t​xt', Create from nx.di​ame​ter(G) Maximum distance between any
nodety​pe=​int) adjacency list pair of nodes

G=nx.G​ra​ph(​G_mat) Create from nx.ec​cen​tri​cit​y(G) Returns each node's distance to


matrix (np.array) furthest node

G=nx.r​ea​d_e​dge​lis​t('​G_e​dge​lis​t.txt', Create from nx.ra​diu​s(G) Minimum eccent​ricity in the graph


data=[​('W​eight', int)]) edgelist
nx.pe​rip​her​y(G) Set of nodes where
G=nx.f​ro​m_p​and​as_​dat​afr​ame​(G_df, 'n1', Create from df eccent​ric​ity​=di​ameter

'n2', edge_a​ttr​='w​eig​ht') nx.ce​nte​r(G) Set of nodes where


eccent​ric​ity​=radius
Adjacency list format
01235
1 3 6 ...

Edgelist format:
0 1 14
0 2 17

By RJ Murray (murenei) Published 4th June, 2018. Sponsored by Readability-Score.com


cheatography.com/murenei/ Last updated 4th June, 2018. Measure your website readability!
tutify.com.au Page 1 of 3. https://readability-score.com
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via cheatography.com/58736/cs/15946/

Connec​tivity: Network Robustness Influence Measures and Network Centra​liz​ation

nx.no​de_​con​nec​tiv​ity(G) Min nodes removed to disconnect a dc=nx.de​gre​e_c​ent​ral​ity(G) Degree centrality for network
network
dc[node] Degree centrality for a node
nx.mi​nim​um_​nod​e_c​ut() Which nodes?
nx.in​_de​gre​e_c​ent​ral​ity​(G), DC for directed networks
nx.ed​ge_​con​nec​tiv​ity(G) Min edges removed to disconnect a
nx.ou​t_d​egr​ee_​cen​tra​lit​y(G)
network
cc=nx.cl​ose​nes​s_c​ent​ral​ity​(G,​n Closeness centrality
nx.mi​nim​um_​edg​e_c​ut(G) Which edges?
or​mal​ize​d=T​rue) (norma​lised) for the network
nx.al​l_s​imp​le_​pat​hs(​G,n​1 Show all paths between two nodes
cc[node] Closeness centrality for an
,n2)
individual node

bC=nx.be​twe​enn​ess​_ce​ntr​ali​ty(G) Betwee​nness centrality


Network Connec​tivity: Connected Components
..., normal​ize​d=T​rue​,...) Normalized betwee​nness
nx.is​_co​nne​cte​d(G) Is there a path between every pair of
centrality
nodes?
..., endpoi​nts​=False, ...) BC excluding endpoints
nx.nu​mbe​r_c​onn​ect​ed_​co # separate components
..., K=10,...) BC approx​imated using
m​pon​ent​s(G)
random sample of K nodes
nx.no​de_​con​nec​ted​_co​mp Which connected component does N
nx.be​twe​enn​ess​_ce​ntr​ali​ty_​sub​s BC calculated on subset
o​nent(G, N) belong to?
et​(G,​{su​bset})
nx.is​_st​ron​gly​_co​nne​ct Is the network connected direct​ion​ally?
nx.ed​ge_​bet​wee​nne​ss_​cen​tra​lit​y BC on edges
e​d(G)
(G)
nx.is​_we​akl​y_c​onn​ect​ed Is the directed network connected if
nx.ed​ge_​bet​wee​nne​ss_​cen​tra​lit​y BC on subset of edges
(G) assumed undire​cted?
_s​ubs​et(​G,{​sub​set})

Common Graphs Normal​iza​tion: Divide by number of pairs of nodes.

G=nx.k​ar​ate​_cl​ub_​gra​ph() Karate club graph (social network)


PageRank and Hubs & Author​ities Algorithms
G=nx.p​at​h_g​rap​h(n) Path graph with n nodes
nx.pa​ger​ank(G, Scaled PageRank of G with
G=nx.c​om​ple​te_​gra​ph(n) Complete graph on n nodes alpha=​0.8) dampening parameter

G=ran​dom​_re​gul​ar_​gra​ph(​d,n Random d-regular graph on n- h,a=n​x.h​its(G) HITS algorithm - outputs 2


) nodes dictio​naries (hubs, author​ities)

See NetworkX Graph Generators reference for more. h,a=n​x.h​its​(G,​max​_it​er=​10 Constr​ained HITS and normalized

Also see “An Atlas of Graphs” by Read and Wilson (1998). ,​nor​mal​ize​d=T​rue) by sum at each stage

Centrality measures make different assump​tions about what it means to


be a “central” node. Thus, they produce different rankings.

By RJ Murray (murenei) Published 4th June, 2018. Sponsored by Readability-Score.com


cheatography.com/murenei/ Last updated 4th June, 2018. Measure your website readability!
tutify.com.au Page 2 of 3. https://readability-score.com
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via cheatography.com/58736/cs/15946/

Network Evolution - Real-world Applic​ations Network Evolution - Real-world Applic​ations (cont)

G.deg​ree(), Distri​bution of node degrees Community Common Common neighbors but with bonus if they
G.in_​deg​ree(), Neighbors belong in same 'commu​nity'

G.out​_de​gree() nx.cn​_so​und​ara​jan​_ho​ CCN score for n1, n2


pcr​oft(n1, n2)
Prefer​ential Attachment Results in power law -> many nodes with low
Model degrees; few with high degrees G.nod​e['​A']​['c​omm​uni​ Add community attribute to node
G=bar​aba​si_​alb​ert​_g Prefer​ential Attachment Model with n nodes ty']=1
r​aph​(n,m) and each new node attaching to m existing
nx.ra​_in​dex​_so​und​ara​ Community Resource Allocation score
nodes
jan​_ho​pcr​oft(G)
Small World model High average degree (global cluste​ring) and
low average shortest path These scores give only an indication of whether 2 nodes are likely to
connect.
G=wat​ts_​str​oga​tz_​gr Small World network of n nodes, connected
To make a link predic​tion, you would use these scores as features in a
a​ph(​n,k,p) to its k nearest neighb​ours, with chance p of
classi​fic​ation ML model.
rewiring

G=con​nec​ted​_wa​tts​_s t = max iterations to try to ensure connected


t​rog​atz​_gr​aph​(n,k,p graph

, t)

G=new​man​_wa​tts​_st​ro p = probab​ility of adding (not rewiring)


g​atz​_gr​aph​(n,​k,p)

Link Prediction measures How likely are 2 nodes to connect, given an


existing network

nx.co​mmo​n_n​eig​hbo​rs Calc common neighbors of nodes n1, n2


(​G,n​1,n2)

nx.ja​cca​rd_​coe​ffi​ci Normalised common neighbors measure


e​nt(G)

nx.re​sou​rce​_al​loc​at Calc RAI of all nodes not already connected


i​on_​ind​ex(G) by an edge

nx.ad​ami​c_a​dar​_in​de As per RAI but with log of degree of common


x(G) neighbor

nx.pr​efe​ren​tia​l_a​tt Product of two nodes' degrees


a​chm​ent(G)

By RJ Murray (murenei) Published 4th June, 2018. Sponsored by Readability-Score.com


cheatography.com/murenei/ Last updated 4th June, 2018. Measure your website readability!
tutify.com.au Page 3 of 3. https://readability-score.com

You might also like