模块 'networkx' 没有属性 'stochastic_block_model'

module 'networkx' has no attribute 'stochastic_block_model'

我正在尝试使用此页面中记录的 networkx "stochastic_block_model" 中的函数生成随机块模型图:https://networkx.github.io/documentation/stable/reference/generated/networkx.generators.community.stochastic_block_model.html

我的 networkx 包已更新到 2.2 版本,但我一直收到错误消息: 模块 'networkx' 没有属性 'stochastic_block_model'。 我该如何解决这个问题?

import networkx as nx


sizes = [75, 75, 300]
probs = [[0.25, 0.05, 0.02],
        [0.05, 0.35, 0.07],
        [0.02, 0.07, 0.40]]
g = nx.stochastic_block_model(sizes, probs, seed=0)
len(g)

H = nx.quotient_graph(g, g.graph['partition'], relabel=True)
for v in H.nodes(data=True):
    print(round(v[1]['density'], 3))




for v in H.edges(data=True):
    print(round(1.0 * v[2]['weight'] / (sizes[v[0]] * sizes[v[1]]), 3))

我正在使用 networkx 的 2.2 版,它是 pypi 上的最新版本。这应该有效:

from networkx.generators.community import stochastic_block_model

在生成器 networkx.generators 包的 __init__.py 中,您会发现:

"""
A package for generating various graphs in networkx.

"""
from networkx.generators.atlas import *
from networkx.generators.classic import *
from networkx.generators.community import *
from networkx.generators.degree_seq import *
from networkx.generators.directed import *
from networkx.generators.duplication import *
from networkx.generators.ego import *
from networkx.generators.expanders import *
from networkx.generators.geometric import *
from networkx.generators.intersection import *
from networkx.generators.joint_degree_seq import *
from networkx.generators.lattice import *
from networkx.generators.line import *
from networkx.generators.mycielski import *
from networkx.generators.nonisomorphic_trees import *
from networkx.generators.random_clustered import *
from networkx.generators.random_graphs import *
from networkx.generators.small import *
from networkx.generators.social import *
from networkx.generators.spectral_graph_forge import *
from networkx.generators.stochastic import *
from networkx.generators.trees import *
from networkx.generators.triads import *

因此,您应该能够像这样导入它:

from networkx.generators import stochastic_block_model

重点是我必须杀死 运行 实例并重新启动我的笔记本或任何 python shell 升级包后才能获得新的更新。