Master PyTorch Geometric Examples: Build Graph AI Faster

Kevin Jul 13, 2026

PyTorch Geometric, a popular library built upon PyTorch, has revolutionized the way we approach graph machine learning tasks. It bridges the gap between deep learning and graph neural networks (GNNs), providing a powerful and flexible tool for handling graph-structured data. If you're new to this domain, exploring PyTorch Geometric examples can significantly enhance your understanding and help you get started with this prolific library. Let's dive into some compelling examples and use cases.

Flat Design Posters
Flat Design Posters

Before we delve into the examples, let's briefly explore what sets PyTorch Geometric apart. Its key strengths lie in its easy-to-use API, seamless integration with PyTorch, and a comprehensive collection of GNN layers and models designed specifically for graph data. Now, let's look at some practical examples.

a stack of black and white lines on top of each other in the shape of a pyramid
a stack of black and white lines on top of each other in the shape of a pyramid

Graph Classification with PyTorch Geometric

Graph classification is a crucial task in graph machine learning, often requiring identifying if a graph belongs to a specific class or not. PyTorch Geometric offers various tools to tackle this challenge effectively.

Modern pyramid design stock vector. Illustration of shape - 13597165
Modern pyramid design stock vector. Illustration of shape - 13597165

To begin, let's consider a simple example using the famous Cora dataset, a citation network where nodes represent documents, and edges represent citation links. Our task is to predict the topic of each document (labelled as one of 'Case', 'Government', 'akter', 'Crime', 'Business', or ' médecine').

Creating a Graph Dataset

an object that is in the shape of a pyramid, with one point at the top
an object that is in the shape of a pyramid, with one point at the top

First, we need to create a PyTorch Geometric Dataset object for our Cora graph. We can use the built-in `Planetoid` dataset to load the graph, ads, and labels.

```python from torch_geometric.datasets import Planetoid dataset = Planetoid(root='data/Cora', name='Cora') graph = dataset[0] ```

Training a Graph Convolutional Network (GCN)

three pyramids are shown in black and white, each with one side facing the other
three pyramids are shown in black and white, each with one side facing the other

Now that we have our data, we can use a GCN, a popular GNN layer in PyTorch Geometric, to classify the graphs. First, let's define our model:

```python import torch from torch.nn import Linear from torch_geometric.nn import GCNConv, global_mean_pool class GCN(torch.nn.Module): def __init__(self, num_node_features, num_classes): super(GCN, self).__init__() torch.manual_seed(1234) self.conv1 = GCNConv(num_node_features, 16) self.conv2 = GCNConv(16, num_classes) def forward(self, data): x, edge_index, batch = data.x, data.edge_index, data.batch x = self.conv1(x, edge_index) x = torch.relu(x) x = self.conv2(x, edge_index) x = global_mean_pool(x, batch) return torch.softmax(x, dim=1) model = GCN(graph.num_features, dataset.num_classes) ```

The GCN model takes the node features, edge list, and batch information as inputs and outputs a softmax probability distribution over the classes. Now, let's train this model on our Cora dataset and evaluate its performance.

a black and white triangle with rays coming out of the center, on a dark background
a black and white triangle with rays coming out of the center, on a dark background

Learning Node Representations for Link Prediction

In this section, we'll explore how PyTorch Geometric can help us learn meaningful node representations for link prediction tasks. The idea here is to learn embeddings for nodes in a graph such that similar nodes are placed closer in the embedding space, making it easier to predict missing links.

Dominic Joyce Artworks | Saatchi Art
Dominic Joyce Artworks | Saatchi Art
Triangular pyramid geometric line art minimal shape design
Triangular pyramid geometric line art minimal shape design
an orange and yellow light shines in the center of a black background with triangular shapes
an orange and yellow light shines in the center of a black background with triangular shapes
Wireframe mesh Polygonal pyramid. Pyramid of the vector illustration
Wireframe mesh Polygonal pyramid. Pyramid of the vector illustration
ChatGPT - Pythagoras Visualizer
ChatGPT - Pythagoras Visualizer
an orange and red hexagonal object with lines going through it in the center
an orange and red hexagonal object with lines going through it in the center
a black and white drawing of a sunburst in the middle of it's rays
a black and white drawing of a sunburst in the middle of it's rays
an abstract background with lines and shapes in shades of orange, red, yellow and blue
an abstract background with lines and shapes in shades of orange, red, yellow and blue
an abstract triangle logo on a dark background
an abstract triangle logo on a dark background
an orange and brown geometric object on a white background
an orange and brown geometric object on a white background
Matthew Hughes (@tasty_plots) on X
Matthew Hughes (@tasty_plots) on X
Pinterest
Pinterest
ChatGPT - Pythagoras Visualizer
ChatGPT - Pythagoras Visualizer
an abstract red and yellow design on a white background
an abstract red and yellow design on a white background
an image of different types of geometric shapes
an image of different types of geometric shapes
Frustum Of Pentagonal Pyramid, vintage illustration.
Frustum Of Pentagonal Pyramid, vintage illustration.
Sharing with you all my passion. (: Thanks for your advises and opinions. - Awesome
Sharing with you all my passion. (: Thanks for your advises and opinions. - Awesome
an orange and yellow geometric object on a gray background
an orange and yellow geometric object on a gray background
an image of a geometric design with red and blue squares in the shape of a circle
an image of a geometric design with red and blue squares in the shape of a circle

To illustrate this, let's consider the well-known Cora graph classification task again. This time, instead of predicting the labels directly, we'll train an autoencoder to learn node representations and then use these embeddings for link prediction.

Learning Node Embeddings with a Variational Autoencoder (VAE)

PyTorch Geometric provides several layers to help us build our encoder and decoder. Let's define a simple VAE for learning node representations:

```python class VAE(torch.nn.Module): def __init__(self, num_node_features, embedding_dim): super(VAE, self).__init__() self.encoder = torch.nn.Sequential( gcn conv(num_node_features, embedding_dim), torch.nn.ReLU(), gcn conv(embedding_dim, embedding_dim * 2), torch.nn.ReLU(), torch.nn.Linear(embedding_dim * 2, embedding_dim) ) self.decoder = torch.nn.Sequential( gcn conv(embedding_dim, embedding_dim * 2), torch.nn.ReLU(), gcn conv(embedding_dim * 2, num_node_features), torch.nn.Sigmoid() ) def reparameterize(self, mu, logvar): std = torch.exp(0.5 * logvar) z = mu + std * torch.randn_like(std) return z def forward(self, data): x, edge_index, _ = data.x, data.edge_index, data.batch hidden = self.encoder(x, edge_index) mu, logvar = hiddenssa z = self.reparameterize(mu, logvar) recon_x = self.decoder(z, edge_index) return recon_x, z, mu, logvar model = VAE(graph.num_features, 128) ```

We train this VAE to minimize the reconstruction loss, i.e., the difference between the original node features and the reconstructed ones. After training, we obtain meaningful node embeddings in the latent space, which we can use for link prediction tasks.

To conclude, PyTorch Geometric offers a wealth of tools and functionalities for performing graph machine learning tasks. From graph classification to learning node representations, the library provides a solid foundation for building and testing graph neural network models. So, start exploring the library today, and enhance your graph machine learning journey with these engaging examples!