Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via [Link]/58736/cs/15946/
Basic graph manipulation Bipartite graphs
import networkx as nx from networkx.algorithms import bipartite
G=nx.Graph() bipartite.is_bipartite(B Check if graph B is bipartite
)
G=nx.MultiGraph() Create a graph allowing
parallel edges bipartite.is_bipartite_n Check if set of nodes is bipartition of
[Link]_edges_from([(0, 1),(0, 2), Create graph from edges ode_set(B,set) graph
(1, 3),(2, 4)]
bipartite.sets(B) Get each set of nodes of bipartite
[Link]aw_networkx(G) Draw the graph graph
bipartite.projected_grap Bipartite projected graph - nodes with
[Link]_node('A',role='manager') Add a node
h(B, X) bipartite friends in common
[Link]_edge('A','B',relation = Add an edge
P=bipart[Link]ighted_pro projected graph with weights (number
'friend')
jected_graph(B, X) of friends in common)
[Link]e['A']['role'] = 'team Set attribute of a node
member'
Network Connectivity
[Link]e['A'], [Link]e[('A','B')] View attributes of node,
[Link]ustering(G, node) Local clustering coefficient
edge
[Link]es(), [Link]es() Show edges, nodes [Link]erage_clustering(G) Global clustering coefficient
list(G.edges()) Return as list instead of [Link]ansitivity(G) Transitivity (% of open triads)
EdgeView class [Link]ortest_path(G,n1,n2) Outputs the path itself
[Link]es(data=True), Include node/edge
[Link]ortest_path_length(G,n1,n2)
[Link]es(data=True) attributes
T=nx.bfs_tree(G, n1) Create breadth-first search tree
[Link]es(data='relation) Return specific attribute from node n1
[Link]erage_shortest_path_ Average distance between all pairs
Creating graphs from data of nodes
length(G)
G=nx.read_adjlist('G_adjlist.txt', Create from [Link]ameter(G) Maximum distance between any
nodetype=int) adjacency list pair of nodes
G=nx.Graph(G_mat) Create from [Link]centricity(G) Returns each node's distance to
matrix ([Link]) furthest node
G=nx.read_edgelist('G_edgelis[Link]', Create from [Link]dius(G) Minimum eccentricity in the graph
data=[('Weight', int)]) edgelist
[Link]riphery(G) Set of nodes where
G=nx.from_pandas_dataframe(G_df, 'n1', Create from df eccentricity=diameter
'n2', edge_attr='weight') [Link]nter(G) Set of nodes where
eccentricity=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 [Link]
[Link]/murenei/ Last updated 4th June, 2018. Measure your website readability!
[Link] Page 1 of 3. [Link]
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via [Link]/58736/cs/15946/
Connectivity: Network Robustness Influence Measures and Network Centralization
[Link]de_connectivity(G) Min nodes removed to disconnect a dc=[Link]gree_centrality(G) Degree centrality for network
network
dc[node] Degree centrality for a node
[Link]nimum_node_cut() Which nodes?
[Link]_degree_centrality(G), DC for directed networks
[Link]ge_connectivity(G) Min edges removed to disconnect a
[Link]t_degree_centrality(G)
network
cc=[Link]oseness_centrality(G,n Closeness centrality
[Link]nimum_edge_cut(G) Which edges?
ormalized=True) (normalised) for the network
[Link]l_simple_paths(G,n1 Show all paths between two nodes
cc[node] Closeness centrality for an
,n2)
individual node
bC=[Link]tweenness_centrality(G) Betweenness centrality
Network Connectivity: Connected Components
..., normalized=True,...) Normalized betweenness
[Link]_connected(G) Is there a path between every pair of
centrality
nodes?
..., endpoints=False, ...) BC excluding endpoints
[Link]mber_connected_co # separate components
..., K=10,...) BC approximated using
mponents(G)
random sample of K nodes
[Link]de_connected_comp Which connected component does N
[Link]tweenness_centrality_subs BC calculated on subset
onent(G, N) belong to?
et(G,{subset})
[Link]_strongly_connect Is the network connected directionally?
[Link]ge_betweenness_centrality BC on edges
ed(G)
(G)
[Link]_weakly_connected Is the directed network connected if
[Link]ge_betweenness_centrality BC on subset of edges
(G) assumed undirected?
_subset(G,{subset})
Common Graphs Normalization: Divide by number of pairs of nodes.
G=nx.karate_club_graph() Karate club graph (social network)
PageRank and Hubs & Authorities Algorithms
G=nx.path_graph(n) Path graph with n nodes
[Link]gerank(G, Scaled PageRank of G with
G=nx.complete_graph(n) Complete graph on n nodes alpha=0.8) dampening parameter
G=random_regular_graph(d,n Random d-regular graph on n- h,a=nx.hits(G) HITS algorithm - outputs 2
) nodes dictionaries (hubs, authorities)
See NetworkX Graph Generators reference for more. h,a=nx.hits(G,max_iter=10 Constrained HITS and normalized
Also see “An Atlas of Graphs” by Read and Wilson (1998). ,normalized=True) by sum at each stage
Centrality measures make different assumptions about what it means to
be a “central” node. Thus, they produce different rankings.
By RJ Murray (murenei) Published 4th June, 2018. Sponsored by [Link]
[Link]/murenei/ Last updated 4th June, 2018. Measure your website readability!
[Link] Page 2 of 3. [Link]
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via [Link]/58736/cs/15946/
Network Evolution - Real-world Applications Network Evolution - Real-world Applications (cont)
[Link]ree(), Distribution of node degrees Community Common Common neighbors but with bonus if they
G.in_degree(), Neighbors belong in same 'community'
[Link]_degree() [Link]_soundarajan_ho CCN score for n1, n2
pcroft(n1, n2)
Preferential Attachment Results in power law -> many nodes with low
Model degrees; few with high degrees [Link]e['A']['communi Add community attribute to node
G=barabasi_albert_g Preferential Attachment Model with n nodes ty']=1
raph(n,m) and each new node attaching to m existing
[Link]_index_soundara Community Resource Allocation score
nodes
jan_hopcroft(G)
Small World model High average degree (global clustering) and
low average shortest path These scores give only an indication of whether 2 nodes are likely to
connect.
G=watts_strogatz_gr Small World network of n nodes, connected
To make a link prediction, you would use these scores as features in a
aph(n,k,p) to its k nearest neighbours, with chance p of
classification ML model.
rewiring
G=connected_watts_s t = max iterations to try to ensure connected
trogatz_graph(n,k,p graph
, t)
G=newman_watts_stro p = probability of adding (not rewiring)
gatz_graph(n,k,p)
Link Prediction measures How likely are 2 nodes to connect, given an
existing network
[Link]mmon_neighbors Calc common neighbors of nodes n1, n2
(G,n1,n2)
[Link]ccard_coeffici Normalised common neighbors measure
ent(G)
[Link]source_allocat Calc RAI of all nodes not already connected
ion_index(G) by an edge
[Link]amic_adar_inde As per RAI but with log of degree of common
x(G) neighbor
[Link]eferential_att Product of two nodes' degrees
achment(G)
By RJ Murray (murenei) Published 4th June, 2018. Sponsored by [Link]
[Link]/murenei/ Last updated 4th June, 2018. Measure your website readability!
[Link] Page 3 of 3. [Link]