You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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), and watts_strogatz_graph(n, 2, 0) (which produces a cycle graph when p=0) all create deterministic graphs. There's no randomness in their structure—for a fixed n, 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 using G for 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_state parameter:
    node_positions = networkx.spring_layout(G, scale=100, random_state=42)  # Fixed seed for reproducibility
    
    With this, every call to spring_layout for 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_state in spring_layout.

内容的提问来源于stack exchange,提问作者eric lardon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:37:06