我正在学习使用Python模块networkx来进行二分图匹配。该模块中有两个函数可用于计算图的最大基数匹配:
由于我的图是二分图,我假设这两个函数会给出相同的结果,至少具有相同数量的边缘。然而,我的代码似乎表明
以下是我的工作代码:
这里是生成的图表。如图所示,subplot-2有6个边缘,而subplot-3有7个。这是networkx实现中的一个错误还是我在这里做错了什么? PS:我的networkx版本是1.11。
nx.maximal_matching()
nx.bipartite.maxmum_matching()
maximal_matching
,但其文档确实说明它“在图中查找最大基数匹配”。由于我的图是二分图,我假设这两个函数会给出相同的结果,至少具有相同数量的边缘。然而,我的代码似乎表明
nx.maximal_matching()
给出了错误的答案:可以有一条额外的边缘,正如nx.bipartite.maxmum_matching()
所建议的那样。以下是我的工作代码:
import networkx as nx
from networkx import bipartite
def plotGraph(graph,ax,title):
pos=[(ii[1],ii[0]) for ii in graph.nodes()]
pos_dict=dict(zip(graph.nodes(),pos))
nx.draw(graph,pos=pos_dict,ax=ax,with_labels=True)
ax.set_title(title)
return
if __name__=='__main__':
#---------------Construct the graph---------------
g=nx.Graph()
edges=[
[(1,0), (0,0)],
[(1,0), (0,1)],
[(1,0), (0,2)],
[(1,1), (0,0)],
[(1,2), (0,2)],
[(1,2), (0,5)],
[(1,3), (0,2)],
[(1,3), (0,3)],
[(1,4), (0,3)],
[(1,5), (0,2)],
[(1,5), (0,4)],
[(1,5), (0,6)],
[(1,6), (0,1)],
[(1,6), (0,4)],
[(1,6), (0,6)]
]
for ii in edges:
g.add_node(ii[0],bipartite=0)
g.add_node(ii[1],bipartite=1)
g.add_edges_from(edges)
#---------------Use maximal_matching---------------
match=nx.maximal_matching(g)
g_match=nx.Graph()
for ii in match:
g_match.add_edge(ii[0],ii[1])
#----------Use bipartite.maximum_matching----------
match2=bipartite.maximum_matching(g)
g_match2=nx.Graph()
for kk,vv in match2.items():
g_match2.add_edge(kk,vv)
#-----------------------Plot-----------------------
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(10,8))
ax1=fig.add_subplot(2,2,1)
plotGraph(g,ax1,'Graph')
ax2=fig.add_subplot(2,2,2)
plotGraph(g_match,ax2,'nx.maximal_matching()')
ax3=fig.add_subplot(2,2,3)
plotGraph(g_match2,ax3,'bipartite.maximum_matching()')
plt.show()
这里是生成的图表。如图所示,subplot-2有6个边缘,而subplot-3有7个。这是networkx实现中的一个错误还是我在这里做错了什么? PS:我的networkx版本是1.11。
max_weight_matching
,因为我的图没有权重。谢谢你为我澄清这一点。 - Jason