Jas*_*son 5 python graph matching bipartite networkx
我正在学习使用networkx python模块对二分图进行一些匹配。模块中有两个函数可以提供图形的最大基数匹配:
nx.maximal_matching()nx.bipartite.maxmum_matching()请注意,尽管其名称为maximal_matching,但其文档确实声明“在图中找到最大基数匹配”。
由于我的图是二分图,因此我假设这2个图将给出相同的结果,至少两个都具有相同的边数。但是,我的代码似乎暗示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()
Run Code Online (Sandbox Code Playgroud)
这是生成的图。如图所示,子图2具有6条边,而3具有7条边。这是networkx实施中的错误,还是我在这里做错了什么?
PS:我的networkx是1.11版
该networkx.maximal_matching算法不会以您想要的方式给出最大基数匹配。它实现了一个简单的贪心算法,其结果是最大的,纯粹是因为不能向其添加额外的边。
对于您想要的全局最大基数匹配,它的对应物是 networkx.max_weight_matching
| 归档时间: |
|
| 查看次数: |
1108 次 |
| 最近记录: |