如何将Python networkx图转换为pygsp



我使用Python,并试图将networkx图转换为pygsp图以绘制信号。然而,我无法理解有关如何完成这一简单代码的文档。我正在尝试使用此处列出的函数from_networkx:此处。

尝试:

我正在谷歌Colab笔记本中运行以下代码(只是一些虚构的例子(:

import pandas as pd
import numpy as np
import networkx as nx
# Make the networkx graph
G = nx.Graph()
# Add some cars (just do 4 for now)
G.add_nodes_from([
('Ford', {'y': 0}),
('Lexus', {'y': 1}),
('Peugot', {'y': 2}),
('Mitsubushi', {'y': 3}),
('Mazda', {'y': 4}),
])
# Relabel the nodes
remapping = {x[0]: i for i, x in enumerate(G.nodes(data = True))}
remapping
G = nx.relabel_nodes(G, remapping, copy=True)
G.nodes(data = True)
# Add some edges --> A = [(0, 1, 0, 1, 1), (1, 0, 1, 1, 0), (0, 1, 0, 0, 1), (1, 1, 0, 0, 0), (1, 0, 1, 0, 0)] as the adjacency matrix
G.add_edges_from([
(0, 1), (0, 3), (0, 4),
(1, 0), (1, 2), (1, 3),
(2, 1), (2, 4), 
(3, 0), (3, 1),
(4, 0), (4, 2)
])
!pip install pygsp
import pygsp
pygsp_graph = pygsp.graphs.Graph.from_networkx(G)

我不断收到错误,说模块不包含函数from_networkx。我尝试过不同的组合,但由于某种原因,我不知道如何完成这项极其简单的任务。

我使用的真实网络在networkx边缘列表中也有一些由"weight"表示的边缘权重,因此这些权重也应该能够通过pygspfrom_networkx函数的weight参数进行转换。

根据这一点,from_networkxto_networkx仅在开发版本中可用,您可以使用!pip install git+https://github.com/epfl-lts2/pygsp安装在google colab上。一旦你这样做,代码就会正常运行。

参见以下代码:

import pandas as pd
import numpy as np
import networkx as nx
# Make the networkx graph
G = nx.Graph()
# Add some cars (just do 4 for now)
G.add_nodes_from([
('Ford', {'y': 0}),
('Lexus', {'y': 1}),
('Peugot', {'y': 2}),
('Mitsubushi', {'y': 3}),
('Mazda', {'y': 4}),
])
# Relabel the nodes
remapping = {x[0]: i for i, x in enumerate(G.nodes(data = True))}
remapping
G = nx.relabel_nodes(G, remapping, copy=True)
G.nodes(data = True)
# Add some edges --> A = [(0, 1, 0, 1, 1), (1, 0, 1, 1, 0), (0, 1, 0, 0, 1), (1, 1, 0, 0, 0), (1, 0, 1, 0, 0)] as the adjacency matrix
G.add_edges_from([
(0, 1), (0, 3), (0, 4),
(1, 0), (1, 2), (1, 3),
(2, 1), (2, 4), 
(3, 0), (3, 1),
(4, 0), (4, 2)
])
!pip install git+https://github.com/epfl-lts2/pygsp
import pygsp
pygsp_graph = pygsp.graphs.Graph.from_networkx(G)
print(pygsp_graph)

输出给出:

Graph(n_vertices=5, n_edges=6)

最新更新