如何计算networkx中的间接关系?间接联系被定义为没有直接关系但通过社交网络中的第三人联系的两个人之间的关系。
尝试检查 Networkx 中的一些现有库,例如共同邻居等,但与间接关系的定义不匹配。
虽然没有特定的 NetworkX 功能,但您仍然可以使用 NetworkX 创建自己的功能(我将在评论中解释 - 抱歉,如果冗长):
import networkx as nx
def find_indirect(G): #G is a graph
# We create an empty dictionary to hold all of the pairs which have indirect ties
indirect_ties = {}
# Iterate over all pairs of nodes in our graph
for x in G.nodes():
for y in G.nodes():
if x != y and not G.has_edge(x, y): # That means 1. the nodes are not the same node and no edge exists between them
neighbors_of_x = set(G.neighbors(x))
neighbors_of_y = set(G.neighbors(y))
# Finding the intersection of the sets creates the unique set of neighbors shared between the two
common_neighbors = neighbors_of_x.intersection(neighbors_of_y)
if common_neighbors: # Obviously if not common_neighbors is true obviates this
indirect_ties[(x, y)] = list(common_neighbors) # Now we have each key in the dict as a tuple of the two nodes that have indirect ties, and the value for the key is what is shared
return indirect_ties
显然,你可以稍微改变一下。我使用字典方法来展示如何存储负责使节点间接的公共邻居。但是,您可以轻松修改代码并仅存储间接节点。