NetworkX重复生成指定图类时,邻接矩阵与节点位置是否一致?
Answer to Your Random Graph Generation Question
Let's break this down clearly into two key parts: adjacency matrices and node positions from the spring layout algorithm.
1. Adjacency Matrices: Identical Every Time
First, let's address the core structure of the graphs you're generating:
- Functions like
complete_graph(n),star_graph(n),balanced_tree(),wheel_graph(n), andwatts_strogatz_graph(n, 2, 0)(which produces a cycle graph whenp=0) all create deterministic graphs. There's no randomness in their structure—for a fixedn, every instance will have exactly the same set of edges. - In your code, there's a small bug: you're assigning the generated graph to
complete_graph(overwriting the NetworkX function name!) but then usingGfor layout and adjacency matrix calls. This will throw an error. You should fix it to something like:for i in numpy.arange(20): G = networkx.complete_graph(n) # Use a distinct variable name node_positions = networkx.spring_layout(G, scale=100) Adjacency = networkx.adjacency_matrix(G) - Once fixed, every iteration will produce an identical adjacency matrix
Adjacency, since the underlying graph structure never changes.
2. Node Positions: Different by Default
The spring_layout() function is where randomness comes in:
- This force-directed layout algorithm starts with random initial node positions by default. Even if you pass the exact same graph every time, the algorithm will converge to different (but visually similar) layouts on each run.
- If you want consistent node positions across iterations, you can fix the random seed using the
random_stateparameter:
With this, every call tonode_positions = networkx.spring_layout(G, scale=100, random_state=42) # Fixed seed for reproducibilityspring_layoutfor the same graph will return identical coordinates.
Quick Recap for All Your Graph Types
For every graph class you listed:
- Adjacency matrices will always be identical across instances (since the graphs are deterministic).
- Node positions will differ unless you set
random_stateinspring_layout.
内容的提问来源于stack exchange,提问作者eric lardon
相关产品推荐
相关产品推荐

