带有networkx的图形的python计算错误

标签 python networkx

我根据数据挖掘收集的数据制作了一个巨大的图表。

我使用“networkx”制作图表,我想将巨大的图表更改为另一个图表。

对于每个节点,加权边的总和为1。

所以我的代码如下:

ng=nx.Graph()  
for n in g.nodes():  
    s=0.0  
    for nb in g.neighbors(n):  
         s=s+1.0/g[n][nb]['weight']  
    for nb in g.neighbors(n):  
        ng.add_edge(n,nb,weight=1.0/s/g[n][nb]['weight'])

在我通过如下代码检查结果后

for n in ng.neighbors('100002950636410'):
    print str(n) + ' : ' + str(ng[n]['100002950636410']['weight'])

邻居的总和不为 1,并且还有很多“权重”为 1 的边。

我是不是做错了什么?我认为我的计算和代码是正确的,但如果问题是图形的大小,那我该怎么办?

最佳答案

你的问题的问题

我认为您的解决方案无法按照您尝试的方式工作。我首先说明原因,然后在下面提出替代解决方案。

考虑这段代码:

import networkx as nx
import matplotlib.pyplot as plt
import random

# Set up a graph with random edges and weights

G = nx.barabasi_albert_graph(6, 2, seed= 3214562)
for u,v in G.edges_iter():
    G[u][v]['weight'] = int(random.random() * 10)

pos = nx.spring_layout(G)

nx.draw(G, pos)
nx.draw_networkx_edge_labels(G,pos)
plt.show()

它产生这个数字:

enter image description here

考虑节点 1。它有两条边,其权重分别为 2 和 9。我们应该将权重分别调整为 2/11 和 9/11。

接下来考虑节点 4。它现在有两条边,权重分别为 2/11 和 8。第一个权重在之前的计算中是固定的,所以我们基本上将第二个权重调整为 8/(8+2/11)。

我们现在有三个边,其权重已调整和固定。我们现在对节点 0、3 和 5 重复此操作。到该过​​程结束时,节点 2 周围的所有边都已重新调整和固定,但它们不会加起来为 1,除非是非常巧合。当然,在更大的图中,这个问题会出现得更快。

解决方案

我建议您为每个节点附加一个包含重新加权边字典的新数据属性,而不是重新加权边本身。这是演示的相关代码:

for n in G.nodes_iter():
    total = sum([ attr['weight']
                  for u,v,attr in G.edges(n, data=True) ])
    total = float(total)
    weights = dict([(nb, G[n][nb]['weight']/total)
                    for nb in G.neighbors(n)])
    G[n]['adj_weights'] = weights

# Print out the adjusted weights

for n in G.nodes_iter():
    for nb,w in G[n]['adj_weights'].iteritems():
        w = int(w*1000)/1000.
        print '{} to {}: {}'.format(n, nb, w)

这会产生:

0 to 2: 0.272
0 to 3: 0.727
1 to 2: 0.818
1 to 4: 0.181
2 to 0: 0.081
2 to 1: 0.243
2 to 3: 0.243
2 to 4: 0.216
2 to 5: 0.216
3 to 0: 0.363
3 to 2: 0.409
3 to 5: 0.227
4 to 1: 0.2
4 to 2: 0.8
5 to 2: 0.615
5 to 3: 0.384

因此,节点 0 的边总和为 1,例如,连接到节点 3 的边也是如此。但是从节点 0 看边 (0,3) 的权重是 0.727,从节点 3 看边是 0.363。

我希望这能让你继续下去。

关于带有networkx的图形的python计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884223/

相关文章:

python - 从请求库 python 处理 cookiejar

python - 将多列添加到 pandas 数据框

python - 在网络图上绘制样本图像

python-3.x - 在networkx中设置自定义节点相等性比较

python Pandas "cannot set a row with mismatched columns"错误

python - 移动目录后 Django 无法工作。我有路径/Python 安装问题吗?

python - 通过selenium 输入tinymce 时遇到问题

python - 将networkx图输入zss算法(树编辑距离)

python - Networkx 图在不同平台上的大小不同

python - 颜色设置不会应用于图形绘制