This documents the development version of NetworkX. Documentation for the current release can be found here.

stochastic_block_model(sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True)[source]

Returns a stochastic block model graph.

This model partitions the nodes in blocks of arbitrary sizes, and places edges between pairs of nodes independently, with a probability that depends on the blocks.

  • sizes (list of ints) – Sizes of blocks

  • p (list of list of floats) – Element (r,s) gives the density of edges going from the nodes of group r to nodes of group s. p must match the number of groups (len(sizes) == len(p)), and it must be symmetric if the graph is undirected.

  • nodelist (list, optional) – The block tags are assigned according to the node identifiers in nodelist. If nodelist is None, then the ordering is the range [0,sum(sizes)-1].

  • seed (integer, random_state, or None (default)) – Indicator of random number generation state. See Randomness.

  • directed (boolean optional, default=False) – Whether to create a directed graph or not.

  • selfloops (boolean optional, default=False) – Whether to include self-loops or not.

  • sparse (boolean optional, default=True) – Use the sparse heuristic to speed up the generator.


g – Stochastic block model graph of size sum(sizes)

Return type

NetworkX Graph or DiGraph


NetworkXError – If probabilities are not in [0,1]. If the probability matrix is not square (directed case). If the probability matrix is not symmetric (undirected case). If the sizes list does not match nodelist or the probability matrix. If nodelist contains duplicate.


>>> 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))



Holland, P. W., Laskey, K. B., & Leinhardt, S., “Stochastic blockmodels: First steps”, Social networks, 5(2), 109-137, 1983.