{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Maxime Labonne",
  "title_listed": "Graph Convolutional Networks: Introduction to GNNs",
  "keywords": "GNN,图神经网络,PyTorch Geometric",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "部分免费/会员墙",
  "url": "https://towardsdatascience.com/graph-convolutional-networks-introduction-to-gnns-24b3f60d6c95/",
  "publish_date": "2023-08",
  "corpus_stage": "预训练/SFT",
  "notes": "",
  "id": "83deaecba8a3",
  "collected_at": "2026-10-01T21:53:55",
  "title": "Graph Convolutional Networks: Introduction to GNNs | Towards Data Science",
  "body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Graph Convolutional Networks: Introduction to GNNs\nA step-by-step guide using PyTorch Geometric\n[Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\nAugust 14, 202317 min read\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1X4I4_PO9l14apt0h3Nbw2A.jpeg)\nImage by author\n**Graph Neural Networks** (GNNs) represent one of the most captivating and rapidly evolving architectures within the deep learning landscape. As deep learning models designed to process data structured as graphs, GNNs bring remarkable versatility and powerful learning capabilities.\nAmong the various types of GNNs, the **Graph Convolutional Networks** (GCNs) have emerged as the most [prevalent and broadly applied model](https://paperswithcode.com/methods/category/graph-models). GCNs are innovative due to their ability to leverage both the features of a node and its locality to make predictions, providing an effective way to handle graph-structured data.\nIn this article, we will delve into the mechanics of the GCN layer and explain its inner workings. Furthermore, we will explore its practical application for node classification tasks, using [PyTorch Geometric](https://pytorch-geometric.readthedocs.io/en/latest/index.html) as our tool of choice.\n[PyTorch](https://pytorch.org/get-started/locally/) Geometric is a specialized extension of PyTorch that has been created specifically for the development and implementation of GNNs. It is an advanced, yet user-friendly library that provides a comprehensive suite of tools to facilitate graph-based machine learning. To commence our journey, the PyTorch Geometric installation will be required. If you are using Google Colab, PyTorch should already be in place, so all we need to do is execute a few additional commands.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist), [Computer Science](https://roadmap.sh/computer-science) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\nAll the code is available on [Google Colab](https://colab.research.google.com/drive/1ZugveUjRrbSNwUbryeKJN2wyhGFRCw0q?usp=sharing) and [GitHub](https://github.com/mlabonne/graph-neural-network-course).\npython\n\n```\n!pip install torch_geometric\n```\n\ntext\n\n```\nimport torch\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\n```\n\nNow that PyTorch Geometric is installed, let's explore the dataset we will use in this tutorial.\n## 🌐 I. Graph data\n[Graphs](https://en.wikipedia.org/wiki/Graph_\\(discrete_mathematics\\)) are an essential structure for representing relationships between objects. You can encounter graph data in a multitude of real-world scenarios, such as social and computer networks, chemical structures of molecules, natural language processing, and image recognition, to name a few.\nIn this article, we will study the infamous and much-used [Zachary's karate club](https://en.wikipedia.org/wiki/Zachary%27s_karate_club) dataset.\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1gPUxh53IHnS0lnnks8_L3Q.png)\nImage by author\nThe Zachary's karate club dataset embodies the relationships formed within a karate club as observed by Wayne W. Zachary during the 1970s. It is a kind of social network, where each node represents a club member, and edges between nodes represent interactions that occurred outside the club environment.\nIn this particular scenario, the members of the club are split into four distinct groups. Our task is to **assign the correct group to each member** (node classification), based on the pattern of their interactions.\nLet's import the dataset with PyG's built-in function and try to understand the `Datasets` object it uses.\njavascript\n\n```\nfrom torch_geometric.datasets import KarateClub\n```\n\ntext\n\n```\n# Import dataset from PyTorch Geometric\ndataset = KarateClub()\n```\n\ntext\n\n```\n# Print information\nprint(dataset)\nprint('------------')\nprint(f'Number of graphs: {len(dataset)}')\nprint(f'Number of features: {dataset.num_features}')\nprint(f'Number of classes: {dataset.num_classes}')\n```\n\ntext\n\n```\nKarateClub()\n------------\nNumber of graphs: 1\nNumber of features: 34\nNumber of classes: 4\n```\n\nThis dataset only has 1 graph, where each node has a feature vector of 34 dimensions and is part of one out of four classes (our four groups). Actually, the `Datasets` object can be seen as a collection of `Data` (graph) objects.\nWe can further inspect our unique graph to know more about it.\npython\n\n```\n# Print first element\nprint(f'Graph: {dataset[0]}')\n```\n\ncss\n\n```\nGraph: Data(x=[34, 34], edge_index=[2, 156], y=[34], train_mask=[34])\n```\n\nThe `[Data](https://pytorch-geometric.readthedocs.io/en/latest/modules/data.html)` object is particularly interesting. Printing it offers a good summary of the graph we're studying:\n  * `x=[34, 34]` is the **node feature matrix** with shape (number of nodes, number of features). In our case, it means that we have 34 nodes (our 34 members), each node being associated to a 34-dim feature vector.\n  * `edge_index=[2, 156]` represents the **graph connectivity** (how the nodes are connected) with shape (2, number of directed edges).\n  * `y=[34]` is the **node ground-truth labels**. In this problem, every node is assigned to one class (group), so we have one value for each node.\n  * `train_mask=[34]` is an optional attribute that tells which nodes should be used for training with a list of `True` or `False` statements.\n\n\nLet's print each of these tensors to understand what they store. Let's start with the node features.\nini\n\n```\ndata = dataset[0]\n```\n\ntext\n\n```\nprint(f'x = {data.x.shape}')\nprint(data.x)\n```\n\ntext\n\n```\nx = torch.Size([34, 34])\ntensor([[1., 0., 0.,  ..., 0., 0., 0.],\n        [0., 1., 0.,  ..., 0., 0., 0.],\n        [0., 0., 1.,  ..., 0., 0., 0.],\n        ...,\n        [0., 0., 0.,  ..., 1., 0., 0.],\n        [0., 0., 0.,  ..., 0., 1., 0.],\n        [0., 0., 0.,  ..., 0., 0., 1.]])\n```\n\nHere, the node feature matrix `x` is an identity matrix: it **doesn't contain any relevant information** about the nodes. It could contain information like age, skill level, etc. but this is not the case in this dataset. It means we'll have to classify our nodes just by looking at their connections.\nNow, let's print the edge index.\npython\n\n```\nprint(f'edge_index = {data.edge_index.shape}')\nprint(data.edge_index)\n```\n\ntext\n\n```\nedge_index = torch.Size([2, 156])\ntensor([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,\n          1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,\n          3,  3,  3,  3,  3,  4,  4,  4,  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,\n          7,  7,  8,  8,  8,  8,  8,  9,  9, 10, 10, 10, 11, 12, 12, 13, 13, 13,\n         13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19, 20, 20, 21,\n         21, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 27, 27,\n         27, 27, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31, 31,\n         31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33,\n         33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33],\n        [ 1,  2,  3,  4,  5,  6,  7,  8, 10, 11, 12, 13, 17, 19, 21, 31,  0,  2,\n          3,  7, 13, 17, 19, 21, 30,  0,  1,  3,  7,  8,  9, 13, 27, 28, 32,  0,\n          1,  2,  7, 12, 13,  0,  6, 10,  0,  6, 10, 16,  0,  4,  5, 16,  0,  1,\n          2,  3,  0,  2, 30, 32, 33,  2, 33,  0,  4,  5,  0,  0,  3,  0,  1,  2,\n          3, 33, 32, 33, 32, 33,  5,  6,  0,  1, 32, 33,  0,  1, 33, 32, 33,  0,\n          1, 32, 33, 25, 27, 29, 32, 33, 25, 27, 31, 23, 24, 31, 29, 33,  2, 23,\n         24, 33,  2, 31, 33, 23, 26, 32, 33,  1,  8, 32, 33,  0, 24, 25, 28, 32,\n         33,  2,  8, 14, 15, 18, 20, 22, 23, 29, 30, 31, 33,  8,  9, 13, 14, 15,\n         18, 19, 20, 22, 23, 26, 27, 28, 29, 30, 31, 32]])\n```\n\nIn graph theory and network analysis, connectivity between nodes is stored using a variety of data structures. The `edge_index` is one such data structure, where the graph's connections are stored in **two lists** (156 directed edges, which equate to 78 bidirectional edges). The reason for these two lists is that one list stores the source nodes, while the second one identifies the destination nodes.\nThis method is known as a **coordinate list** (COO) format, which is essentially a means to efficiently store a [sparse matrix](https://en.wikipedia.org/wiki/Sparse_matrix#Storing_a_sparse_matrix). Sparse matrices are data structures that efficiently store matrices with a majority of zero elements. In the COO format, only non-zero elements are stored, saving memory and computational resources.\nContrarily, a more intuitive and straightforward way to represent graph connectivity is through an **adjacency matrix** _A_. This is a square matrix where each element _A_ᵢⱼ _s_pecifies the presence or absence of an edge from node _i_ to node _j_ in the graph. In other words, a non-zero element _A_ᵢⱼ implies a connection from node _i_ to node _j_ , and a zero indicates no direct connection.\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1CjPY3V96hZ647kb38hVaNg.png)\nImage by author\nAn adjacency matrix, however, is not as space-efficient as the COO format for sparse matrices or graphs with fewer edges. However, for clarity and easy interpretation, the adjacency matrix remains a popular choice for representing graph connectivity.\nThe adjacency matrix can be inferred from the `edge_index` with a utility function `to_dense_adj()`.\njavascript\n\n```\nfrom torch_geometric.utils import to_dense_adj\n```\n\ntext\n\n```\nA = to_dense_adj(data.edge_index)[0].numpy().astype(int)\nprint(f'A = {A.shape}')\nprint(A)\n```\n\ntext\n\n```\nA = (34, 34)\n[[0 1 1 ... 1 0 0]\n [1 0 1 ... 0 0 0]\n [1 1 0 ... 0 1 0]\n ...\n [1 0 0 ... 0 1 1]\n [0 0 1 ... 1 0 1]\n [0 0 0 ... 1 1 0]]\n```\n\nWith graph data, it is relatively uncommon for nodes to be densely interconnected. As you can see, our adjacency matrix _A_ is **sparse** (filled with zeros).\nIn many real-world graphs, most nodes are connected to only a few other nodes, resulting in a large number of zeros in the adjacency matrix. Storing so many zeros is not efficient at all, which is why the COO format is adopted by PyG.\nOn the contrary, ground-truth labels are easy to understand.\npython\n\n```\nprint(f'y = {data.y.shape}')\nprint(data.y)\n```\n\ntext\n\n```\ny = torch.Size([34])\ntensor([1, 1, 1, 1, 3, 3, 3, 1, 0, 1, 3, 1, 1, 1, 0, 0, 3, 1, 0, 1, 0, 1, 0, 0,\n        2, 2, 0, 0, 2, 0, 0, 2, 0, 0])\n```\n\nOur node ground-truth labels stored in `y` simply encode the group number (0, 1, 2, 3) for each node, which is why we have 34 values.\nFinally, let's print the train mask.\npython\n\n```\nprint(f'train_mask = {data.train_mask.shape}')\nprint(data.train_mask)\n```\n\ntext\n\n```\ntrain_mask = torch.Size([34])\ntensor([ True, False, False, False,  True, False, False, False,  True, False,\n        False, False, False, False, False, False, False, False, False, False,\n        False, False, False, False,  True, False, False, False, False, False,\n        False, False, False, False])\n```\n\nThe train mask shows which nodes are supposed to be used for training with `True` statements. These nodes represent the training set, while the others can be considered as the test set. This division helps in model evaluation by providing unseen data for testing.\nBut we're not done yet! The `[Data](https://pytorch-geometric.readthedocs.io/en/latest/modules/data.html)` object has a lot more to offer. It provides various utility functions that enable the investigation of several properties of the graph. For instance:\n  * `is_directed()` tells you if the graph is **directed**. A directed graph signifies that the adjacency matrix is not symmetric, i.e., the direction of edges matters in the connections between nodes.\n  * `isolated_nodes()` checks if some nodes are **not connected** to the rest of the graph. These nodes are likely to pose challenges in tasks like classification due to their lack of connections.\n  * `has_self_[loops](https://en.wikipedia.org/wiki/Loop_(graph_theory))()` indicates if at least one node is **connected to itself**. This is distinct from the concept of loops: a loop implies a path that starts and ends at the same node, traversing other nodes in between.\n\n\nIn the context of the Zachary's karate club dataset, all these properties return `False`. This implies that the graph is not directed, does not have any isolated nodes, and none of its nodes are connected to themselves.\npython\n\n```\nprint(f'Edges are directed: {data.is_directed()}')\nprint(f'Graph has isolated nodes: {data.has_isolated_nodes()}')\nprint(f'Graph has loops: {data.has_self_loops()}')\n```\n\ntext\n\n```\nEdges are directed: False\nGraph has isolated nodes: False\nGraph has loops: False\n```\n\nFinally, we can convert a graph from PyTorch Geometric to the popular graph library [NetworkX](https://networkx.org/) using `[to_networkx](https://pytorch-geometric.readthedocs.io/en/latest/modules/utils.html?highlight=to_networkx#torch_geometric.utils.to_networkx)`. This is particularly useful to visualize a small graph with `networkx` and `matplotlib`.\nLet's plot our dataset with a different color for each group.\njavascript\n\n```\nfrom torch_geometric.utils import to_networkx\n```\n\ntext\n\n```\nG = to_networkx(data, to_undirected=True)\nplt.figure(figsize=(12,12))\nplt.axis('off')\nnx.draw_networkx(G,\n                pos=nx.spring_layout(G, seed=0),\n                with_labels=True,\n                node_size=800,\n                node_color=data.y,\n                cmap=\"hsv\",\n                vmin=-2,\n                vmax=3,\n                width=0.8,\n                edge_color=\"grey\",\n                font_size=14\n                )\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1hPouqFUjF4BwzTJeJWyNvQ.png)\nThis plot of Zachary's karate club displays our 34 nodes, 78 (bidirectional) edges, and 4 labels with 4 different colors. Now that we've seen the essentials of loading and handling a dataset with PyTorch Geometric, we can introduce the **Graph Convolutional Network** architecture.\n## ✉️ II. Graph Convolutional Network\nThis section aims to introduce and build the graph convolutional layer from the ground up.\nIn traditional neural networks, linear layers apply a **linear transformation** to the incoming data. This transformation converts input features _x_ into hidden vectors _h_ through the use of a weight matrix 𝐖. Ignoring biases for the time being, this can be expressed as:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1oJzwGLdNLaJrjA-bufR-BQ.png)\nWith graph data, an additional layer of complexity is added through the **connections between nodes**. These connections matter because, typically, in networks, it's assumed that similar nodes are more likely to be linked to each other than dissimilar ones, a phenomenon known as [network homophily](https://en.wikipedia.org/wiki/Network_homophily).\nWe can enrich our **node representation** by merging its features with those of its neighbors. This operation is called convolution, or neighborhood aggregation. Let's represent the neighborhood of node _i_ including itself as _Ñ_.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1fiqRdbHBbKeqoS49B6ruyg.png)\nUnlike filters in Convolutional Neural Networks (CNNs), our weight matrix 𝐖 is unique and shared among every node. But there is another issue: nodes do not have a f**ixed number of neighbors** like pixels do.\nHow do we address cases where one node has only one neighbor, and another has 500? If we simply sum the feature vectors, the resulting embedding _h_ would be much larger for the node with 500 neighbors. To ensure a **similar range** of values for all nodes and comparability between them, we can normalize the result based on the **degree** of nodes, where degree refers to the number of connections a node has.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/17uGB3skMU0d5qGLrCd70MA.png)\nWe're almost there! Introduced by Kipf et al. (2016), the [graph convolutional layer](https://arxiv.org/abs/1609.02907) has one final improvement.\nThe authors observed that features from nodes with numerous neighbors propagate much more easily than those from more isolated nodes. To offset this effect, they suggested assigning **bigger weights** to features from nodes with fewer neighbors, thus balancing the influence across all nodes. This operation is written as:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1BNyzJMlREISPhvrKn39Ptw.png)\nNote that when _i_ and _j_ have the same number of neighbors, it is equivalent to our own layer. Now, let's see how to implement it in Python with PyTorch Geometric.\n## 🧠 III. Implementing a GCN\nPyTorch Geometric provides the `GCNConv` function, which directly implements the graph convolutional layer.\nIn this example, we'll create a basic Graph Convolutional Network with a single GCN layer, a ReLU activation function, and a linear output layer. This output layer will yield **four values** corresponding to our four categories, with the highest value determining the class of each node.\nIn the following code block, we define the GCN layer with a 3-dimensional hidden layer.\njavascript\n\n```\nfrom torch.nn import Linear\nfrom torch_geometric.nn import GCNConv\n\n```\n\ntext\n\n```\nclass GCN(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.gcn = GCNConv(dataset.num_features, 3)\n        self.out = Linear(3, dataset.num_classes)\n```\n\ntext\n\n```\n    def forward(self, x, edge_index):\n        h = self.gcn(x, edge_index).relu()\n        z = self.out(h)\n        return h, z\n```\n\ntext\n\n```\nmodel = GCN()\nprint(model)\n```\n\ntext\n\n```\nGCN(\n  (gcn): GCNConv(34, 3)\n  (out): Linear(in_features=3, out_features=4, bias=True)\n)\n```\n\nIf we added a second GCN layer, our model would not only aggregate feature vectors from the neighbors of each node, but also from the neighbors of these neighbors.\nWe can **stack several graph layers** to aggregate more and more distant values, but there's a catch: if we add too many layers, the aggregation becomes so intense that all the embeddings end up looking the same. This phenomenon is called **over-smoothing** and can be a real problem when you have too many layers.\nNow that we've defined our GNN, let's write a simple training loop with PyTorch. I chose a regular cross-entropy loss since it's a multi-class classification task, with Adam as optimizer. In this article, we won't implement a train/test split to keep things simple and focus on how GNNs learn instead.\nThe training loop is standard: we try to predict the correct labels, and we compare the GCN's results to the values stored in `data.y`. The error is calculated by the cross-entropy loss and backpropagated with Adam to fine-tune our GNN's weights and biases. Finally, we print metrics every 10 epochs.\nini\n\n```\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.02)\n```\n\ntext\n\n```\n# Calculate accuracy\ndef accuracy(pred_y, y):\n    return (pred_y == y).sum() / len(y)\n```\n\ntext\n\n```\n# Data for animations\nembeddings = []\nlosses = []\naccuracies = []\noutputs = []\n```\n\ntext\n\n```\n# Training loop\nfor epoch in range(201):\n    # Clear gradients\n    optimizer.zero_grad()\n```\n\ntext\n\n```\n    # Forward pass\n    h, z = model(data.x, data.edge_index)\n```\n\ntext\n\n```\n    # Calculate loss function\n    loss = criterion(z, data.y)\n```\n\ntext\n\n```\n    # Calculate accuracy\n    acc = accuracy(z.argmax(dim=1), data.y)\n```\n\ntext\n\n```\n    # Compute gradients\n    loss.backward()\n```\n\ntext\n\n```\n    # Tune parameters\n    optimizer.step()\n```\n\ntext\n\n```\n    # Store data for animations\n    embeddings.append(h)\n    losses.append(loss)\n    accuracies.append(acc)\n    outputs.append(z.argmax(dim=1))\n```\n\ntext\n\n```\n    # Print metrics every 10 epochs\n    if epoch % 10 == 0:\n        print(f'Epoch {epoch:>3} | Loss: {loss:.2f} | Acc: {acc*100:.2f}%')\n```\n\ntext\n\n```\nEpoch   0 | Loss: 1.40 | Acc: 41.18%\nEpoch  10 | Loss: 1.21 | Acc: 47.06%\nEpoch  20 | Loss: 1.02 | Acc: 67.65%\nEpoch  30 | Loss: 0.80 | Acc: 73.53%\nEpoch  40 | Loss: 0.59 | Acc: 73.53%\nEpoch  50 | Loss: 0.39 | Acc: 94.12%\nEpoch  60 | Loss: 0.23 | Acc: 97.06%\nEpoch  70 | Loss: 0.13 | Acc: 100.00%\nEpoch  80 | Loss: 0.07 | Acc: 100.00%\nEpoch  90 | Loss: 0.05 | Acc: 100.00%\nEpoch 100 | Loss: 0.03 | Acc: 100.00%\nEpoch 110 | Loss: 0.02 | Acc: 100.00%\nEpoch 120 | Loss: 0.02 | Acc: 100.00%\nEpoch 130 | Loss: 0.02 | Acc: 100.00%\nEpoch 140 | Loss: 0.01 | Acc: 100.00%\nEpoch 150 | Loss: 0.01 | Acc: 100.00%\nEpoch 160 | Loss: 0.01 | Acc: 100.00%\nEpoch 170 | Loss: 0.01 | Acc: 100.00%\nEpoch 180 | Loss: 0.01 | Acc: 100.00%\nEpoch 190 | Loss: 0.01 | Acc: 100.00%\nEpoch 200 | Loss: 0.01 | Acc: 100.00%\n```\n\nGreat! Without much surprise, we reach 100% accuracy on the training set (full dataset). It means that our model learned to correctly assign every member of the karate club to its correct group.\nWe can produce a neat visualization by animating the graph and see the evolution of the GNN's predictions during the training process.\njavascript\n\n```\n%%capture\nfrom IPython.display import HTML\nfrom matplotlib import animation\nplt.rcParams[\"animation.bitrate\"] = 3000\n```\n\ntext\n\n```\ndef animate(i):\n    G = to_networkx(data, to_undirected=True)\n    nx.draw_networkx(G,\n                    pos=nx.spring_layout(G, seed=0),\n                    with_labels=True,\n                    node_size=800,\n                    node_color=outputs[i],\n                    cmap=\"hsv\",\n                    vmin=-2,\n                    vmax=3,\n                    width=0.8,\n                    edge_color=\"grey\",\n                    font_size=14\n                    )\n    plt.title(f'Epoch {i} | Loss: {losses[i]:.2f} | Acc: {accuracies[i]*100:.2f}%',\n              fontsize=18, pad=20)\n```\n\ntext\n\n```\nfig = plt.figure(figsize=(12, 12))\nplt.axis('off')\n```\n\ntext\n\n```\nanim = animation.FuncAnimation(fig, animate, \n            np.arange(0, 200, 10), interval=500, repeat=True)\nhtml = HTML(anim.to_html5_video())\ndisplay(html)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1SICganhibeJlFogOCFob1Q.gif)\nThe first predictions are random, but the GCN perfectly labels every node after a while. Indeed, the final graph is the same as the one we plotted at the end of the first section. But what does the GCN really learn?\nBy aggregating features from neighboring nodes, the GNN learns a vector representation (or **embedding**) of every node in the network. In our model, the final layer just learns how to use these representations to produce the best classifications. However, embeddings are the real products of GNNs.\nLet's print the embeddings learned by our model.\npython\n\n```\n# Print embeddings\nprint(f'Final embeddings = {h.shape}')\nprint(h)\n```\n\ntext\n\n```\nFinal embeddings = torch.Size([34, 3])\ntensor([[1.9099e+00, 2.3584e+00, 7.4027e-01],\n        [2.6203e+00, 2.7997e+00, 0.0000e+00],\n        [2.2567e+00, 2.2962e+00, 6.4663e-01],\n        [2.0802e+00, 2.8785e+00, 0.0000e+00],\n        [0.0000e+00, 0.0000e+00, 2.9694e+00],\n        [0.0000e+00, 0.0000e+00, 3.3817e+00],\n        [0.0000e+00, 1.5008e-04, 3.4246e+00],\n        [1.7593e+00, 2.4292e+00, 2.4551e-01],\n        [1.9757e+00, 6.1032e-01, 1.8986e+00],\n        [1.7770e+00, 1.9950e+00, 6.7018e-01],\n        [0.0000e+00, 1.1683e-04, 2.9738e+00],\n        [1.8988e+00, 2.0512e+00, 2.6225e-01],\n        [1.7081e+00, 2.3618e+00, 1.9609e-01],\n        [1.8303e+00, 2.1591e+00, 3.5906e-01],\n        [2.0755e+00, 2.7468e-01, 1.9804e+00],\n        [1.9676e+00, 3.7185e-01, 2.0011e+00],\n        [0.0000e+00, 0.0000e+00, 3.4787e+00],\n        [1.6945e+00, 2.0350e+00, 1.9789e-01],\n        [1.9808e+00, 3.2633e-01, 2.1349e+00],\n        [1.7846e+00, 1.9585e+00, 4.8021e-01],\n        [2.0420e+00, 2.7512e-01, 1.9810e+00],\n        [1.7665e+00, 2.1357e+00, 4.0325e-01],\n        [1.9870e+00, 3.3886e-01, 2.0421e+00],\n        [2.0614e+00, 5.1042e-01, 2.4872e+00],\n...\n        [2.1778e+00, 4.4730e-01, 2.0077e+00],\n        [3.8906e-02, 2.3443e+00, 1.9195e+00],\n        [3.0748e+00, 0.0000e+00, 3.0789e+00],\n        [3.4316e+00, 1.9716e-01, 2.5231e+00]], grad_fn=<ReluBackward0>)\n```\n\nAs you can see, embeddings do not need to have the same dimensions as feature vectors. Here, I chose to reduce the number of dimensions from 34 (`dataset.num_features`) to three to get a nice visualization in 3D.\nLet's plot these embeddings before any training happens, at epoch 0.\npython\n\n```\n# Get first embedding at epoch = 0\nembed = h.detach().cpu().numpy()\n```\n\ntext\n\n```\nfig = plt.figure(figsize=(12, 12))\nax = fig.add_subplot(projection='3d')\nax.patch.set_alpha(0)\nplt.tick_params(left=False,\n                bottom=False,\n                labelleft=False,\n                labelbottom=False)\nax.scatter(embed[:, 0], embed[:, 1], embed[:, 2],\n           s=200, c=data.y, cmap=\"hsv\", vmin=-2, vmax=3)\n```\n\ntext\n\n```\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1EP37HkRCQB0TitIlWARXgw.png)\nWe see every node from Zachary's karate club with their true labels (and not the model's predictions). For now, they're all over the place since the GNN is not trained yet. But if we plot these embeddings at each step of the training loop, we'd be able to visualize what the GNN truly learns.\nLet's see how they evolve over time, as the GCN gets better and better at classifying nodes.\npython\n\n```\n%%capture\n```\n\ntext\n\n```\ndef animate(i):\n    embed = embeddings[i].detach().cpu().numpy()\n    ax.clear()\n    ax.scatter(embed[:, 0], embed[:, 1], embed[:, 2],\n           s=200, c=data.y, cmap=\"hsv\", vmin=-2, vmax=3)\n    plt.title(f'Epoch {i} | Loss: {losses[i]:.2f} | Acc: {accuracies[i]*100:.2f}%',\n              fontsize=18, pad=40)\n```\n\ntext\n\n```\nfig = plt.figure(figsize=(12, 12))\nplt.axis('off')\nax = fig.add_subplot(projection='3d')\nplt.tick_params(left=False,\n                bottom=False,\n                labelleft=False,\n                labelbottom=False)\n```\n\ntext\n\n```\nanim = animation.FuncAnimation(fig, animate, \n              np.arange(0, 200, 10), interval=800, repeat=True)\nhtml = HTML(anim.to_html5_video())\ndisplay(html)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1CiegA_x7-oTYRgzl-WDpBw.gif)\nOur Graph Convolutional Network (GCN) has effectively learned embeddings that group similar nodes into **distinct clusters**. This enables the final linear layer to distinguish them into separate classes with ease.\nEmbeddings are not unique to GNNs: they can be found everywhere in deep learning. They don't have to be 3D either: actually, they rarely are. For instance, language models like [BERT](https://arxiv.org/abs/1810.04805) produce embeddings with 768 or even 1024 dimensions.\nAdditional dimensions store more information about nodes, text, images, etc. but they also create bigger models that are more difficult to train. This is why keeping low-dimensional embeddings as long as possible is advantageous.\n## Conclusion\nGraph Convolutional Networks are an incredibly versatile architecture that can be applied in **many contexts**. In this article, we familiarized ourselves with the PyTorch Geometric library and objects like `Datasets` and `Data`. Then, we successfully reconstructed a graph convolutional layer from the ground up. Next, we put theory into practice by implementing a GCN, which gave us an understanding of practical aspects and how individual components interact. Finally, we visualized the training process and obtained a clear perspective of what it involves for such a network.\nZachary's karate club is a simplistic dataset, but it is good enough to understand the most important concepts in graph data and GNNs. Although we only talked about node classification in this article, there are other tasks GNNs can accomplish: **link prediction** (e.g., to recommend a friend), **graph classification** (e.g., to label molecules), **graph generation** (e.g., to create new molecules), and so on.\nBeyond GCN, numerous GNN layers and architectures have been proposed by researchers. In the next article, we'll introduce the [Graph Attention Network](https://mlabonne.github.io/blog/gat/) (GAT) architecture, which dynamically computes the GCN's normalization factor and the importance of each connection with an attention mechanism.\nIf you want to know more about graph neural networks, dive deeper into the world of GNNs with my book, [Hands-On Graph Neural Networks](https://mlabonne.github.io/blog/book.html).\n## Next article\n> [**Chapter 2: Graph Attention Networks: Self-Attention Explained**](https://towardsdatascience.com/graph-attention-networks-in-python-975736ac5c0c)\n* * *\n_Learn more about machine learning and support my work with one click - become a Medium member here:_\n> [**Join Medium with my referral link - Maxime Labonne**](https://medium.com/@mlabonne/membership)\n_If you're already a member, you can_[ _follow me on Medium_](https://medium.com/@mlabonne) _._\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657499317_sxy3ci.png)\nWritten By\n## [Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\n[See all from Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\n[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Graph Neural Networks](https://towardsdatascience.com/tag/graph-neural-networks/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Programming](https://towardsdatascience.com/tag/programming/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fgraph-convolutional-networks-introduction-to-gnns-24b3f60d6c95%2F&title=Graph%20Convolutional%20Networks%3A%20Introduction%20to%20GNNs)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fgraph-convolutional-networks-introduction-to-gnns-24b3f60d6c95%2F&title=Graph%20Convolutional%20Networks%3A%20Introduction%20to%20GNNs)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fgraph-convolutional-networks-introduction-to-gnns-24b3f60d6c95%2F&text=Graph%20Convolutional%20Networks%3A%20Introduction%20to%20GNNs)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/05/1sIlSOdhIq3yL39YujCNklw.jpeg)](https://towardsdatascience.com/custom-iteration-patterns-with-python-generators-12b98e552b38/)\n## [Custom Iteration Patterns with Python Generators](https://towardsdatascience.com/custom-iteration-patterns-with-python-generators-12b98e552b38/)\n[Programming](https://towardsdatascience.com/category/programming/)\nCreating Custom Iteration Patterns\n[Sadrach Pierre, Ph.D.](https://towardsdatascience.com/author/spierre91/)\nMay 8, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/11/1k_SJp9oopJ58gUerEYB9FA-scaled.jpeg)](https://towardsdatascience.com/measuring-the-cognitive-overload-factor-of-a-data-visualization-65b0ce56254b/)\n## [Measuring the Cognitive Overload Factor of a Data Visualization](https://towardsdatascience.com/measuring-the-cognitive-overload-factor-of-a-data-visualization-65b0ce56254b/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA simple empirical method to compute COF, illustrated\n[Murali Kashaboina](https://towardsdatascience.com/author/murali-kashaboina/)\nNovember 22, 20228 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/01/0g2GDll9oaaXLzQid-scaled.jpg)](https://towardsdatascience.com/from-darwin-to-deep-work-0db4bf1761d8/)\n## [From Darwin to Deep Work](https://towardsdatascience.com/from-darwin-to-deep-work-0db4bf1761d8/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nFocus Strategies for Machine Learning Practitioners\n[Pascal Janetzky](https://towardsdatascience.com/author/pascaljanetzky/)\nJanuary 14, 20256 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/03/1W1bW4WF7meFit79lATTpyw.jpeg)](https://towardsdatascience.com/analyzing-melbourne-house-prices-with-r-5c13218f242d/)\n## [Analyzing Melbourne House Prices with R](https://towardsdatascience.com/analyzing-melbourne-house-prices-with-r-5c13218f242d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA comprehensive practice guide for data analysis.\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nMarch 6, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1x79T2-26lkEpdoErqbtgqw.jpeg)](https://towardsdatascience.com/logistic-regression-in-classification-model-using-python-machine-learning-dc9573e971d0/)\n## [Logistic Regression in Classification model using Python: Machine Learning](https://towardsdatascience.com/logistic-regression-in-classification-model-using-python-machine-learning-dc9573e971d0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearning how to build a basic logistic regression model in machine learning using python\n[Kaushik Katari](https://towardsdatascience.com/author/kaushikvarma.katari/)\nNovember 3, 20203 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/12/1hOv1TFcUPQ4vf4A8TbwLCQ.jpeg)](https://towardsdatascience.com/logistic-regression-models-comparison-2a88a9da4eb6/)\n## [Logistic Regression Models Comparison](https://towardsdatascience.com/logistic-regression-models-comparison-2a88a9da4eb6/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nStatistics in R Series\n[Md Sohel Mahmood](https://towardsdatascience.com/author/mdsohel-mahmood/)\nDecember 4, 20225 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/0gddcH-jkWm4jjic-scaled.jpg)](https://towardsdatascience.com/identifying-global-feature-relationships-with-shap-values-f9e8b2b4121c/)\n## [Identifying Global Feature Relationships with SHAP Values](https://towardsdatascience.com/identifying-global-feature-relationships-with-shap-values-f9e8b2b4121c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to calculate global information for your features and use it for agnostic feature selection proceduresx\n[Tiago Toledo Jr.](https://towardsdatascience.com/author/tiagotoledojr/)\nDecember 7, 20218 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1Gs-91OoxjBQicsatrYhpfw-scaled.jpeg)](https://towardsdatascience.com/postmortems-the-single-most-important-keystone-habit-for-a-team-step-by-step-guide-d2d14de5b3ad/)\n## [Postmortems: The single most important keystone habit for a team (step-by-step guide)](https://towardsdatascience.com/postmortems-the-single-most-important-keystone-habit-for-a-team-step-by-step-guide-d2d14de5b3ad/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nI'm an ill-disciplined person. My habit of reading books about habit-formation is stronger than any of the habits they've help me form.\n[Greg Detre](https://towardsdatascience.com/author/gregdetre/)\nJanuary 10, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/ChatGPT-Image-May-22-2026-01_27_30-PM.jpg)](https://towardsdatascience.com/the-domain-shift-moving-data-governance-from-product-triage-to-infrastructure-investment/)\n## [The Domain Shift: Moving Data Governance from Product Triage to Infrastructure Investment](https://towardsdatascience.com/the-domain-shift-moving-data-governance-from-product-triage-to-infrastructure-investment/)\n[Data Governance](https://towardsdatascience.com/category/data-science/data-governance/)\nHow shifting the operational focus from isolated data products to systemic domain architecture resolves technical bottlenecks and optimizes platform investment.\n[Sravani Alle](https://towardsdatascience.com/author/alle-sravani/)\nMay 26, 20267 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3642/image?etag=1780830904480&width=500&height=500) Check Your Biases ](https://towardsdatascience.com/check-your-biases-ba2685a7f799/ \"Check Your Biases\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4973/image?etag=1782232567105&width=500&height=500) Machine Learning Tricks, Learning with ChatGPT, and Other Recent Must-Reads ](https://towardsdatascience.com/machine-learning-tricks-learning-with-chatgpt-and-other-recent-must-reads-f277648a1921/ \"Machine Learning Tricks, Learning with ChatGPT, and Other Recent Must-Reads\")\n\n\nword word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word\n  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1\n",
  "metadata": {
    "title": "Graph Convolutional Networks: Introduction to GNNs | Towards Data Science",
    "description": "A step-by-step guide using PyTorch Geometric",
    "keywords": null,
    "author": "Maxime Labonne",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Graph Convolutional Networks: Introduction to GNNs",
    "og:description": "A step-by-step guide using PyTorch Geometric",
    "og:url": "https://towardsdatascience.com/graph-convolutional-networks-introduction-to-gnns-24b3f60d6c95/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1X4I4_PO9l14apt0h3Nbw2A.jpeg",
    "og:image:width": "1920",
    "og:image:height": "1080",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Maxime Labonne",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "17 min read",
    "article:published_time": "2023-08-14T14:12:08.000Z",
    "article:modified_time": "2023-08-14T14:12:08.000Z",
    "article:author": "https://towardsdatascience.com/author/mlabonne/"
  },
  "paywall": {
    "listed_paid": true,
    "detected": false,
    "marker": "",
    "public_only": true,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": "",
    "retried": true
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_000.txt",
      "chars": 29
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_001.txt",
      "chars": 86
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_002.txt",
      "chars": 48
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_003.txt",
      "chars": 63
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_004.txt",
      "chars": 204
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_005.txt",
      "chars": 90
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_006.txt",
      "chars": 52
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_007.txt",
      "chars": 70
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_008.txt",
      "chars": 18
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_009.txt",
      "chars": 43
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_010.txt",
      "chars": 279
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_011.txt",
      "chars": 70
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_012.txt",
      "chars": 1447
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_013.txt",
      "chars": 47
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_014.txt",
      "chars": 90
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_015.txt",
      "chars": 133
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_016.txt",
      "chars": 43
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_017.txt",
      "chars": 140
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_018.txt",
      "chars": 70
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_019.txt",
      "chars": 301
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_020.txt",
      "chars": 166
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_021.txt",
      "chars": 81
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_022.txt",
      "chars": 46
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_023.txt",
      "chars": 452
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_024.txt",
      "chars": 68
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_025.txt",
      "chars": 181
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_026.txt",
      "chars": 125
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_027.txt",
      "chars": 27
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_028.txt",
      "chars": 89
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_029.txt",
      "chars": 98
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_030.txt",
      "chars": 86
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_031.txt",
      "chars": 79
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_032.txt",
      "chars": 89
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_033.txt",
      "chars": 61
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_034.txt",
      "chars": 62
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_035.txt",
      "chars": 69
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_036.txt",
      "chars": 44
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_037.txt",
      "chars": 43
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_038.txt",
      "chars": 144
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_039.txt",
      "chars": 136
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_040.txt",
      "chars": 791
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_041.txt",
      "chars": 117
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_042.txt",
      "chars": 588
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_043.txt",
      "chars": 51
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_044.txt",
      "chars": 157
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_045.txt",
      "chars": 67
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_046.txt",
      "chars": 1357
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_047.txt",
      "chars": 68
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_048.txt",
      "chars": 328
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_049.txt",
      "chars": 11
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_050.txt",
      "chars": 10
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_051.txt",
      "chars": 310
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_052.txt",
      "chars": 215
    },
    {
      "language": "txt",
      "file": "attachments/83deaecba8a3/code/block_053.txt",
      "chars": 159
    }
  ],
  "images": [
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1X4I4_PO9l14apt0h3Nbw2A.jpeg",
      "alt": "Image by author",
      "local_path": "attachments/83deaecba8a3/images/000.jpeg",
      "bytes": 188966,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1gPUxh53IHnS0lnnks8_L3Q.png",
      "alt": "Image by author",
      "local_path": "attachments/83deaecba8a3/images/001.png",
      "bytes": 868308,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1CjPY3V96hZ647kb38hVaNg.png",
      "alt": "Image by author",
      "local_path": "attachments/83deaecba8a3/images/002.png",
      "bytes": 121378,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/05/1sIlSOdhIq3yL39YujCNklw.jpeg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/003.jpeg",
      "bytes": 386609,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/11/1k_SJp9oopJ58gUerEYB9FA-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/004.jpeg",
      "bytes": 607923,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/01/0g2GDll9oaaXLzQid-scaled.jpg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/005.jpg",
      "bytes": 336785,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/03/1W1bW4WF7meFit79lATTpyw.jpeg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/006.jpeg",
      "bytes": 162342,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1x79T2-26lkEpdoErqbtgqw.jpeg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/007.jpeg",
      "bytes": 160250,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/12/1hOv1TFcUPQ4vf4A8TbwLCQ.jpeg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/008.jpeg",
      "bytes": 171371,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/0gddcH-jkWm4jjic-scaled.jpg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/009.jpg",
      "bytes": 173394,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1Gs-91OoxjBQicsatrYhpfw-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/010.jpeg",
      "bytes": 315689,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/ChatGPT-Image-May-22-2026-01_27_30-PM.jpg",
      "alt": "",
      "local_path": "attachments/83deaecba8a3/images/011.jpg",
      "bytes": 299589,
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [],
  "links": [],
  "retry_at": "2026-10-03T07:59:28",
  "repair_version": 2,
  "repaired_at": "2026-10-14T11:11:49Z",
  "source_url": "https://towardsdatascience.com/graph-convolutional-networks-introduction-to-gnns-24b3f60d6c95/",
  "delivery_status": "excluded_paid",
  "discovery_status": "excluded_paid",
  "missing_reason": "按原约定排除付费/会员全文"
}