AttributeError: 模块 'networkx.algorithms.community' 没有 'best_partition' 属性。

13

我正在尝试使用网络分析库 networkx 中的 社区检测算法,应用于著名的 Facebook Snap 数据集。

这是我的代码:

import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import community
from networkx.algorithms.community.centrality import girvan_newman

G_fb = nx.read_edgelist("./facebook_combined.txt",create_using = nx.Graph(), nodetype=int)

parts = community.best_partition(G_fb)
values = [parts.get(node) for node in G_fb.nodes()]

但是当我运行这个单元格时,我遇到了标题错误,即:

AttributeError: module 'networkx.algorithms.community' has no attribute 'best_partition'

有什么建议吗?

7个回答

13
我认为你混淆了networkx中的community modulepython-louvain模块中的社区检测,后者使用了networkx。
如果安装了python-louvain,则其文档中的示例对我有效,并生成像这样的图像。

sample graph partition

请注意,您将导入community而不是networkx.algorithms.community。也就是说,
import community

[.. code ..]

partition = community.best_partition(G_fb)

当我尝试导入 community 时,出现了这个错误:模块没有名为'community'。 - Mohammad Heydari
4
你是否真正安装了 python-louvain 模块? - DSM
拯救了我的一天。谢谢。 - Adiii
1
我使用的代码和你的完全一样,但仍然出现相同的错误。你能帮忙吗? - Fatemeh Asgarinejad

10

我在CS224W中遇到了这个问题

AttributeError: 模块'community'没有属性'best_partition' enter image description here

请修改karate.py文件

将导入语句替换为 import community.community_louvain as community_louvain

然后它对我起作用。


4

我有同样的问题。在我的情况下,通过不同的方式导入模块来解决了这个问题:

import community.community_louvain

Source


非常感谢! | 导入 community.community_louvain 作为 louvain。 | partitions = louvain.best_partition(G) - Mohammad Aqajani

2
我天真地以为 pip install community 是我要找的包,但实际上我需要 pip install python-louvain,然后作为 import community 导入。

1

我在CS224W中也遇到了这个问题,但更改karate.py或其他解决方案都没有起作用。

对我来说(在colab中),使用新的PyG安装代码有效。此代码将安装最新版本:

!pip install -q torch-scatter -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html
!pip install -q torch-sparse -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html
!pip install -q git+https://github.com/rusty1s/pytorch_geometric.git

0

这帮助我在没有错误的情况下运行代码:

pip uninstall community
import community.community_louvain as cl
partition = cl.best_partition(G_fb)

0

我曾经遇到过类似的问题。 在我的情况下,是因为另一台机器上的库networkx已经过时了。

通过以下命令,问题得以解决。

pip3 install --upgrade networkx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接