{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Train a Hypersage TNN\n", "\n", "In this notebook, we will create and train HyperSAGE layer (Arya et al., [2020](https://arxiv.org/abs/2010.04558)) - two-levels message passing strategy for hypergraphs learning. We will use a benchmark dataset, shrec16, a collection of 3D meshes, to train the model to perform classification at the level of the hypergraph.\n", "\n", "Following the \"awesome-tnns\" [github repo.](https://github.com/awesome-tnns/awesome-tnns/blob/main/Hypergraphs.md)\n", "\n", "๐ŸŸฅ $\\quad m_{y \\rightarrow z}^{(0 \\rightarrow 1)} = (B_1)^T_{zy} \\cdot w_y \\cdot (h_y^{(0)})^p$ \n", "\n", "๐ŸŸฅ $\\quad m_z^{(0 \\rightarrow 1)} = \\left(\\frac{1}{\\vert \\mathcal{B}(z)\\vert}\\sum_{y \\in \\mathcal{B}(z)} m_{y \\rightarrow z}^{(0 \\rightarrow 1)}\\right)^{\\frac{1}{p}}$\n", "\n", "๐ŸŸฅ $\\quad m_{z \\rightarrow x}^{(1 \\rightarrow 0)} = (B_1)_{xz} \\cdot w_z \\cdot (m_z^{(0 \\rightarrow 1)})^p$\n", "\n", "๐ŸŸง $\\quad m_x^{(1 \\rightarrow 0)} = \\left(\\frac{1}{\\vert \\mathcal{C}(x) \\vert}\\sum_{z \\in \\mathcal{C}(x)} m_{z \\rightarrow x}^{(1 \\rightarrow 0)}\\right)^{\\frac{1}{p}}$\n", "\n", "๐ŸŸฉ $\\quad m_x^{(0)} = m_x^{(1 \\rightarrow 0)}$ \n", "\n", "๐ŸŸฆ $\\quad h_x^{t+1, (0)} = \\sigma \\left(\\frac{m_x^{(0)} + h_x^{t,(0)}}{\\lvert m_x^{(0)} + h_x^{t,(0)}\\rvert} \\cdot \\Theta^t\\right)$ \n", "\n", "### Additional theoretical clarifications\n", "\n", "Arya et al propose to interpret the propagation of information in a given hypergraph as a two-level aggregation problem, where the neighborhood of any node is divided into intra-edge neighbors and inter-edge neighbors. Given a hypergraph $H=(\\mathcal{V}, \\mathcal{E})$, let $\\textbf{X}$ denote the feature matrix, such that $\\textbf{x}_{i} \\in \\textbf{X}$ is the feature set for node $\\textbf{v}_{i} \\in \\textbf{V}$ . For two-level aggregation, \n", "let $\\mathcal{F}_{1}(ยท)$ and $\\mathcal{F}_{2}(ยท)$ denote the intra-edge and inter-edge aggregation functions, respectively. Message passing at node vi for aggregation of information at the $\\mathcal{l}^{th}$ layer can then be stated as\n", "\n", "$ \\mathcal{x}_{i,l}^{(e)} \\leftarrow \\mathcal{F}_{1}(\\{ \\mathcal{x}_{j,l-1} | \\mathcal{v}_{j} \\in \\mathcal{N}( \\mathcal{v}_{i},\n", "\\textbf{e},\\alpha) \\}), $\n", "\n", "$ \\mathcal{x}_{i,l} \\leftarrow \\mathcal{x}_{i,l-1} + \\mathcal{F}_{2}(\\{ \\mathcal{x}_{i,l}^{(e)} | \\mathcal{v}_{i} \\in {E}( \\mathcal{v}_{i}) \\}), $\n", "\n", "where, $ \\mathcal{x}_{i,l}^{(e)}$ refers to the aggregated feature set at $\\mathcal{v}_{i}$ obtained with intra-edge aggregation for edge $\\textbf{e}$." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2023-06-01T16:14:51.222779223Z", "start_time": "2023-06-01T16:14:49.575421023Z" } }, "outputs": [], "source": [ "\"\"\"\n", "This module contains the HyperSAGE class for hypergraph-based neural networks.\n", "\n", "The AllSet class implements a specific hypergraph-based neural network architecture\n", "used for solving certain types of problems.\n", "\n", "Author: Your Name\n", "\n", "\"\"\"\n", "\n", "import numpy as np\n", "import torch\n", "import torch_geometric.datasets as geom_datasets\n", "from torch_geometric.utils import to_undirected\n", "\n", "from topomodelx.nn.hypergraph.hypersage import HyperSAGE\n", "\n", "torch.manual_seed(0)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "If GPU's are available, we will make use of them. Otherwise, this will run on CPU." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2023-06-01T16:14:51.959770754Z", "start_time": "2023-06-01T16:14:51.956096841Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cuda\n" ] } ], "source": [ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "print(device)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Pre-processing\n", "\n", "## Import data ##\n", "\n", "The first step is to import the dataset, Cora, a benchmark classification datase. We then lift the graph into our domain of choice, a hypergraph.\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2023-06-01T16:14:53.022151550Z", "start_time": "2023-06-01T16:14:52.949636599Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.11/site-packages/torch_geometric/data/in_memory_dataset.py:284: UserWarning: It is not recommended to directly access the internal storage format `data` of an 'InMemoryDataset'. If you are absolutely certain what you are doing, access the internal storage via `InMemoryDataset._data` instead to suppress this warning. Alternatively, you can access stacked individual attributes of every graph via `dataset.{attr_name}`.\n", " warnings.warn(msg)\n" ] } ], "source": [ "cora = geom_datasets.Planetoid(root=\"tmp/\", name=\"cora\")\n", "data = cora.data\n", "\n", "x_0s = data.x\n", "y = data.y\n", "edge_index = data.edge_index\n", "\n", "train_mask = data.train_mask\n", "val_mask = data.val_mask\n", "test_mask = data.test_mask" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Define neighborhood structures and lift into hypergraph domain. ##\n", "\n", "Now we retrieve the neighborhood structure (i.e. their representative matrice) that we will use to send messges from node to hyperedges. In the case of this architecture, we need the boundary matrix (or incidence matrix) $B_1$ with shape $n_\\text{nodes} \\times n_\\text{edges}$.\n", "\n", "In citation Cora dataset we lift graph structure to the hypergraph domain by creating hyperedges from 1-hop graph neighbourhood of each node. \n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2023-06-01T16:14:53.022151550Z", "start_time": "2023-06-01T16:14:52.949636599Z" } }, "outputs": [], "source": [ "# Ensure the graph is undirected (optional but often useful for one-hop neighborhoods).\n", "edge_index = to_undirected(edge_index)\n", "\n", "# Create a list of one-hop neighborhoods for each node.\n", "one_hop_neighborhoods = []\n", "for node in range(data.num_nodes):\n", " # Get the one-hop neighbors of the current node.\n", " neighbors = data.edge_index[1, data.edge_index[0] == node]\n", "\n", " # Append the neighbors to the list of one-hop neighborhoods.\n", " one_hop_neighborhoods.append(neighbors.numpy())\n", "\n", "# Detect and eliminate duplicate hyperedges.\n", "unique_hyperedges = set()\n", "hyperedges = []\n", "for neighborhood in one_hop_neighborhoods:\n", " # Sort the neighborhood to ensure consistent comparison.\n", " neighborhood = tuple(sorted(neighborhood))\n", " if neighborhood not in unique_hyperedges:\n", " hyperedges.append(list(neighborhood))\n", " unique_hyperedges.add(neighborhood)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Additionally we print the statictis associated with obtained incidence matrix" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hyperedge statistics: \n", "Number of hyperedges without duplicated hyperedges 2581\n", "min = 1, \n", "max = 168, \n", "mean = 4.003099573808601, \n", "median = 3.0, \n", "std = 5.327622607829558, \n", "Number of hyperedges with size equal to one = 412\n" ] } ], "source": [ "# Calculate hyperedge statistics.\n", "hyperedge_sizes = [len(he) for he in hyperedges]\n", "min_size = min(hyperedge_sizes)\n", "max_size = max(hyperedge_sizes)\n", "mean_size = np.mean(hyperedge_sizes)\n", "median_size = np.median(hyperedge_sizes)\n", "std_size = np.std(hyperedge_sizes)\n", "num_single_node_hyperedges = sum(np.array(hyperedge_sizes) == 1)\n", "\n", "# Print the hyperedge statistics.\n", "print(\"Hyperedge statistics: \")\n", "print(\"Number of hyperedges without duplicated hyperedges\", len(hyperedges))\n", "print(f\"min = {min_size}, \")\n", "print(f\"max = {max_size}, \")\n", "print(f\"mean = {mean_size}, \")\n", "print(f\"median = {median_size}, \")\n", "print(f\"std = {std_size}, \")\n", "print(f\"Number of hyperedges with size equal to one = {num_single_node_hyperedges}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Construct incidence matrix" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "max_edges = len(hyperedges)\n", "incidence_1 = np.zeros((x_0s.shape[0], max_edges))\n", "for col, neighibourhood in enumerate(hyperedges):\n", " for row in neighibourhood:\n", " incidence_1[row, col] = 1\n", "\n", "assert all(incidence_1.sum(0) > 0) is True, \"Some hyperedges are empty\"\n", "assert all(incidence_1.sum(1) > 0) is True, \"Some nodes are not in any hyperedges\"\n", "incidence_1 = torch.Tensor(incidence_1).to_sparse_coo()" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Create the Neural Network" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define the network that initializes the base model and sets up the readout operation.\n", "Different downstream tasks might require different pooling procedures.\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "class Network(torch.nn.Module):\n", " \"\"\"Network class that initializes the base model and readout layer.\n", "\n", " Base model parameters:\n", " ----------\n", " Reqired:\n", " in_channels : int\n", " Dimension of the input features.\n", " hidden_channels : int\n", " Dimension of the hidden features.\n", "\n", " Optitional:\n", " **kwargs : dict\n", " Additional arguments for the base model.\n", "\n", " Readout layer parameters:\n", " ----------\n", " out_channels : int\n", " Dimension of the output features.\n", " task_level : str\n", " Level of the task. Either \"graph\" or \"node\".\n", " \"\"\"\n", "\n", " def __init__(\n", " self, in_channels, hidden_channels, out_channels, task_level=\"graph\", **kwargs\n", " ):\n", " super().__init__()\n", "\n", " # Define the model\n", " self.base_model = HyperSAGE(\n", " in_channels=in_channels, hidden_channels=hidden_channels, **kwargs\n", " )\n", "\n", " # Readout\n", " self.linear = torch.nn.Linear(hidden_channels, out_channels)\n", " self.out_pool = task_level == \"graph\"\n", "\n", " def forward(self, x_0, incidence_1):\n", " # Base model\n", " x_0 = self.base_model(x_0, incidence_1)\n", "\n", " # Pool over all nodes in the hypergraph\n", " x = torch.max(x_0, dim=0)[0] if self.out_pool is True else x_0\n", "\n", " return self.linear(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Initialize the model" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# Base model hyperparameters\n", "in_channels = x_0s.shape[1]\n", "hidden_channels = 128\n", "n_layers = 1\n", "mlp_num_layers = 1\n", "\n", "# Readout hyperparameters\n", "out_channels = torch.unique(y).shape[0]\n", "task_level = \"graph\" if out_channels == 1 else \"node\"\n", "\n", "\n", "model = Network(\n", " in_channels=in_channels,\n", " hidden_channels=hidden_channels,\n", " out_channels=out_channels,\n", " n_layers=n_layers,\n", " device=device,\n", " task_level=task_level,\n", ").to(device)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Train the Neural Network\n", "\n", "We specify the model, the loss, and an optimizer." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# Optimizer and loss\n", "opt = torch.optim.Adam(model.parameters(), lr=0.01)\n", "\n", "# Categorial cross-entropy loss\n", "loss_fn = torch.nn.CrossEntropyLoss()\n", "\n", "\n", "# Accuracy\n", "def acc_fn(y, y_hat):\n", " return (y == y_hat).float().mean()" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2023-06-01T16:14:59.046068930Z", "start_time": "2023-06-01T16:14:59.037648626Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_33450/1422611997.py:1: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).\n", " x_0s = torch.tensor(x_0s)\n", "/tmp/ipykernel_33450/1422611997.py:5: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).\n", " torch.tensor(y, dtype=torch.long).to(device),\n" ] } ], "source": [ "x_0s = torch.tensor(x_0s)\n", "x_0s, incidence_1, y = (\n", " x_0s.float().to(device),\n", " incidence_1.float().to(device),\n", " torch.tensor(y, dtype=torch.long).to(device),\n", ")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "The following cell performs the training, looping over the network for a low amount of epochs. We keep training minimal for the purpose of rapid testing." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_33450/1422611997.py:1: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).\n", " x_0s = torch.tensor(x_0s)\n", "/tmp/ipykernel_33450/1422611997.py:5: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).\n", " torch.tensor(y, dtype=torch.long).to(device),\n" ] } ], "source": [ "x_0s = torch.tensor(x_0s)\n", "x_0s, incidence_1, y = (\n", " x_0s.float().to(device),\n", " incidence_1.float().to(device),\n", " torch.tensor(y, dtype=torch.long).to(device),\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note: The number of epochs below have been kept low to facilitate debugging and testing. Real use cases should likely require more epochs.**" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch: 5 \n", "Train_loss: 1.9424, acc: 0.5929\n", "Val_loss: 1.9401, Val_acc: 0.2460\n", "Test_loss: 1.9405, Test_acc: 0.2620\n", "Epoch: 10 \n", "Train_loss: 1.9305, acc: 0.9357\n", "Val_loss: 1.9221, Val_acc: 0.5680\n", "Test_loss: 1.9220, Test_acc: 0.5580\n", "Epoch: 15 \n", "Train_loss: 1.9105, acc: 0.9714\n", "Val_loss: 1.8899, Val_acc: 0.6560\n", "Test_loss: 1.8904, Test_acc: 0.6490\n", "Epoch: 20 \n", "Train_loss: 1.8811, acc: 0.9786\n", "Val_loss: 1.8450, Val_acc: 0.7260\n", "Test_loss: 1.8466, Test_acc: 0.6990\n", "Epoch: 25 \n", "Train_loss: 1.8412, acc: 0.9929\n", "Val_loss: 1.7831, Val_acc: 0.7360\n", "Test_loss: 1.7857, Test_acc: 0.7210\n", "Epoch: 30 \n", "Train_loss: 1.7905, acc: 1.0000\n", "Val_loss: 1.7067, Val_acc: 0.7420\n", "Test_loss: 1.7103, Test_acc: 0.7220\n" ] } ], "source": [ "torch.manual_seed(0)\n", "test_interval = 5\n", "num_epochs = 5\n", "\n", "epoch_loss = []\n", "for epoch_i in range(1, num_epochs + 1):\n", " model.train()\n", "\n", " opt.zero_grad()\n", "\n", " # Extract edge_index from sparse incidence matrix\n", " y_hat = model(x_0s, incidence_1)\n", " loss = loss_fn(y_hat[train_mask], y[train_mask])\n", "\n", " loss.backward()\n", " opt.step()\n", " epoch_loss.append(loss.item())\n", "\n", " if epoch_i % test_interval == 0:\n", " model.eval()\n", " y_hat = model(x_0s, incidence_1)\n", "\n", " loss = loss_fn(y_hat[train_mask], y[train_mask])\n", " print(f\"Epoch: {epoch_i} \")\n", " print(\n", " f\"Train_loss: {np.mean(epoch_loss):.4f}, acc: {acc_fn(y_hat[train_mask].argmax(1), y[train_mask]):.4f}\",\n", " flush=True,\n", " )\n", "\n", " loss = loss_fn(y_hat[val_mask], y[val_mask])\n", "\n", " print(\n", " f\"Val_loss: {loss:.4f}, Val_acc: {acc_fn(y_hat[val_mask].argmax(1), y[val_mask]):.4f}\",\n", " flush=True,\n", " )\n", "\n", " loss = loss_fn(y_hat[test_mask], y[test_mask])\n", " print(\n", " f\"Test_loss: {loss:.4f}, Test_acc: {acc_fn(y_hat[test_mask].argmax(1), y[test_mask]):.4f}\",\n", " flush=True,\n", " )" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.3" }, "vscode": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" } } }, "nbformat": 4, "nbformat_minor": 2 }