python - Networkx Python 边缘比较

标签 python graph networkx

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

例如下面你可以看到它的第一次和第二次迭代:

---------------------- 一般信息图 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 中的边数。所以它应该只有 3151,而不是 8094。8094 应该是 Not found。请注意,找到的边数 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 符号 unpacks the tuple .

最后,使用 list comprehension给出了获取edge_not_found的更好方法:

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

这将创建一个由组成的列表,这些边位于G但不在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)

关于python - Networkx Python 边缘比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29495405/

相关文章:

python - 两个节点之间的路径

python - 尝试从 pyevolve 导入时出现 "AttributeError: fileno"

python - 我的dicts of dicts是否适用于这个Dijkstra算法?

python - Python 中唯一的一组随机数字对

haskell - 修改Haskell包fgl中的边缘标签

python - 如何使用networkx nx.draw()使x轴和y轴出现?

python - 以优化方式使用 Pandas 在 DataFrame 中查找和替换

python - 使用 Python 变量更新 PostgreSql 表

python - 有没有办法堆叠两个 tensorflow 数据集?

Python networkx 图形标签