【问题标题】:networkx says I have less nodes than I actually havenetworkx 说我的节点比实际的少
【发布时间】:2019-07-03 14:54:18
【问题描述】:

我对 NetworkX 有一个奇怪的问题。
给定DS-1 dataset,我的任务是每年创建一个在数据集中报告的图表。到目前为止,完全没有问题。对于 2013 年,这就是我得到的

我们可以说...有点拥挤。
现在这是我的奇怪问题。我的作业表明我应该按照某种逻辑选择每个图的顶部 k 节点。所以,由于我有一些节点少于 5 个的图(并且,根据要求,这个 k 将是 [0,5,10,50,200] 中的一个值),我想在迭代中排除那些 len(G ) 是

for x in graphsPerYear:
    G = graphsPerYear[x]
    if len(G) < k:
        print(G.nodes)
        print(G.number_of_nodes())
        print("Skipping year " + str(x) + " since it has " + str(len(G)) + " nodes which is less than the prompted k")
        continue

这会输出以下内容:

['linear matrix inequality', 'social inequality']
2
Skipping year 2013 since it has 2 nodes which is less than the prompted k

但图片却完全相反。我错过了什么?

编辑

添加图表的创建

def createGraphPerYear(dataset, year):
    insertedWords = set()
    listaAnni = set(dataset['anno'].values)
    grafi = dict()
    for anno in listaAnni:
        datasetTemporale = dataset[dataset['anno'] == anno]
        G=nx.DiGraph()
        for index, row in datasetTemporale.iterrows():
            #Reminder: ogni row è formato da anno, keyword1, keyword2, dizionario utilizzatore keywords - numero volte
            #FASE 1: AGGIUNTA DEI DUE POSSIBILI NODI
            if row.keyword1 not in G:
                G.add_node(row.keyword1)
            if row.keyword2 not in G:
                G.add_node(row.keyword2)
            if not __areNodesConnected(G,row.keyword1, row.keyword2):
                G.add_edge(row.keyword1,row.keyword2)
        grafi[anno] = G
    return grafi

def __areNodesConnected(G, nodeToCheckOne,nodeToCheckTwo):
    return nodeToCheckOne in G.neighbors(nodeToCheckTwo)

【问题讨论】:

  • 注释:对于DiGraph,如果从uv 已经存在边,则命令G.add_edge(u,v) 将不起作用。否则,如果这些节点中的任何一个不存在,它将首先添加节点,然后创建边。所以你在for循环中的if语句可以被删除,__areNodesConnected就不需要了。 [同样__areNodesConnected 等同于G.has_edge(nodeToCheckOne,nodeToCheckTwo)]。
  • 我很确定问题出在您未显示的其他代码中。您能否为2013 绘制图表并检查它是否与您显示的图相似,然后立即检查len(G)
  • @Joel 所以这就是我所做的:采用迭代 graphsPerYear 的 for,在 G 初始化之后,我放了一个 nx.draw(G) plt.show(),紧接着,一个打印(长度(G))。输出是 170,这对我来说很酷(P.S.:感谢您的评论!)

标签: python graph networkx


【解决方案1】:

当您将节点添加到网络时,hashes 它会确定唯一性。 任何具有相同hash 的节点都被确定为相同。

By definition, a Graph is a collection of nodes (vertices) 
along with identified pairs of nodes (called edges, links, etc). 
In NetworkX, nodes can be any hashable object e.g., 
a text string, an image, an XML object, another Graph, 
a customized node object, etc.

仔细检查项目是否不是同一个字符串,或者它们的哈希性对于不同的节点是否等效。

【讨论】:

  • 2013 年有 453 个条目...并不是说我不想检查所有条目,但是,恕我直言,看看图像有助于确定肯定有不同的字符串。另外:在创建图表时,我会仔细检查关键字是否已经在其中(如果关键字不在 G 中)
  • 请在您add_nodeadd_edge 时发布您的问题以及如何完成
  • 完成了,内森! :)
  • sto leggendo questi tsv ma non capisco il formatto, spiegami le Colonne
  • 所以我有这个数据集,它代表了一些作者随着时间的推移如何使用一些关键字。 Year:表示该行被引用的年份; keywordOne:是一些科学论文中使用的第一个关键字;关键字二:和以前一样;最后一列应该代表在这两个关键字之间创建的边缘装饰器
猜你喜欢
  • 2021-09-30
  • 2015-01-17
  • 2014-09-13
  • 2022-10-13
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多