今天用到著名的社团检测算法Louvain时,发现GitHub上有一个非常成熟的包,地址如下:https://github.com/JavyWang/python-louvain
但是,导入包的方式有点奇怪,用的不是包名“python-louvain”而是“community”,在jupyter中运行的时候出现标题中的错误:
AttributeError: module ‘community’ has no attribute 'best_partition'
网上查了一下,有说是虚拟环境的问题,但是我没有用虚拟环境,于是到我系统中的python目录下将原来的包文件全部删除重新安装。
之前安装是用下面的命令
pip install python-louvain
这次我直接将GitHub中的包文件下载到python库中,下载路径为:https://github.com/taynaud/python-louvain/archive/master.zip
解压后在python-louvain-master所在的目录打开cmd,用下面的命令安装
python setup.py install
安装完毕后发现,site-packages中多了一个community包
这应该是到导入的包了,在pycharm里面运行了一下,没有问题。
import networkx as nx
import time
import pandas as pd
import community
input_file = 'F:/Data/CI_PLP/p2p-Gnutella24/p2p-Gnutella24_1.txt'
data = pd.read_csv(input_file, sep=' ', header=None, names=['A', 'B'], encoding='utf-8')
# 转换得到边列表
edgelist = data[['A', 'B']].values.tolist()
# 读取邻接列表生成网络
G = nx.from_edgelist(edgelist)
start_time = time.time()
coms = community.best_partition(G)
end_time = time.time()
print(end_time-start_time)
用时如下
C:\Users\WJW\AppData\Local\Programs\Python\Python36\python.exe F:/PYTHON/CI_PLP/main.py
87.85697078704834
Process finished with exit code 0
然后回到jupyter中跑一下,还是有问题,于是重启jupyter,好了。
可以运行,但是时间长了8秒左右。再次运行一遍,时间少了很多。