How to solve Chinese Whispers Python Issue 'AttributeError: 'Graph' object has no attribute 'node'

How to solve Chinese Whispers Python Issue 'AttributeError: 'Graph' object has no attribute 'node'

我正在尝试实现Chinese Whispers Algorithm,但我无法弄清楚下面的问题:我想要得到的结果如下图所示

import networkx as nx
from random import shuffle as shuffle
# build nodes and edge lists
nodes = [
    (1,{'attr1':1}),
    (2,{'attr1':1})

]
edges = [
    (1,2,{'weight': 0.732})

]
# initialize the graph
G = nx.Graph()
# Add nodes
G.add_nodes_from(nodes)
# CW needs an arbitrary, unique class for each node before initialisation
# Here I use the ID of the node since I know it's unique
# You could use a random number or a counter or anything really
for n, v in enumerate(nodes):
  G.node[v[0]]["class"] = v[1]["attr1"]
# add edges
G.add_edges_from(edges)
# run Chinese Whispers
# I default to 10 iterations. This number is usually low.
# After a certain number (individual to the data set) no further clustering occurs
iterations = 10
for z in range(0,iterations):
    gn = G.nodes()
    # I randomize the nodes to give me an arbitrary start point
    shuffle(gn)
    for node in gn:
        neighs = G[node]
        classes = {}
        # do an inventory of the given nodes neighbours and edge weights
        for ne in neighs:
            if isinstance(ne, int) :
                if G.node[ne]['class'] in classes:
                    classes[G.node[ne]['class']] += G[node][ne]['weight']
                else:
                    classes[G.node[ne]['class']] = G[node][ne]['weight']
        # find the class with the highest edge weight sum
        max = 0
        maxclass = 0
        for c in classes:
            if classes[c] > max:
                max = classes[c]
                maxclass = c
        # set the class of target node to the winning local class
        G.node[node]['class'] = maxclass

我想做这个输出 enter image description here

使用 G.nodes 代替 G.node

如@Shridhar R Kulkarni 的回答所述,您希望在引用 updating/adding 属性的节点时使用 G.nodes

脚本的另一个问题是,对于洗牌,您只需要节点标识符列表:

    gn = list(G.nodes()) # use list() to allow shuffling
    shuffle(gn)

如果您只对计算感兴趣,而不是(重新)实现,您也可以使用现有的库 chinese-whispers