簡體   English   中英

如何從未連接的圖形中隨機選擇兩個節點(節點對),Python,networkx

[英]how to select two nodes (pairs of nodes) randomly from a graph that are NOT connected, Python, networkx

我想從圖中提取兩個節點,因為它們不應該連接,即它們之間不存在直接邊緣。 我知道我可以使用“random.choice(g.edges())獲得隨機邊緣”,但這會給我連接的隨機節點。 我想要一對未連接的節點(一對未連接的邊)。 幫助我...伙計們

簡單! :)

抓取一個隨機節點 - 然后從不包括鄰居和自身的節點列表中選擇一個隨機節點。 代碼說明如下。 :)

import networkx as nx
from random import choice

# Consider this graph
#
#     3
#     |
# 2 - 1 - 5 - 6
#     | 
#     4

g = nx.Graph()
g.add_edge(1,2)
g.add_edge(1,3)
g.add_edge(1,4)
g.add_edge(1,5)
g.add_edge(5,6)

first_node = choice(g.nodes())                  # pick a random node
possible_nodes = set(g.nodes())
neighbours = g.neighbors(first_node) + [first_node]
possible_nodes.difference_update(neighbours)    # remove the first node and all its neighbours from the candidates
second_node = choice(list(possible_nodes))      # pick second node      

print first_node, second_node

到目前為止,這里提出的解決方案都不會均勻地對非邊緣(v1,v2)進行采樣。 考慮具有4個節點和2個邊的示例圖:

1 —— 2
|
3    4

有4種非邊緣可供選擇:(1,4),(2,3),(2,4),(3,4)。 使用Maria或Philip的方法從所有4個頂點中隨機選擇第一個頂點,然后從受限制的頂點集中選擇第二個頂點,以便不創建任何邊(或自循環),將為每個頂點提供以下概率要選擇的邊緣:

p(1,4)= 1/4 * 1 + 1/4 * 1/3 = 8/24

p(2,3)= 1/4 * 1/2 + 1/4 * 1/2 = 6/24

p(3,4)= p(2,4)= 1/4 * 1/2 + 1/4 * 1/3 = 5/24

所以程序不統一。

這意味着如果您想要均勻采樣的非邊緣,則必須選擇兩個不受限制的頂點,並在它們形成現有邊(或相等)時拒絕樣本(兩個頂點)。 在NetworkX中:

v1 = np.random.choice(G.nodes())
v2 = np.random.choice(G.nodes())

while G.has(edge(v1,v2)) or v1==v2:
  v1 = np.random.choice(G.nodes())
  v2 = np.random.choice(G.nodes())

我不知道那個庫,但我想你可以做到以下幾點:

  n1 = random.choice(g.nodes())
  n2 = random.choice(g.nodes()) 
  while (n1 == n2 or any of the edges of n1 lead to n2):
    n2 = random.choice(g.nodes())
  enjoy(yourNodes)

干杯

如果圖形很小,您可以將nx.non_edges()收集到np.arrayrandom.choice

non_edges = np.array(nx.non_edges(graph))

sample_num = 10000
sample = non_edges[np.random.choice(len(non_edges), sample_num, replace=False)]

請注意, non_edges()本身會返回生成器,而不是實際列表。 但是如果你把它變成一個np.array你就會收集生成器中的所有項目。 如果你的圖形很大且稀疏,這可能會引起內存錯誤,但對於小圖形,這將是最簡單的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM