网络分析流程与 NetworkX 实践05 / 16
NetworkX 速查表
| 任务 | 函数 | 相关专题 / 说明 |
|---|---|---|
| 建图 | nx.Graph()、nx.DiGraph()、G.add_edge(u, v, weight=w) |
网络结构指标与随机图;有向图区分入度、出度 |
| 读入 | nx.read_edgelist()、nx.from_pandas_edgelist()、nx.read_gexf()、nx.read_graphml() |
GEXF/GraphML 可与 Gephi、Cytoscape 互通,见数据读写与格式转换 |
| 导出 | nx.write_gexf(G, "g.gexf")、nx.write_graphml()、nx.to_pandas_edgelist(G)、nx.node_link_data(G) |
导出到 Gephi/Cytoscape 作图,或导出 JSON 供网页使用 |
| 矩阵 | nx.to_numpy_array(G, nodelist=)、nx.from_numpy_array(A)、nx.to_scipy_sparse_array(G)、nx.laplacian_matrix(G) |
网络结构指标与随机图、同步与协同动力学;固定
nodelist |
| 基本信息 | G.number_of_nodes()、G.number_of_edges()、nx.density(G)、nx.number_of_selfloops(G)、list(nx.isolates(G)) |
先检查自环与孤立点 |
| 连通性 | nx.is_connected(G)、nx.connected_components(G)、nx.strongly_connected_components(D)、nx.weakly_connected_components(D) |
很多指标要求连通,先取最大连通分支 |
| 子图 | G.subgraph(nodes).copy()、nx.k_core(G, k)、nx.core_number(G) |
网络上的传播与免疫中的 k-壳 |
| 度 | G.degree()、D.in_degree()、D.out_degree()、nx.degree_histogram(G) |
网络结构指标与随机图;加权时
G.degree(weight="weight") 为强度 |
| 路径 | nx.shortest_path(G, s, t, weight=)、nx.average_shortest_path_length(G)、nx.diameter(G) |
网络结构指标与随机图;只对连通图有定义;weight
被当作距离 |
| 聚集 | nx.clustering(G)、nx.average_clustering(G)、nx.transitivity(G) |
网络结构指标与随机图;注意平均聚集系数与传递性的区别 |
| 同配性 | nx.degree_assortativity_coefficient(G) |
高度节点是否倾向于相连,见度相关性与网络结构的高阶统计 |
| 中心性 | nx.degree_centrality、nx.betweenness_centrality、nx.closeness_centrality、nx.eigenvector_centrality、nx.pagerank |
网络结构指标与随机图、网络上的传播与免疫;大网络的介数可用参数
k 抽样近似 |
| 社团 | nx.community.louvain_communities(G, seed=)、nx.community.greedy_modularity_communities(G)、nx.community.girvan_newman(G)、nx.community.label_propagation_communities(G) |
社团结构与社区发现;Louvain
有随机性,固定 seed 并多次运行 |
| 模块度 | nx.community.modularity(G, communities) |
社团结构与社区发现 |
| 模型网络 | nx.gnm_random_graph(n, m)、nx.watts_strogatz_graph(n, k, p)、nx.barabasi_albert_graph(n, m)、nx.random_partition_graph(sizes, p_in, p_out)、nx.stochastic_block_model(sizes, P) |
网络结构指标与随机图、小世界与无标度网络模型、社团结构与社区发现 |
| 零模型 | nx.double_edge_swap(G, nswap, max_tries)、nx.configuration_model(deg_seq) |
保度随机化;配置模型会产生重边和自环,需要清理 |
| 匹配 | nx.bipartite.hopcroft_karp_matching(B, top_nodes) |
网络可控性与稳定性中的驱动节点 |
| 布局 | nx.spring_layout(G, seed=)、nx.kamada_kawai_layout、nx.spectral_layout、nx.forceatlas2_layout、nx.multipartite_layout |
见布局算法;forceatlas2_layout
需 NetworkX 3.4 及以上 |
| 可视化 | nx.draw_networkx(G, pos, node_color=, node_size=) |
快速查看;论文图建议用 Gephi/Cytoscape |
| 后端 | nx.betweenness_centrality(G, backend="cugraph")、nx.config.backend_priority |
安装 nx-cugraph、nx-parallel 等后端后,同一函数可调用 GPU 或并行实现 |
| 自带数据 | nx.karate_club_graph()、nx.les_miserables_graph()、nx.florentine_families_graph() |
演示用的小网络 |
三个常见坑:(1)average_shortest_path_length
在非连通图上会报错,先取最大连通分支,并在报告中说明丢掉了多少节点;(2)louvain_communities
每次结果可能不同,要固定随机种子、多次运行并报告结果的稳定性;(3)NetworkX
是纯 Python 实现,对几十万节点以上的网络(如完整的 STRING
人类网络)计算介数会很慢,可以先按置信度过滤,或改用
igraph、graph-tool。更多陷阱见下一节。