Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Graph Neural Networks (GNNs) Using R
Next article icon

Graph Neural Networks with PyTorch

Last Updated : 02 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Graph Neural Networks (GNNs) represent a powerful class of machine learning models tailored for interpreting data described by graphs. This is particularly useful because many real-world structures are networks composed of interconnected elements, such as social networks, molecular structures, and communication systems. In this article, we will see how we can use Pytorch for building graph neural networks.

Implementation of a Simple GNN Model using PyTorch

Implementing Graph Neural Networks (GNNs) with the CORA dataset in PyTorch, specifically using PyTorch Geometric (PyG), involves several steps. Here's a guide through the process, including code snippets for each step.

Step 1: Loading the CORA Dataset

The CORA dataset is a citation graph where nodes represent documents, and edges represent citation links. Each document is classified into one of seven categories, making it a popular dataset for node classification tasks in GNNs.

First, ensure you have PyTorch Geometric installed. If not, you can install it using pip:

pip install torch-scatter torch-sparse torch-cluster torch-spline-conv torch-geometric

Then, load the CORA dataset:

import torch from torch_geometric.data import Planetoid import torch.nn.functional as F from torch_geometric.nn import GCNConv  # Loading the Cora dataset dataset = Planetoid(root='data/Planetoid', name='Cora')

Step 2: Defining a GNN Model Using PyTorch

We'll define a simple GNN model using one of the most straightforward types of GNN layers, the Graph Convolutional Network (GCN) layer, provided by PyTorch Geometric.

A custom Graph Neural Network (GNN) model is built using PyTorch's `torch.nn.Module` class. The model consists of two Graph Convolutional Network (GCN) layers, each followed by a Rectified Linear Unit (ReLU) activation function and dropout regularization. The model's `forward` method takes feature data and edge information as input, applies the defined layers sequentially, and outputs a log-softmax activation for classification. Additionally, an Adam optimizer is initialized to train the model with a specified learning rate and weight decay.

class CustomGNN(torch.nn.Module):     def __init__(self, input_dim, hidden_dim, output_dim):         super(CustomGNN, self).__init__()         self.layer1 = GCNConv(input_dim, hidden_dim)         self.layer2 = GCNConv(hidden_dim, output_dim)      def forward(self, feature_data, edge_info):         # First GCN layer         x = self.layer1(feature_data, edge_info)         x = F.relu(x)         x = F.dropout(x, p=0.5, training=self.training)         # Second GCN layer         x = self.layer2(x, edge_info)         return F.log_softmax(x, dim=1)  # Initialize the GNN model input_features = dataset.num_node_features num_classes = dataset.num_classes model = CustomGNN(input_features, 16, num_classes)  optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)  graph_data = dataset[0]  # Get the graph data

Step 3: Training the GNN Model on the CORA Dataset

Now, let's train the model. This involves initializing the model, defining the optimizer, and running the training loop.

def train_model():     model.train()     optimizer.zero_grad()     output = model(graph_data.x, graph_data.edge_index)     loss = F.nll_loss(output[graph_data.train_mask], graph_data.y[graph_data.train_mask])     loss.backward()     optimizer.step()     return loss.item()  for epoch in range(200):     loss_value = train_model()     print(f'Epoch: {epoch+1:03d}, Loss: {loss_value:.4f}') 

Step 4: Evaluating the Model's Performance

This code defines a basic GNN model, trains it on the CORA dataset, and evaluates its accuracy. The model architecture and training parameters are kept simple for demonstration purposes. In practice, you may want to experiment with deeper models, different types of GNN layers, and other optimization techniques to improve performance.

def evaluate_model():     model.eval()     with torch.no_grad():         predictions = model(graph_data.x, graph_data.edge_index).argmax(dim=1)         correct = (predictions[graph_data.test_mask] == graph_data.y[graph_data.test_mask]).sum()         acc = int(correct) / int(graph_data.test_mask.sum())     return acc  accuracy = evaluate_model() print(f'Test Accuracy: {accuracy:.4f}')

Complete Code to Implement Simple GNN using PyTorch

