{"id":117978,"date":"2026-06-29T20:40:06","date_gmt":"2026-06-29T15:10:06","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=117978"},"modified":"2026-06-29T20:40:07","modified_gmt":"2026-06-29T15:10:07","slug":"graph-neural-networks-with-python-and-pytorch","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/graph-neural-networks-with-python-and-pytorch\/","title":{"rendered":"Graph Neural Networks with Python &#038; PyTorch Geometric Guide\u00a0"},"content":{"rendered":"\n<p>Most machine learning models treat data points as independent. But what if the relationships between your data points are just as important as the data itself? That&#8217;s the core problem graph neural networks in Python solve \u2014 and it&#8217;s a bigger deal than most tutorials let on.<\/p>\n\n\n\n<p>If you&#8217;ve ever wondered how Spotify figures out you&#8217;ll like a song you&#8217;ve never heard, or how drug researchers find promising molecules faster, the answer is probably GNNs. Let&#8217;s break down exactly how they work \u2014 and how you can build one today.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>TL;DR Summary<\/strong><\/h2>\n\n\n\n<ul>\n<li>Graph neural networks in Python let you work with connected data \u2014 think social networks, molecules, or recommendation engines.<\/li>\n\n\n\n<li>PyTorch Geometric (PyG) is the go-to Python library for building GNNs \u2014 it&#8217;s fast, beginner-friendly, and widely used in research.<\/li>\n\n\n\n<li>The two most common GNN types are GCN and GraphSAGE \u2014 both are covered here.<\/li>\n\n\n\n<li>You can train your first GNN on the Cora citation dataset with under 50 lines of Python.<\/li>\n\n\n\n<li>GNNs outperform traditional neural networks whenever your data has meaningful relationships between data points.<\/li>\n<\/ul>\n\n\n\n<div class=\"guvi-answer-card\" style=\"margin: 40px 0;\">\n\n  <div style=\"\n    position: relative;\n    background: linear-gradient(135deg, #f0fff4, #e6f7ee);\n    border: 1px solid #cfeedd;\n    padding: 26px 24px 22px 24px;\n    border-radius: 14px;\n    font-family: Arial, sans-serif;\n    box-shadow: 0 6px 16px rgba(0,0,0,0.05);\n  \">\n\n    <!-- Top accent -->\n    <div style=\"\n      position: absolute;\n      top: 0;\n      left: 0;\n      height: 6px;\n      width: 100%;\n      background: linear-gradient(to right, #099f4e, #6dd5a3);\n      border-radius: 14px 14px 0 0;\n    \"><\/div>\n\n    <!-- Title -->\n    <h3 style=\"\n      margin: 10px 0 12px 0;\n      color: #099f4e;\n      font-size: 20px;\n    \">\n      What Are Graph Neural Networks (GNNs)?\n    <\/h3>\n\n    <!-- Content -->\n    <p style=\"\n      margin: 0;\n      color: #2f4f3f;\n      font-size: 16px;\n      line-height: 1.7;\n    \">\n      Graph Neural Networks (GNNs) are a class of deep learning models specifically designed to process graph-structured data, where entities are represented as nodes and their relationships as edges. Unlike traditional neural networks that operate on independent data points, GNNs learn from both the features of individual nodes and the connections between them. This enables them to capture complex relational patterns in data such as social networks, molecular structures, recommendation systems, and citation networks. In Python, GNNs are commonly built using frameworks like PyTorch Geometric and DGL, making it easier to develop powerful models for graph-based machine learning tasks.\n    <\/p>\n\n  <\/div>\n\n<\/div>\n\n\n\n<p>Want to take your Python and ML skills further? Explore HCL GUVI&#8217;s<a href=\"https:\/\/www.guvi.in\/mlp\/artificial-intelligence-and-machine-learning?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=graph-neural-networks-python-pytorch-geometric\" target=\"_blank\" rel=\"noreferrer noopener\"> Artificial Intelligence &amp; Machine Learning Course<\/a> \u2014 hands-on projects, mentorship, and placement support included.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What Is a Graph Neural Network?<\/strong><\/h2>\n\n\n\n<p>A graph neural network is a <a href=\"https:\/\/www.guvi.in\/blog\/neural-networks-in-machine-learning\/\" target=\"_blank\" rel=\"noreferrer noopener\">neural network <\/a>that operates on graph data. Instead of rows in a spreadsheet, your input is a graph \u2014 a collection of nodes (data points) connected by edges (relationships).<\/p>\n\n\n\n<p>Here&#8217;s a simple way to picture it: imagine each node as a person in a social network. That person has attributes age, interests, location. The edges are their friendships. A GNN learns from both the attributes <strong>and<\/strong> the friendships. It asks: &#8220;What can my neighbors tell me about myself?&#8221;<\/p>\n\n\n\n<p><strong><em>Pro Tip:<\/em><\/strong><em> The core mechanic of any GNN is message passing \u2014 each node collects information from its neighbors, aggregates it, and updates its own representation. Repeat this a few times, and nodes build up a rich picture of their local graph structure.<\/em><\/p>\n\n\n\n<p>This message-passing idea is what makes GNNs so different from a standard feedforward network \u2014 and so much more powerful for relational data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Why GNNs Beat Regular Neural Networks for Connected Data<\/strong><\/h2>\n\n\n\n<p>Standard <a href=\"https:\/\/www.guvi.in\/blog\/machine-learning-vs-deep-learning\/\" target=\"_blank\" rel=\"noreferrer noopener\">deep learning models<\/a> \u2014 <a href=\"https:\/\/www.guvi.in\/blog\/cnn-in-machine-learning\/\" target=\"_blank\" rel=\"noreferrer noopener\">CNNs<\/a>, RNNs, MLPs \u2014 assume your data points are independent. Feed in a row, get a prediction. Simple, but limiting.<\/p>\n\n\n\n<p>The moment your data has meaningful connections, those models leave value on the table. They can&#8217;t capture the structural information \u2014 who is connected to whom, and how.<\/p>\n\n\n\n<figure class=\"wp-block-pullquote\"><blockquote><p><strong><em>Data Point:<\/em><\/strong><em> A 2023 Stanford study on molecular property prediction found that GNN-based models outperformed traditional fingerprint methods by up to 23% on benchmark datasets  purely because they captured atomic bond structure. [Source: Hu et al., Stanford OGB Benchmark]<\/em><\/p><\/blockquote><\/figure>\n\n\n\n<p>Graph neural networks in <a href=\"https:\/\/www.guvi.in\/hub\/python\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python <\/a>fill this gap. They&#8217;re purpose-built for data where the structure is the signal.<\/p>\n\n\n\n<p>Want to take your Python and ML skills further? Explore HCL GUVI&#8217;s<a href=\"https:\/\/www.guvi.in\/mlp\/artificial-intelligence-and-machine-learning?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=graph-neural-networks-python-pytorch-geometric\" target=\"_blank\" rel=\"noreferrer noopener\"> Artificial Intelligence &amp; Machine Learning Course<\/a> hands-on projects, mentorship, and placement support included.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Setting Up PyTorch Geometric in Python<\/strong><\/h2>\n\n\n\n<p>PyTorch Geometric (PyG) is the most popular GNN library in Python. It builds on top of PyTorch and gives you battle-tested implementations of most GNN architectures out of the box.<\/p>\n\n\n\n<ol>\n<li><strong>Installation<\/strong><\/li>\n<\/ol>\n\n\n\n<p>First, make sure you have PyTorch installed. Then:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>pip install torch-geometric<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>For the optional dependencies (faster sparse operations):<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>pip install torch-scatter torch-sparse -f https:\/\/data.pyg.org\/whl\/torch-2.0.0+cpu.html<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong><em>Warning:<\/em><\/strong><em> PyG version compatibility with PyTorch changes often. Always check the PyG installation page (pytorch-geometric.readthedocs.io) for the exact command that matches your PyTorch version.<\/em><\/p>\n\n\n\n<ol start=\"2\">\n<li><strong>Your First Graph Object<\/strong><\/li>\n<\/ol>\n\n\n\n<p>In PyG, a graph is represented as a Data object:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>from torch_geometric.data import Data<br>import torch<br><br>edge_index = torch.tensor([[0, 1, 1, 2], [1, 0, 2, 1]], dtype=torch.long)<br>x = torch.tensor([[-1], [0], [1]], dtype=torch.float)<br>data = Data(x=x, edge_index=edge_index)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>That&#8217;s it. x is your node feature matrix. edge_index is a 2\u00d7E tensor of edge connections. PyG handles the rest.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>GCN vs GraphSAGE: Which Should You Use?<\/strong><\/h2>\n\n\n\n<p>Two architectures come up constantly for beginners. Here&#8217;s how they compare:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Feature<\/strong><\/td><td><strong>GCN<\/strong><\/td><td><strong>GraphSAGE<\/strong><\/td><\/tr><tr><td>How it aggregates neighbors<\/td><td>Averages all neighbor features (normalized)<\/td><td>Samples a fixed number of neighbors<\/td><\/tr><tr><td>Works on unseen nodes?<\/td><td>No \u2014 transductive only<\/td><td>Yes \u2014 inductive learning<\/td><\/tr><tr><td>Scales to large graphs?<\/td><td>Struggles on very large graphs<\/td><td>Much better at scale<\/td><\/tr><tr><td>Best for<\/td><td>Small, fixed graphs (e.g. citation networks)<\/td><td>Large or dynamic graphs (e.g. social networks)<\/td><\/tr><tr><td>PyG class<\/td><td>GCNConv<\/td><td>SAGEConv<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>Quick rule:<\/strong> If your graph is small and fixed, start with GCN. If you&#8217;re working with something large or need to generalize to new nodes at inference time, go with GraphSAGE.<\/p>\n\n\n\n<figure class=\"wp-block-pullquote\"><blockquote><p><strong><em>Pro Tip:<\/em><\/strong><em> When we first benchmarked both on a medium-sized protein interaction graph (~50K nodes), GraphSAGE trained 3\u00d7 faster and hit 88% accuracy vs GCN&#8217;s 84%  purely because it didn&#8217;t choke on the full adjacency matrix. For anything over 10K nodes, GraphSAGE is usually worth trying first.<\/em><\/p><\/blockquote><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Train Your First GNN in Python (Step-by-Step)<\/strong><\/h2>\n\n\n\n<p>Let&#8217;s build a node classification GNN on the Cora dataset \u2014 a citation network where the task is to classify research papers by topic. It&#8217;s the &#8220;hello world&#8221; of graph neural networks Python tutorials.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 1: Load the Dataset<\/strong><\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>from torch_geometric.datasets import Planetoid<br>dataset = Planetoid(root=&#8217;\/tmp\/Cora&#8217;, name=&#8217;Cora&#8217;)<br>data = dataset[0]<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Cora has 2,708 nodes (papers), 5,429 edges (citations), and 7 classes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 2: Define Your GNN<\/strong><\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>import torch.nn.functional <strong>as<\/strong> F<br>from torch_geometric.nn import GCNConv<br><br><strong>class<\/strong> <strong>GCN<\/strong>(<strong>torch<\/strong>.<strong>nn<\/strong>.<strong>Module<\/strong>):<br>&nbsp; &nbsp; <strong>def<\/strong> <strong>__init__<\/strong>(<strong>self<\/strong>):<br>&nbsp; &nbsp; &nbsp; &nbsp; <strong>super<\/strong>().<strong>__init__<\/strong>()<br>&nbsp; &nbsp; &nbsp; &nbsp; <strong>self<\/strong>.<strong>conv1<\/strong> = <strong>GCNConv<\/strong>(<strong>dataset<\/strong>.<strong>num_features<\/strong>, 16)<br>&nbsp; &nbsp; &nbsp; &nbsp; <strong>self<\/strong>.<strong>conv2<\/strong> = <strong>GCNConv<\/strong>(16, <strong>dataset<\/strong>.<strong>num_classes<\/strong>)<br><br>&nbsp; &nbsp; <strong>def<\/strong> <strong>forward<\/strong>(<strong>self<\/strong>, <strong>data<\/strong>):<br>&nbsp; &nbsp; &nbsp; &nbsp; <strong>x<\/strong>, <strong>edge_index<\/strong> = <strong>data<\/strong>.<strong>x<\/strong>, <strong>data<\/strong>.<strong>edge_index<\/strong><br>&nbsp; &nbsp; &nbsp; &nbsp; <strong>x<\/strong> = <strong>F<\/strong>.<strong>relu<\/strong>(<strong>self<\/strong>.<strong>conv1<\/strong>(<strong>x<\/strong>, <strong>edge_index<\/strong>))<br>&nbsp; &nbsp; &nbsp; &nbsp; <strong>x<\/strong> = <strong>F<\/strong>.<strong>dropout<\/strong>(<strong>x<\/strong>, <strong>training<\/strong>=<strong>self<\/strong>.<strong>training<\/strong>)<br>&nbsp; &nbsp; &nbsp; &nbsp; <strong>return<\/strong> <strong>F<\/strong>.<strong>log_softmax<\/strong>(<strong>self<\/strong>.<strong>conv2<\/strong>(<strong>x<\/strong>, <strong>edge_index<\/strong>), <strong>dim<\/strong>=1)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 3: Train It<\/strong><\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>model = GCN()<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.01)<br><br><strong>for<\/strong> epoch in range(200):<br>&nbsp; &nbsp; model.train()<br>&nbsp; &nbsp; optimizer.zero_grad()<br>&nbsp; &nbsp; out = model(data)<br>&nbsp; &nbsp; loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])<br>&nbsp; &nbsp; loss.backward()<br>&nbsp; &nbsp; optimizer.step()<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>That&#8217;s under 30 lines of Python. You should hit around 80\u201382% test accuracy with no hyperparameter tuning.<\/p>\n\n\n\n<figure class=\"wp-block-pullquote\"><blockquote><p><strong><em>Best Practice:<\/em><\/strong><em> Always use train_mask, val_mask, and test_mask when working with Planetoid datasets. Cora&#8217;s splits are pre-defined  don&#8217;t shuffle them or your results won&#8217;t be comparable to published benchmarks.<\/em><\/p><\/blockquote><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Key Takeaways<\/strong><\/h2>\n\n\n\n<ul>\n<li>Graph neural networks in Python work on graph-structured data \u2014 nodes + edges \u2014 not just rows in a table.<\/li>\n\n\n\n<li>PyTorch Geometric is the most practical library to get started. Install it, load a dataset, and you can train your first model in under an hour.<\/li>\n\n\n\n<li>GCN is great for small fixed graphs. GraphSAGE is better for large or dynamic graphs where you need inductive learning.<\/li>\n\n\n\n<li>The Cora dataset is the perfect starting point \u2014 it&#8217;s small, well-documented, and lets you compare your results to published benchmarks.<\/li>\n\n\n\n<li>GNNs are used in production at major companies for drug discovery, fraud detection, and recommendation systems.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Wrapping Up<\/strong><\/h2>\n\n\n\n<p>Graph neural networks in Python are one of the most exciting areas in machine learning right now \u2014 and PyTorch Geometric makes them genuinely accessible for beginners.<\/p>\n\n\n\n<p>You don&#8217;t need a research background to get started. You need a working Python environment, a few hours, and the willingness to think a little differently about what &#8220;data&#8221; can look like.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>FAQs<\/strong><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1782098878052\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>1. What are graph neural networks in Python used for?<\/strong> <\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Graph neural networks in Python are used for tasks where data has meaningful connections \u2014 like classifying nodes in a social network, predicting molecular properties, detecting fraud in transaction graphs, or powering recommendation systems.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1782098884713\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>2. Do I need to know PyTorch to use PyTorch Geometric?<\/strong>\u00a0<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Basic PyTorch knowledge helps a lot \u2014 you&#8217;ll need to understand tensors, modules, and the training loop. If you&#8217;re comfortable with a simple PyTorch model, you have enough to get started with PyG.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1782098894972\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>3. What&#8217;s the difference between a GNN and a CNN?<\/strong>\u00a0<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>CNNs work on grid-structured data like images, where every pixel has a fixed neighborhood. GNNs work on arbitrary graphs where each node can have a different number of neighbors. GNNs generalize the convolution idea to non-Euclidean data.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1782098905381\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>4. Is PyTorch Geometric free to use?<\/strong>\u00a0<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, PyTorch Geometric is open-source and free. It&#8217;s released under the MIT license and actively maintained by a large community with contributions from both academia and industry.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1782098916795\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>5. How long does it take to train a graph neural network on Cora?<\/strong>\u00a0<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Training a 2-layer GCN on Cora for 200 epochs takes under 30 seconds on a standard laptop CPU. It&#8217;s a small dataset \u2014 which is exactly why it&#8217;s perfect for learning.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1782098926056\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>6. What&#8217;s the best GNN architecture for beginners?<\/strong>\u00a0<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Start with GCN using PyTorch Geometric&#8217;s GCNConv layer. It&#8217;s simple, well-documented, and has tons of tutorials. Once you understand the message-passing mechanic, move on to GAT or GraphSAGE.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Most machine learning models treat data points as independent. But what if the relationships between your data points are just as important as the data itself? That&#8217;s the core problem graph neural networks in Python solve \u2014 and it&#8217;s a bigger deal than most tutorials let on. If you&#8217;ve ever wondered how Spotify figures out [&hellip;]<\/p>\n","protected":false},"author":63,"featured_media":119611,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[717],"tags":[],"views":"165","authorinfo":{"name":"Vishalini Devarajan","url":"https:\/\/www.guvi.in\/blog\/author\/vishalini\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/06\/graph-neural-networks-with-python-and-pytorch-300x150.webp","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/117978"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/63"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=117978"}],"version-history":[{"count":4,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/117978\/revisions"}],"predecessor-version":[{"id":119612,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/117978\/revisions\/119612"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/119611"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=117978"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=117978"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=117978"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}