拓端tecdat|用R语言编程代写和python进行社交网络中的社区检测

原文链接:http://tecdat.cn/?p=7295

 

在这篇文章中,我用R语言和python检测社交网络中的社区

 

 

 

 

建立自我网络

Kaggle数据 在110个.egonet文件中(对应于110个匿名Facebook用户),每个文件都包含他的朋友的网络。 

让我们关注文件0.egonet,其中包含有关用户0的网络的所有信息。文件的每一行都是该行中直接属于自我网络一部分的第一个用户的朋友的列表。 

 

1

2

3

4

1: 146 189 229 201 204 ...

2: 146 191 229 201 204 ...

3: 185 80 61 188 22 222 ...

4: 72 61 187 163 177 138 ...

01个朋友,而146-189-229 …也有朋友。

02个朋友,而146-191-229 …也有朋友。

03个朋友,而185-80-61 …也有朋友。

04个朋友,而72-61-187 …也有朋友。

 在下面,我附加了访问每个egonet文件的Python代码,并构建了要馈送到Networkx构造函数的节点和边的列表。 构建图后,将计算其邻接矩阵并将其保存在csv文件中。

 

import networkx as nx

from os import listdir

from os.path import isfile, join

import itertools

import matplotlib.pyplot as plt

import os

import re

import scipy

from scipy.sparse import *

from operator import itemgetter

from sklearn.cluster import KMeans

import numpy as np

import sys

import pandas as pd

 

 

def load_egonet_files(path):

    """

    given the path to the .egonet files returns a list with all the files.

    """

    onlyfiles = [fyle for fyle in listdir(path) if fyle.endswith('.egonet')]

    return onlyfiles

 

#########################################################################################################

  
   

 

提供的代码的结果是110个CSV文件,其中包含每个自我网络图的邻接矩阵。

 

检测社区

首先,让我们绘制一个图,看看它在聚类检测之前的样子。在R代码下方,从CSV文件加载数据,构建网络(我们使用0.egonet)并进行绘制。

 

# read graph from csv file

dat = read.csv('graph-0.csv', header=TRUE, row.names=1, check.names=FALSE)

m = as.matrix(dat)

# build graph from adjacency matrix

g = graph.adjacency(m,mode="undirected",weighted=NULL)

 

# plots the graph

 

 

  

R 提供了几种强大的社区检测算法。 

模块化本质上是属于给定组的边缘的分数减去如果边缘随机分布的预期分数。所以越高越好。

在这里,您可以在用户0网络上找到结果。

 


> modularity(wc)

[1] 0.4629543

 

> modularity(wc)

[1] 0.4463902

 


> modularity(wc)

[1] 0.4330911

 


> modularity(wc)

[1] 0.4649535

 


> modularity(wc)

[1] 0.4511259

 

> modularity(wc)

[1] 0.4314803

 

 spinglass.community算法(基于统计物理方法)是最好的算法,其模块化为0.4649。事实证明,对于小型自我社会网络中的社区发现这一特殊问题 。

在下面,您也可以在R中找到检测到的群集的良好可视化效果。 

如果您有任何疑问,请在下面发表评论。   

 

posted @ 2019-10-08 16:09  拓端tecdat  阅读(418)  评论(0编辑  收藏  举报