27

I have bellow python code to build knn graph but I have an error: AttributeError: 'Graph' object has no attribute 'node'. It seems that the nx.Graph() has no node attribute but I don't know what should I replace with that.

import networkx as nx
def knn_graph(df, k, verbose=False):
    points = [p[1:] for p in df.itertuples()]
    g = nx.Graph()
    if verbose: print ("Building kNN graph (k = %d)" % (k))
    iterpoints = tqdm(enumerate(points), total=len(points)) if verbose else enumerate(points)
    for i, p in iterpoints:
        distances = map(lambda x: euclidean_distance(p, x), points)
        closests = np.argsort(distances)[1:k+1] # second trough kth closest
        for c in closests:
            g.add_edge(i, c, weight=distances[c])
        g.node[i]['pos'] = p
    return g
nino
  • 481
  • 2
  • 6
  • 13

2 Answers2

52

If you are using NetworkX 2.4, use G.nodes[] instead of G.node[]. The latter attribute is deprecated. See the release notes.

cottontail
  • 10,268
  • 18
  • 50
  • 51
Zechen Zhang
  • 621
  • 4
  • 3
0

I had the same issue. I'm using Anaconda3. pip uninstall networkx did not work in Anaconda command window. I opened Anaconda powershell and did pip uninstall networkx and then came back to Anaconda command window to pip install networkx==2.3

After this the error is resolved