微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

改变节点的属性

如何解决改变节点的属性

我有以下网络:

G = nx.Graph()
G.add_node(0,weight=8)
G.add_node(1,weight=5)
G.add_node(2,weight=3)
G.add_node(3,weight=2)
G.add_node(4,weight=1)
G.add_node(5,weight=5)
G.add_node(6,weight=8)

nx.add_path(G,[0,1,2,5])
nx.add_path(G,[2,6,3])
nx.add_path(G,[3,6])


# labels = {n: G.nodes[n]['weight'] for n in G.nodes}
labels = {
    n: str(n) + '\nweight=' + str(G.nodes[n]['weight']) if 'weight' in G.nodes[n] else str(n)
    for n in G.nodes
}
colors = [G.nodes[n]['weight'] for n in G.nodes]
fig = plt.figure(figsize=(10,10))

nx.draw(G,with_labels=True,labels=labels,node_color=colors)

每个节点都有自己的权重。我正在尝试根据其邻居的权重平均值更新每个节点的权重。

enter image description here

更新后,

  • 节点 0 的权重应为 6.5
  • 节点 1 的权重应为 5.33
  • 节点 2 的权重应为 5.25
  • 节点 3 的权重应为 5(因为它与 6 相关联)
  • 节点 4 仍应具有权重 1
  • 节点 5 的权重为 4
  • 节点 6 的权重应为 4.33

我会说,为了更新值,我可能应该使用 G.neighbors(x) 获取节点 x 的邻居的迭代器,或者只是循环遍历节点,但由于我需要计算平均值,因此不是正如我所期望的那样容易。

解决方法

我给你做了一个疯狂的列表理解(因为它们很酷):

newWeights = \
    [
        sum( # summ for averaging
            [G.nodes[neighbor]['weight'] for neighbor in G.neighbors(node)] # weight of every neighbor
            + [G.nodes[i]['weight']] # adds the node itsself to the average
        ) / (len(list(G.neighbors(node)))+1) # average over number of neighbours+1
        if len(list(G.neighbors(node))) > 0 # if there are no neighbours
        else G.nodes[i]['weight'] # weight stays the same if no neighbours
    for i,node in enumerate(G.nodes) # do the above for every node
    ]
print(newWeights) # [6.5,5.333333333333333,5.25,5.0,1,4.0,4.333333333333333]
for i,node in enumerate(G.nodes):
    G.nodes[i]['weight'] = newWeights[i] # writes new weights after it calculated them all.


但如果你讨厌玩乐并列出推导式,你也可以使用这个版本:

newWeights = []
for i,node in enumerate(G.nodes): # calculates average for every node
    summation = G.nodes[i]['weight'] # weight of node itsself
    for neighbor in G.neighbors(node): # adds the weight of every neighbour
        summation += G.nodes[neighbor]['weight']
    average = summation / (len(list(G.neighbors(node)))+1) # division for average 
    newWeights.append(average) 

print(newWeights)
for i,node in enumerate(G.nodes):
    G.nodes[i]['weight'] = newWeights[i]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。