【问题标题】:How to measure the graph edit distance by considering the node names如何通过考虑节点名称来测量图形编辑距离
【发布时间】:2019-04-04 14:51:17
【问题描述】:

我已经使用库 networkx 在 python 中定义了两个图,现在我想考虑节点的“名称”来测量这两个图之间的距离

我创建了两个图表,看起来完全一样(树形图)

G=nx.Graph()
G.add_edges_from([("A","B"),("A","C")])

H=nx.Graph()
H.add_edges_from([("X","Y"),("X","Z")])

res=nx.graph_edit_distance(G,H)
res2=nx.optimize_edit_paths(G,H)
res3=nx.optimal_edit_paths(G,H)

我希望替换所有节点,因为节点没有相同的名称,但我得到成本(更改/距离)0 的结果。这意味着该函数没有考虑节点的名称。

documentation 中建议使用函数“node_math”,但我不知道如何使用它。它似乎不是networkx功能。

【问题讨论】:

    标签: python-3.x networkx


    【解决方案1】:

    它给出答案为0 的原因是因为它认为节点是相等的。如果您看到文档,它会提到

    node_match (callable) – 如果 G1 中的节点 n1 则返回 True 的函数 和 G2 中的 n2 在匹配时应该被认为是相等的。

    函数会被调用

    node_match(G1.nodes[n1], G2.nodes[n2]).
    

    也就是说,该函数将接收节点属性字典 n1 和 n2 作为输入。

    现在,既然你还没有声明任何属性,那么在这种情况下

    G.nodes['A'] will return {}
    

    H.nodes['Z'] will return {}
    

    现在,由于两者都是空字典,因此它们将被视为相等。

    这是您的代码的修改版本,我在其中为您的节点添加了标签属性。

    import networkx as nx
    
    G=nx.Graph()
    G.add_nodes_from([("A", {'label':'a'}), ("B", {'label':'b'}),
                      ("C", {'label':'c'})])
    
    G.add_edges_from([("A","B"),("A","C")])
    
    H=nx.Graph()
    H.add_nodes_from([("X", {'label':'x'}), ("Y", {'label':'y'}),
                      ("Z", {'label':'z'})])
    H.add_edges_from([("X","Y"),("X","Z")])
    
    # This is the function which checks for equality of labels
    def return_eq(node1, node2):
        return node1['label']==node2['label']
    
    print(nx.graph_edit_distance(G, H, node_match=return_eq))
    # Output: 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 2011-12-16
      • 1970-01-01
      相关资源
      最近更新 更多