繁体   English   中英

Networkx Python Edge比较

[英]Networkx Python Edges Comparison

我一直在尝试为项目构建图形,并且在尝试向其添加更多信息后识别新添加的边。

例如,在下面的示例中,您可以看到其第一次和第二次迭代:

----------------------一般信息图H ------------------------ -----

Total number of Nodes in Graph:  2364
Total number of Edges:  3151

----------------------常规信息图G ------------------------ -----

Total number of Nodes in Graph:  6035
Total number of Edges:  11245

我遇到的问题是当我尝试使用代码来识别新添加的边缘时:

counter = 0
edges_all = list(G.edges_iter(data=True)) 
edges_before = list(H.edges_iter(data=True)) 
print "How many edges in old graph: ", len(edges_before)
print "How many edges in new graph: ", len(edges_all)
edge_not_found = []
for edge in edges_all:
    if edge in edges_before:
        counter += 1
    else:
        edge_not_found.append(edge)
print "Edges found: ", counter
print "Not found: ", len(edge_not_found)

我一直得到这些结果:

How many edges in old graph:  3151
How many edges in new graph:  11245
Edges found:  1601
Not found:  9644

我不明白为什么找到1601而不是11245-3151 = 8094

有任何想法吗?

谢谢!

TL / DR:对于您所看到的内容,有一个简单的解释,如果您最终使用的话,则可以使用更短的方法来编写代码(此过程中有很多解释)。


首先要注意的是, Edges found似乎是HG Edges found数量。 因此,它应该只包含3151,而不是8094。应该Not found 8094。 请注意,找到的边数1601大约是您期望数的一半。 这是有道理的,因为:

我相信您遇到的问题是,当networkx列出边缘时,边缘可能在edges_before显示为(a,b) 但是,在edges_after ,它可能会在列表中显示为(b,a)

因此(b,a)不会在edges_before 它将使您的测试失败。 假设在为HG列出边缘顺序时它们之间不相关,那么您期望找到其中一半通过。 您可以进行其他测试以查看(b,a)是否为H的边。 这是H.has_edge(b,a)

一个直接的改进:

for edge in edges_all:
    if H.has_edge(edge[0],edge[1]):
        counter += 1
    else:
        edge_not_found.append(edge)

这样,您甚至可以避免定义edges_before

您还可以通过更好的改进来避免定义edges_all

for edge in G.edges_iter(data=True):
    if H.has_edge(edge[0],edge[1]):
        etc

注意:我已将其写为H.has_edge(edge[0],edge[1])来说明正在发生的事情。 编写它的更复杂的方法是H.has_edge(*edge) *edge表示法将元组解包

最后,使用列表推导提供了一种更好的获取edge_not_found的方法:

edge_not_found = [edge for edge in G.edges_iter(data=True) if not H.has_edge(*edge)]

这将创建一个由edge s组成的列表,这些edgeG但不在H

将所有这些放在一起(并使用.size()命令对网络中的边缘进行计数),我们得到了一个更干净的版本:

print "How many edges in old graph: ", H.size()
print "How many edges in new graph: ", G.size()
edge_not_found = [edge for edge in G.edges_iter(data=True) if not H.has_edge(*edge)]
print "Not found: ", len(edge_not_found)
print "Edges found: ", G.size()-len(edge_not_found)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM