如何使用python在networkx中找到不同的组?

问题描述 投票:2回答:1

我正在使用facebook数据集并在其上制作图表。但是却无法在其中找到不同的群体。我使用的代码是这样的:

import networkx as nx
import matplotlib.pyplot as plt

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

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

提前致谢!

python facebook python-2.7 networkx network-analysis
1个回答
0
投票

定义

群组的另一个术语是群集。这是一个相当普遍的问题。

您必须定义群集(或分组)指标。解决此问题的一种方法是定义距离度量。例如,您可以使用Jaccard距离。如果它们共享共同的邻居,则两个节点关闭:

距离矩阵

import numpy as np
nn = len(g.nodes)
mat = np.empty((nn, nn), dtype=float)
mat.fill(-100.0)
np.fill_diagonal(mat, -0.0)

Networkx可以使用nx.jaccard_coefficient()为您计算Jaccard系数:

preds = nx.jaccard_coefficient(g, g.edges)
for u, v, j in preds:
    mat[u,v] = -100 * (1 - j)

聚类

from sklearn.cluster import AffinityPropagation
np.median(mat)
af = AffinityPropagation(preference=-100, affinity="precomputed")
lab = af.fit_predict(mat)
len(np.unique(lab))

结果:571个集群

绘制

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

plt.figure(figsize=(15,6))
pd.value_counts(lab).plot.bar()
plt.xticks([])
plt.show()

plot

最大的群集包含70个节点。

编辑:

社区检测

您似乎想要找到社区。您可以使用python-louvain package来分区图:

import community
import collections

partition = community.best_partition(g)
values = [partition.get(node) for node in g.nodes()]
counter=collections.Counter(values)
print(counter)

[出]:Counter({7: 548, 4: 543, 2: 435, 1: 431, 3: 423, 0: 350, 5: 323, 9: 237, 13: 226, 12: 206, 6: 121, 8: 73, 11: 60, 10: 25, 14: 19, 15: 19})

您可以使用颜色可视化这些“组”:

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.