Pytorch-Geometric

I’m new to Pytorch-geometric, and geometric deep learning. I’m trying to visualize the datasets available in pytorch-geometric, but couldn’t find anything to do so.

How do I visualize these graph datasets. Is there provision to do so in pytorch-geometric? How else can we visualize this ?

from torch_geometric.datasets import KarateClub
dataset = KarateClub()

for i in dataset[0]:
  print(i)
# this torch.geometric.datasets object comprises of edge(edge information for each node), x(nodes) and y(labels for each node)

edge,x,y = dataset[0]
numpyx = x[1].numpy()
numpyy = y[1].numpy()
numpyedge = edge[1].numpy()

import networkx as nx

g = nx.Graph(numpyx)

name,edgeinfo = edge

src = edgeinfo[0].numpy()
dst = edgeinfo[1].numpy()
edgelist = zip(src,dst)

for i,j in edgelist:
  g.add_edge(i,j) 

nx.draw_networkx(g)

Hi,
What is nx here? Is it networkx library?

Yes. My apologies. I’ve now modified the code to include the import line.

No problem, Good luck.

Actually… there’s an even better way. PyG has something in-built to convert the graph datasets to a networkx graph.

import networkx as nx
import torch
import numpy as np
import pandas as pd
from torch_geometric.datasets import Planetoid
from torch_geometric.utils.convert import to_networkx

dataset1 = Planetoid(root = '/content/cora',name='Cora')

cora = dataset1 [0]

coragraph = to_networkx(cora)

node_labels = cora.y[list(coragraph.nodes)].numpy()

import matplotlib.pyplot as plt
plt.figure(1,figsize=(14,12)) 
nx.draw(coragraph, cmap=plt.get_cmap('Set1'),node_color = node_labels,node_size=75,linewidths=6)
plt.show()

2 Likes