如何将 Python networkx 图转换为 pygsp

How to convert Python networkx graph into pygsp

我正在使用 Python 并试图将 networkx 图形转换为 pygsp 图形以绘制信号。但是,我无法理解有关如何执行这段简单代码的文档。我正在尝试使用此处列出的函数 from_networkxhere.

尝试:

我是 运行 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 pygsp
import pygsp

pygsp_graph = pygsp.graphs.Graph.from_networkx(G)

我不断收到错误消息,指出该模块不包含函数 from_networkx。我尝试了不同的组合,但出于某种原因无法弄清楚如何完成这个极其简单的任务。

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

根据 thisfrom_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)