节点 u 不在图中,common_neighbors networkX

Node u is not in the graph, common_neighbors networkX

我正在使用 networkx 进行 link 预测,我想知道图表中 2 个节点之间的共同邻居,看看它们是否可以被 linked,我遇到了这个问题。

所以这是我的代码:

import pandas as pd
import numpy as np
import random
import networkx as nx
from tqdm import tqdm
import re
import matplotlib.pyplot as plt

# load nodes details
with open("/content/drive/MyDrive/fb-pages-food.nodes") as f:
    fb_nodes = f.read().splitlines() 

# load edges (or links)
with open("/content/drive/MyDrive/fb-pages-food.edges") as f:
    fb_links = f.read().splitlines() 

len(fb_nodes), len(fb_links)


# capture nodes in 2 separate lists
node_list_1 = []
node_list_2 = []

for i in tqdm(fb_links):
  node_list_1.append(i.split(',')[0])
  node_list_2.append(i.split(',')[1])

fb_df = pd.DataFrame({'node_1': node_list_1, 'node_2': node_list_2})


# create graph
G = nx.from_pandas_edgelist(fb_df, "node_1", "node_2", create_using=nx.Graph())

# plot graph
plt.figure(figsize=(10,10))

pos = nx.random_layout(G, seed=23)
nx.draw(G, with_labels=False,  pos = pos, node_size = 40, alpha = 0.6, width = 0.7)
plt.show()

问题出在这里:

sorted(nx.common_neighbors(G, 0, 1))
NetworkXError                             Traceback (most recent call last)
<ipython-input-59-93f15d34d0d4> in <module>()
----> 1 sorted(nx.common_neighbors(G, 0, 1))

1 frames
/usr/local/lib/python3.7/dist-packages/networkx/classes/function.py in common_neighbors(G, u, v)
    952     """
    953     if u not in G:
--> 954         raise nx.NetworkXError("u is not in the graph.")
    955     if v not in G:
    956         raise nx.NetworkXError("v is not in the graph.")

NetworkXError: u is not in the graph.

如果没有相同的数据就不可能重现您的错误,但一种可能的解释是原始数据中的节点标签与整数不同,例如它们是整数的字符串表示形式(例如“1”、“2”与 1、2)。

可能的解决方案是:

  • 检查 pandas 数据框并执行 int dtype:fb_df = fb_df.astype('int')
  • relabel the graph nodesG_new = nx.convert_node_labels_to_integers(G)。使用这种方法,您需要检查新标签是否符合您的期望,例如节点“2”可以重新标记为整数 0,有关详细信息,请参阅链接文档。