PyTorch Geometric (PyG)

2.7.0 · active · verified Sat Apr 11

PyTorch Geometric (PyG) is a library built upon PyTorch to easily write and train Graph Neural Networks (GNNs) for a wide range of applications related to structured data. It consists of various methods for deep learning on graphs and other irregular structures, providing easy-to-use mini-batch loaders, multi-GPU support, `torch.compile` support, a large number of common benchmark datasets, and helpful transforms. It is actively maintained with frequent minor releases delivering new features and bug fixes.

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a basic graph using PyTorch Geometric's `Data` object, which is the fundamental building block for representing graphs. It defines node features and graph connectivity (edges) and then prints basic properties of the created graph.

import torch
from torch_geometric.data import Data

# Define an edge list (COO format: [source_nodes, target_nodes])
edge_index = torch.tensor([[0, 1, 1, 2],
                           [1, 0, 2, 1]], dtype=torch.long)

# Define node features (3 nodes, 1 feature per node)
x = torch.tensor([[-1],
                  [0],
                  [1]], dtype=torch.float)

# Create a Data object to represent the graph
data = Data(x=x, edge_index=edge_index)

print(data)
print(f"Number of nodes: {data.num_nodes}")
print(f"Number of edges: {data.num_edges}")
print(f"Is undirected: {data.is_undirected()}")

view raw JSON →