我不相信有一个 NetworkX 函数可以从邻接矩阵创建图形,因此您必须编写自己的函数。 (不过,他们确实有一个二分模块 https://networkx.github.io/documentation/latest/reference/algorithms.bipartite.html你应该检查一下。)
这是定义一个函数的一种方法,该函数采用稀疏邻接矩阵并将其转换为 NetworkX 图(请参阅注释以获取解释)。
# Input: M scipy.sparse.csc_matrix
# Output: NetworkX Graph
def nx_graph_from_biadjacency_matrix(M):
# Give names to the nodes in the two node sets
U = [ "u{}".format(i) for i in range(M.shape[0]) ]
V = [ "v{}".format(i) for i in range(M.shape[1]) ]
# Create the graph and add each set of nodes
G = nx.Graph()
G.add_nodes_from(U, bipartite=0)
G.add_nodes_from(V, bipartite=1)
# Find the non-zero indices in the biadjacency matrix to connect
# those nodes
G.add_edges_from([ (U[i], V[j]) for i, j in zip(*M.nonzero()) ])
return G
请参阅下面的示例用例,我在其中使用nx.complete_bipartite_graph http://networkx.lanl.gov/reference/generated/networkx.generators.classic.complete_bipartite_graph.html#networkx.generators.classic.complete_bipartite_graph生成完整的图:
import networkx as nx, numpy as np
from networkx.algorithms import bipartite
from scipy.sparse import csc_matrix
import matplotlib.pyplot as plt
RB = nx.complete_bipartite_graph(3, 2)
A = csc_matrix(bipartite.biadjacency_matrix(RB, row_order=bipartite.sets(RB)[0]))
G = nx_graph_from_biadjacency_matrix(A)
nx.draw_circular(G, node_color = "red", with_labels = True)
plt.show()
And here's the output graph: