如何在python中使用networkx找到谁是网络中最重要的个人?

时间:2018-03-09 09:15:23

标签: python facebook dataset networkx network-analysis

我正在使用facebook snap数据集,并在python上使用 networkX 在其上创建图表。但是找不到最重要的,或者你可以说网络中连接最多的那个。

我正在使用的代码我在facebook snap数据集上制作图表:

import networkx as nx
import matplotlib.pyplot as plt


'''Exploratory Data Analysis'''
g = nx.read_edgelist('facebook_combined.txt', create_using=nx.Graph(), nodetype=int)
print nx.info(g)

'''Simple Graph'''
sp = nx.spring_layout(g)
nx.draw_networkx(g, pos=sp, with_labels=False, node_size=35)
# plt.axes("off")
plt.show()

它给出的结果是:

enter image description here

数据集的链接是here

数据集的来源是here

但问题是我怎样才能在这个网络中找到最重要的个人?

1 个答案:

答案 0 :(得分:3)

定义"重要性的一种方式"是个人的中介中心性。中介中心性是衡量通过特定顶点的最短路径的度量。通过顶点的路径越短,顶点到网络的中心就越多。

因为任何一对顶点之间的最短路径可以独立于任何其他顶点对确定。 为此,我们将使用multiprocessing库和itertools库中的Pool对象。

我们需要做的第一件事是将网络的顶点划分为n个子集,其中n取决于我们有权访问的处理器的数量。例如,如果我们使用具有32个核心的计算机,我们将Facebook网络划分为32个块,每个块包含128个顶点。

现在不是一个处理器计算所有4,039个顶点的中介性,而是我们可以有32个处理器并行计算128个顶点中每个顶点之间的中介性。这大大减少了算法的运行时间,并允许它扩展到更大的网络。

我使用的代码是:

import networkx as nx
import matplotlib.pyplot as plt


'''Exploratory Data Analysis'''
    g = nx.read_edgelist('facebook_combined.txt', create_using=nx.Graph(), nodetype=int)
print nx.info(g)

'''Parallel Betweenness Centrality'''
from multiprocessing import Pool
import itertools

spring_pos = nx.spring_layout(g)


def partitions(nodes, n):
    # '''Partitions the nodes into n subsets'''
    nodes_iter = iter(nodes)
    while True:
        partition = tuple(itertools.islice(nodes_iter,n))
        if not partition:
            return
        yield partition


def btwn_pool(G_tuple):
    return nx.betweenness_centrality_source(*G_tuple)


def between_parallel(G, processes=None):
    p = Pool(processes=processes)
    part_generator = 4 * len(p._pool)
    node_partitions = list(partitions(G.nodes(), int(len(G) / part_generator)))
    num_partitions = len(node_partitions)

    bet_map = p.map(btwn_pool,
                    zip([G] * num_partitions,
                        [True] * num_partitions,
                        [None] * num_partitions,
                        node_partitions))

    bt_c = bet_map[0]
    for bt in bet_map[1:]:
        for n in bt:
            bt_c[n] += bt[n]
    return bt_c


bt = between_parallel(g)
top = 10

max_nodes = sorted(bt.iteritems(), key=lambda v: -v[1])[:top]
bt_values = [5] * len(g.nodes())
bt_colors = [0] * len(g.nodes())
for max_key, max_val in max_nodes:
    bt_values[max_key] = 150
    bt_colors[max_key] = 2

plt.axis("off")
nx.draw_networkx(g, pos=spring_pos, cmap=plt.get_cmap("rainbow"), node_color=bt_colors, node_size=bt_values,
                 with_labels=False)

plt.show()

它给出的输出: enter image description here

现在,让我们看看网络中具有前10个最高中介中心性度量的顶点。 如您所见,主要位于集线器中心或作为两个集线器之间桥梁的顶点具有较高的中介中心性。桥顶点具有高中介性,因为连接集线器的所有路径都通过它们,并且集线器中心顶点具有高中介性,因为所有内部集线器路径都通过它们。