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

如何用Python将普通矩阵转换为关联矩阵并绘制图网络

Convert Regular Matrix to Incidence Matrix & Plot Graph in Python

Hey there! Let's walk through this step by step—first figuring out how to turn your "regular matrix" into an incidence matrix, then using Python to visualize the resulting graph. First, let's make sure we're aligned on definitions:

An incidence matrix is an n×m matrix where n = number of nodes, m = number of edges. For undirected graphs, entries are 1 if a node is connected to an edge, 0 otherwise. For directed graphs, entries are +1 for the edge's start node, -1 for the end node.

First: Clarify Your "Regular Matrix" Type

Most often, people refer to an adjacency matrix (n×n, where A[i][j] = 1 if nodes i and j are connected) as a "regular matrix" for graph tasks. Below are two common scenarios:


Scenario 1: Your Regular Matrix is an Adjacency Matrix

If you already have an adjacency matrix (directed or undirected), here's how to convert it to an incidence matrix and plot the graph:

Step 1: Import Required Libraries

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

Step 2: Convert Adjacency Matrix to Incidence Matrix

We'll write a helper function to handle both directed and undirected graphs:

def adj_to_incidence(adj_matrix, directed=False):
    n_nodes = adj_matrix.shape[0]
    edges = []
    
    # Collect unique edges (avoid duplicates for undirected graphs)
    for i in range(n_nodes):
        # For undirected, only check j > i to skip reverse edges
        range_j = range(i+1, n_nodes) if not directed else range(n_nodes)
        for j in range_j:
            if adj_matrix[i][j] != 0:
                edges.append((i, j))
    
    n_edges = len(edges)
    incidence_matrix = np.zeros((n_nodes, n_edges), dtype=int)
    
    # Populate the incidence matrix
    for edge_idx, (u, v) in enumerate(edges):
        if directed:
            incidence_matrix[u][edge_idx] = 1
            incidence_matrix[v][edge_idx] = -1
        else:
            incidence_matrix[u][edge_idx] = 1
            incidence_matrix[v][edge_idx] = 1
    
    return incidence_matrix, edges

Step 3: Test with an Example

Let's use a simple undirected graph adjacency matrix:

# Example: 3 nodes connected in a triangle
adj_matrix = np.array([
    [0, 1, 1],
    [1, 0, 1],
    [1, 1, 0]
])

incidence_matrix, edges = adj_to_incidence(adj_matrix)
print("Incidence Matrix:\n", incidence_matrix)
# Output:
# [[1 1 0]
#  [1 0 1]
#  [0 1 1]]

Step 4: Plot the Graph

You can build the graph directly from the adjacency matrix (simpler) or use the incidence matrix:

# Option 1: Build graph from adjacency matrix
G = nx.from_numpy_array(adj_matrix, create_using=nx.Graph())

# Option 2: Build graph from incidence matrix
# G = nx.incidence_matrix_to_graph(incidence_matrix)

# Visualize
plt.figure(figsize=(6, 6))
nx.draw(G, with_labels=True, node_color="#aaddff", node_size=1600, font_size=14, edge_color="#333333")
plt.title("Triangle Graph from Adjacency Matrix")
plt.show()

Scenario 2: Your Regular Matrix is Not an Adjacency Matrix

If your matrix is something else (like a node feature matrix, where each row is a node's attributes), you first need to define rules to create edges, then generate an adjacency matrix. For example, let's use cosine similarity to connect nodes with similar features:

# Example: 3 nodes with 2D features
feature_matrix = np.array([
    [1.0, 2.0],
    [3.0, 4.0],
    [1.1, 2.2]
])

# Step 1: Compute similarity between nodes
from sklearn.metrics.pairwise import cosine_similarity
similarity_matrix = cosine_similarity(feature_matrix)

# Step 2: Create adjacency matrix (connect nodes with similarity > 0.9)
adj_matrix = (similarity_matrix > 0.9).astype(int)
np.fill_diagonal(adj_matrix, 0)  # Remove self-loops

# Step 3: Convert to incidence matrix (same function as before)
incidence_matrix, edges = adj_to_incidence(adj_matrix)

# Step 4: Plot the graph
G = nx.from_numpy_array(adj_matrix)
plt.figure(figsize=(6, 6))
nx.draw(G, with_labels=True, node_color="#ffddaa", node_size=1600, font_size=14)
plt.title("Graph from Feature Matrix (Similarity-Based Edges)")
plt.show()

Key Takeaways

  1. Identify your matrix type: If it's already an adjacency matrix, skip straight to conversion. If not, define edge rules first to build an adjacency matrix.
  2. Use networkx for graph tasks: It handles both adjacency and incidence matrices seamlessly, so you don't have to reinvent the wheel for plotting.

内容的提问来源于stack exchange,提问作者farah lana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:42:44