Runtime error with networkx : dictionary changed during iteration while running a neural gas script

社会主义新天地 提交于 2020-06-29 03:32:15

问题


I am trying to run a neural gas network with an older script that doesn't work well with networkx 2 so I modified some things. However I am getting the error : Dictionary changed size during iteration and I don't get how to fix this because networkx is not my speciality. Any help?

The code that is causing the problem right now:

def prune_connections(self, a_max):


    for u, v, attributes in self.network.edges(data=True):



        if attributes['age'] > a_max:



            self.network.remove_edge(u, v)



    for u in self.network.nodes():



        if self.network.degree(u) == 0:



            self.network.remove_node(u)

and the error I am getting :

    in __iter__

        for nbr, dd in nbrs.items():

RuntimeError: dictionary changed size during iteration

回答1:


Here you're looping through the edges of the graph:

for u, v, attributes in self.network.edges(data=True):

But within that loop you modify the edges. So self.network.edges (which is fundamentally a dictionary) is changing while you're iterating. This isn't allowed by python.

A solution to this is to predefine

edgelist = list(self.network.edges(data=True))

then do

for u, v, attributes in edgelist:



来源:https://stackoverflow.com/questions/62321965/runtime-error-with-networkx-dictionary-changed-during-iteration-while-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!