gpt4 book ai didi

python - 从网络图中有效地创建邻接矩阵(反之亦然)Python NetworkX

转载 作者:行者123 更新时间:2023-12-04 23:42:25 29 4
gpt4 key购买 nike

我正在尝试创建网络图并从中生成稀疏矩阵。来自维基百科Laplacian matrix例如,我决定尝试使用 networkx 重新创建以下网络图

enter image description here

如何有效地在 adjacency matrix 之间转换和一个 network graph ?

例如,如果我有一个网络图,我如何快速将其转换为邻接矩阵,如果我有一个邻接图,我如何有效地将其转换为网络图。

下面是我的代码,我觉得它对于大型网络来说效率很低。

#!/usr/bin/python

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import pandas as pd

%matplotlib inline

#Adjacent matrix
adj_matrix = np.matrix([[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0]])
adj_sparse = sp.sparse.coo_matrix(adj_matrix, dtype=np.int8)
labels = range(1,7)
DF_adj = pd.DataFrame(adj_sparse.toarray(),index=labels,columns=labels)
print DF_adj

# 1 2 3 4 5 6
#1 0 1 0 0 1 0
#2 1 0 1 0 1 0
#3 0 1 0 1 0 0
#4 0 0 1 0 1 1
#5 1 1 0 1 0 0
#6 0 0 0 1 0 0

#Network graph
G = nx.Graph()
G.add_nodes_from(labels)

#Connect nodes
for i in range(DF_adj.shape[0]):
col_label = DF_adj.columns[i]
for j in range(DF_adj.shape[1]):
row_label = DF_adj.index[j]
node = DF_adj.iloc[i,j]
if node == 1:
G.add_edge(col_label,row_label)


#Draw graph
nx.draw(G,with_labels = True)

#DRAWN GRAPH MATCHES THE GRAPH FROM WIKI

#Recreate adjacency matrix
DF_re = pd.DataFrame(np.zeros([len(G.nodes()),len(G.nodes())]),index=G.nodes(),columns=G.nodes())
for col_label,row_label in G.edges():
DF_re.loc[col_label,row_label] = 1
DF_re.loc[row_label,col_label] = 1
print G.edges()
#[(1, 2), (1, 5), (2, 3), (2, 5), (3, 4), (4, 5), (4, 6)]

print DF_re
# 1 2 3 4 5 6
#1 0 1 0 0 1 0
#2 1 0 1 0 1 0
#3 0 1 0 1 0 0
#4 0 0 1 0 1 1
#5 1 1 0 1 0 0
#6 0 0 0 1 0 0

最佳答案

如何从图转换为邻接矩阵:

import scipy as sp
import networkx as nx
G=nx.fast_gnp_random_graph(100,0.04)
adj_matrix = nx.adjacency_matrix(G)

这是 documentation .

从邻接矩阵到图:
H=nx.Graph(adj_matrix)  #if it's directed, use H=nx.DiGraph(adj_matrix)

这是 documentation .

关于python - 从网络图中有效地创建邻接矩阵(反之亦然)Python NetworkX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33773187/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com