SciPy,从版本 1.4.0 开始,在scipy.sparse.csgraph.maximum_bipartite_matching 中包含一个 Hopcroft--Karp 的实现,在性能方面与 NetworkX 相媲美。该功能也存在于以前的版本中,但假设完美匹配;这个假设在 1.4.0 中被取消了。
它的性能究竟如何取决于二分图的结构,但仅通过随机图(并忽略 NetworkX 初始化底层数据结构所需的时间),我获得了大约 200 倍的性能提升:
import networkx as nx
from scipy.sparse import rand
from scipy.sparse.csgraph import maximum_bipartite_matching
n = 5000
graph = rand(n, n, density=.1, format='csr', random_state=42)
G = nx.algorithms.bipartite.from_biadjacency_matrix(graph)
>>> %timeit maximum_bipartite_matching(graph, perm_type='column')
8.95 ms ± 183 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit nx.algorithms.bipartite.maximum_matching(G, top_nodes=range(n))
2.01 s ± 118 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)