如何解决如何使用networkxPython计算图表编辑距离?
我正在处理图形编辑距离;根据定义,将原始图G1转换为与G2同构的图是最小的成本总和;
图形编辑操作通常包括:
- 顶点插入可将单个新的标记顶点引入图形。
- 删除顶点以从图形中删除单个(通常是断开的)顶点。
- 顶点替换可更改给定顶点的标签(或颜色)。
- 边缘插入以在一对顶点之间引入新的彩色边缘。
- 删除边以删除一对顶点之间的单个边。
- 边缘替换以更改给定边缘的标签(或颜色)。
现在我要使用networkx的实现-我没有任何边缘标签,G1和G2的节点集相同,并且我不希望图形与G2同构,但是我想要G2本身;
这主要是因为G1:1-> 2-> 3和G2:3-> 2-> 1彼此同构,但是如果节点代表某些事件,则从因果关系的角度来看它们是非常不同的;
因此,在这种情况下,我一直在进行如下测试:
import networkx as nx
G=nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edges_from([(1,2),(2,3)])
G2=nx.DiGraph()
G2.add_node(1)
G2.add_node(2)
G2.add_node(3)
G2.add_edges_from([(3,1)])
nx.graph_edit_distance(G,G2)
但是它返回距离为零,这是有道理的,因为这些图是同构的;
所以我尝试设置node_match,但仍然没有运气
import networkx as nx
def nmatch(n1,n2):
return n1==n2
G=nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edges_from([(1,G2,node_match=nmatch)
如果我们假设删除或添加边/顶点的成本为1,则编辑距离应为4,因为我们可以:
- 删除G中的两条边,从G2中添加2条边
在不考虑同构但真正等效的情况下计算编辑距离如何合适?
解决方法
似乎您没有在比较自己想要的东西。 nmatch中的n1
和n2
始终为{}
。来自文档
(...)也就是说,该函数将接收n1和n2的节点属性字典作为输入。
您不是在比较节点对象,而是在与它们相关联的字典(您需要的任何数据)
您可以在添加节点时将自定义数据添加到该字典,例如:
import networkx as nx
def nmatch(n1,n2):
return n1==n2
G=nx.DiGraph()
G.add_node(1,id=1)
G.add_node(2,id=2)
G.add_node(3,id=3)
G.add_edges_from([(1,2),(2,3)])
G2=nx.DiGraph()
G2.add_node(1,id=1)
G2.add_node(2,id=2)
G2.add_node(3,id=3)
G2.add_edges_from([(3,1)])
nx.graph_edit_distance(G,G2,node_match=nmatch)
返回2,因为您可以进行2个边缘替换。如果您希望结果为4(2次插入,2次删除),则可能会增加替换成本
,这是另一个解决方案,产生2个
import networkx as nx
G=nx.DiGraph()
G.add_node(1,1)])
# arguments
# arguments for nodes
def node_subst_cost(node1,node2):
# check if the nodes are equal,if yes then apply no cost,else apply 1
if node1 == node2:
return 0
return 1
def node_del_cost(node):
return 1 # here you apply the cost for node deletion
def node_ins_cost(node):
return 1 # here you apply the cost for node insertion
# arguments for edges
def edge_subst_cost(edge1,edge2):
# check if the edges are equal,else apply 3
if edge1==edge2:
return 0
return 1
def edge_del_cost(node):
return 1 # here you apply the cost for edge deletion
def edge_ins_cost(node):
return 1 # here you apply the cost for edge insertion
paths,cost = nx.optimal_edit_paths(
G,node_subst_cost=node_subst_cost,node_del_cost=node_del_cost,node_ins_cost=node_ins_cost,edge_subst_cost=edge_subst_cost,edge_del_cost=edge_del_cost,edge_ins_cost=edge_ins_cost
)
print(cost)
如果在Python 2.7上运行它,请将以下行添加到标题中
# This Python file uses the following encoding: utf-8
from __future__ import print_function,unicode_literals
from __future__ import absolute_import,division
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。