Python
!pip install torch-scatter torch-sparse torch-cluster torch-spline-conv torch-geometric  import torch from torch_geometric.data import Planetoid import torch.nn.functional as F from torch_geometric.nn import GCNConv  # Loading the Cora dataset dataset = Planetoid(root='data/Planetoid', name='Cora') dataset = Planetoid(root='/tmp/Cora', name='Cora')  import torch import torch.nn.functional as F from torch_geometric.nn import GCNConv  class CustomGNN(torch.nn.Module):     def __init__(self, input_dim, hidden_dim, output_dim):         super(CustomGNN, self).__init__()         self.layer1 = GCNConv(input_dim, hidden_dim)         self.layer2 = GCNConv(hidden_dim, output_dim)      def forward(self, feature_data, edge_info):         # First GCN layer         x = self.layer1(feature_data, edge_info)         x = F.relu(x)         x = F.dropout(x, p=0.5, training=self.training)         # Second GCN layer         x = self.layer2(x, edge_info)         return F.log_softmax(x, dim=1)  # Initialize the GNN model input_features = dataset.num_node_features num_classes = dataset.num_classes model = CustomGNN(input_features, 16, num_classes)  optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)  graph_data = dataset[0]  # Get the graph data  def train_model():     model.train()     optimizer.zero_grad()     output = model(graph_data.x, graph_data.edge_index)     loss = F.nll_loss(output[graph_data.train_mask], graph_data.y[graph_data.train_mask])     loss.backward()     optimizer.step()     return loss.item()  for epoch in range(200):     loss_value = train_model()     print(f'Epoch: {epoch+1:03d}, Loss: {loss_value:.4f}')  def evaluate_model():     model.eval()     with torch.no_grad():         predictions = model(graph_data.x, graph_data.edge_index).argmax(dim=1)         correct = (predictions[graph_data.test_mask] == graph_data.y[graph_data.test_mask]).sum()         acc = int(correct) / int(graph_data.test_mask.sum())     return acc  accuracy = evaluate_model() print(f'Test Accuracy: {accuracy:.4f}') 

Output:

Epoch: 1, Loss: 1.9575103521347046 Epoch: 2, Loss: 1.8464752435684204 Epoch: 3, Loss: 1.7240716218948364 ... Epoch: 197, Loss: 0.01653033308684826 Epoch: 198, Loss: 0.021068871021270752 Epoch: 199, Loss: 0.01990758441388607 Epoch: 200, Loss: 0.029717298224568367 Test Accuracy: 0.811

The output shows the loss value decreasing over 200 epochs of training a Graph Neural Network (GNN) on the CORA dataset, indicating that the model is learning to classify nodes more accurately over time. The final test accuracy of 0.811 demonstrates that the trained GNN model can correctly predict the class of over 81% of the nodes in the test set, showcasing its effectiveness in node classification tasks within graph-structured data.


Next Article
Graph Neural Networks (GNNs) Using R
author
moneeshnagireddy
Improve
Article Tags :
  • Deep Learning
  • AI-ML-DS
  • Neural Network
  • Python-PyTorch
  • AI-ML-DS With Python

Similar Reads

  • What are Graph Neural Networks?
    Graph Neural Networks (GNNs) are a neural network specifically designed to work with data represented as graphs. Unlike traditional neural networks, which operate on grid-like data structures like images (2D grids) or text (sequential), GNNs can model complex, non-Euclidean relationships in data, su
    13 min read
  • Graph Neural Networks (GNNs) Using R
    A specialized class of neural networks known as Graph Neural Networks (GNNs) has been developed to learn from such graph-structured data effectively. GNNs are designed to capture the dependencies between nodes in a graph through message passing between the nodes, making them powerful tools for tasks
    8 min read
  • How to Visualize PyTorch Neural Networks
    Visualizing neural networks is crucial for understanding their architecture, debugging, and optimizing models. PyTorch offers several ways to visualize both simple and complex neural networks. In this article, we'll explore how to visualize different types of neural networks, including a simple feed
    7 min read
  • Visualizing PyTorch Neural Networks
    Visualizing neural network models is a crucial step in understanding their architecture, debugging, and conveying their design. PyTorch, a popular deep learning framework, offers several tools and libraries that facilitate model visualization. This article will guide you through the process of visua
    4 min read
  • How to implement neural networks in PyTorch?
    This tutorial shows how to use PyTorch to create a basic neural network for classifying handwritten digits from the MNIST dataset. Neural networks, which are central to modern AI, enable machines to learn tasks like regression, classification, and generation. With PyTorch, you'll learn how to design
    5 min read
  • Training Neural Networks using Pytorch Lightning
    Introduction: PyTorch Lightning is a library that provides a high-level interface for PyTorch. Problem with PyTorch is that every time you start a project you have to rewrite those training and testing loop. PyTorch Lightning fixes the problem by not only reducing boilerplate code but also providing
    7 min read
  • Create Custom Neural Network in PyTorch
    PyTorch is a popular deep learning framework, empowers you to build and train powerful neural networks. But what if you need to go beyond the standard layers offered by the library? Here's where custom layers come in, allowing you to tailor the network architecture to your specific needs. This compr
    5 min read
  • Implementing Recurrent Neural Networks in PyTorch
    Recurrent Neural Networks (RNNs) are a class of neural networks that are particularly effective for sequential data. Unlike traditional feedforward neural networks RNNs have connections that form loops allowing them to maintain a hidden state that can capture information from previous inputs. This m
    6 min read
  • Training Neural Networks with Validation using PyTorch
    Neural Networks are a biologically-inspired programming paradigm that deep learning is built around. Python provides various libraries using which you can create and train neural networks over given data. PyTorch is one such library that provides us with various utilities to build and train neural n
    8 min read
  • Building a Convolutional Neural Network using PyTorch
    Convolutional Neural Networks (CNNs) are deep learning models used for image processing tasks. They automatically learn spatial hierarchies of features from images through convolutional, pooling and fully connected layers. In this article we'll learn how to build a CNN model using PyTorch. This incl
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences