节点%u不在图中,COMMON_Neighbors网络X [英] Node u is not in the graph, common_neighbors networkX

查看:31
本文介绍了节点%u不在图中,COMMON_Neighbors网络X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用networkx进行链接预测,我想知道我的图中两个节点之间的公共邻居,看看它们是否可以链接,我遇到了这个问题。

所以这是我的代码:

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 数据帧并强制执行intdtype:fb_df = fb_df.astype('int')
  • relabel the graph nodesG_new = nx.convert_node_labels_to_integers(G)。使用此方法时,您需要检查新标签是否符合您的预期,例如,节点‘2’可以重新标记为整数0,有关详细信息,请参阅链接的文档。

这篇关于节点%u不在图中,COMMON_Neighbors网络X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