Train a hypergraph neural network using UniGCNII layers#
This tutorial consists of three main steps: 1. Loading the CiCitationCora dataset and lifting it to the hypergraph domain. 2. Defining a hypergraph neural network (HGNN) which utlilizes the UniGCNII layer, and 3. Training the obtained neural network on the training data and evaluating it on test data.
First, we import the neccessary packages.
[1]:
import numpy as np
import torch
import torch_geometric.datasets as geom_datasets
from torch_geometric.utils import to_undirected
from topomodelx.nn.hypergraph.unigcnii import UniGCNII
torch.manual_seed(0)
If GPUs are available, we want to make use of them, otherwise the model is run on CPU.
[2]:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
cuda
Pre-processing#
Import data#
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.
[3]:
cora = geom_datasets.Planetoid(root="tmp/", name="cora")
data = cora.data
x_0s = data.x
y = data.y
edge_index = data.edge_index
train_mask = data.train_mask
val_mask = data.val_mask
test_mask = data.test_mask
/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}`.
warnings.warn(msg)
Define neighborhood structures and lift into hypergraph domain.#
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}\).
In citation Cora dataset we lift graph structure to the hypergraph domain by creating hyperedges from 1-hop graph neighbourhood of each node.
[4]:
# Ensure the graph is undirected (optional but often useful for one-hop neighborhoods).
edge_index = to_undirected(edge_index)
# Create a list of one-hop neighborhoods for each node.
one_hop_neighborhoods = []
for node in range(data.num_nodes):
# Get the one-hop neighbors of the current node.
neighbors = data.edge_index[1, data.edge_index[0] == node]
# Append the neighbors to the list of one-hop neighborhoods.
one_hop_neighborhoods.append(neighbors.numpy())
# Detect and eliminate duplicate hyperedges.
unique_hyperedges = set()
hyperedges = []
for neighborhood in one_hop_neighborhoods:
# Sort the neighborhood to ensure consistent comparison.
neighborhood = tuple(sorted(neighborhood))
if neighborhood not in unique_hyperedges:
hyperedges.append(list(neighborhood))
unique_hyperedges.add(neighborhood)
Additionally we print the statictis associated with obtained incidence matrix
Now, we can load the loaded dataset
[5]:
# Calculate hyperedge statistics.
hyperedge_sizes = [len(he) for he in hyperedges]
min_size = min(hyperedge_sizes)
max_size = max(hyperedge_sizes)
mean_size = np.mean(hyperedge_sizes)
median_size = np.median(hyperedge_sizes)
std_size = np.std(hyperedge_sizes)
num_single_node_hyperedges = sum(np.array(hyperedge_sizes) == 1)
# Print the hyperedge statistics.
print("Hyperedge statistics: ")
print("Number of hyperedges without duplicated hyperedges", len(hyperedges))
print(f"min = {min_size}, ")
print(f"max = {max_size}, ")
print(f"mean = {mean_size}, ")
print(f"median = {median_size}, ")
print(f"std = {std_size}, ")
print(f"Number of hyperedges with size equal to one = {num_single_node_hyperedges}")
Hyperedge statistics:
Number of hyperedges without duplicated hyperedges 2581
min = 1,
max = 168,
mean = 4.003099573808601,
median = 3.0,
std = 5.327622607829558,
Number of hyperedges with size equal to one = 412
[6]:
max_edges = len(hyperedges)
incidence_1 = np.zeros((x_0s.shape[0], max_edges))
for col, neighibourhood in enumerate(hyperedges):
for row in neighibourhood:
incidence_1[row, col] = 1
assert all(incidence_1.sum(0) > 0) is True, "Some hyperedges are empty"
assert all(incidence_1.sum(1) > 0) is True, "Some nodes are not in any hyperedges"
incidence_1 = torch.Tensor(incidence_1).to_sparse_coo()
Creating a neural network#
Define the network that initializes the base model and sets up the readout operation. Different downstream tasks might require different pooling procedures.
[7]:
class Network(torch.nn.Module):
"""Network class that initializes the base model and readout layer.
Base model parameters:
----------
Reqired:
in_channels : int
Dimension of the input features.
hidden_channels : int
Dimension of the hidden features.
Optitional:
**kwargs : dict
Additional arguments for the base model.
Readout layer parameters:
----------
out_channels : int
Dimension of the output features.
task_level : str
Level of the task. Either "graph" or "node".
"""
def __init__(
self, in_channels, hidden_channels, out_channels, task_level="graph", **kwargs
):
super().__init__()
# Define the model
self.base_model = UniGCNII(
in_channels=in_channels, hidden_channels=hidden_channels, **kwargs
)
# Readout
self.linear = torch.nn.Linear(hidden_channels, out_channels)
self.out_pool = task_level == "graph"
def forward(self, x_0, incidence_1):
# Base model
x_0, x_1 = self.base_model(x_0, incidence_1)
# Pool over all nodes in the hypergraph
x = torch.max(x_0, dim=0)[0] if self.out_pool is True else x_0
return self.linear(x)
Initialize the model
[8]:
# Base model hyperparameters
in_channels = x_0s.shape[1]
hidden_channels = 128
n_layers = 2
mlp_num_layers = 1
input_drop = 0.5
# Readout hyperparameters
out_channels = torch.unique(y).shape[0]
task_level = "graph" if out_channels == 1 else "node"
model = Network(
in_channels=in_channels,
hidden_channels=hidden_channels,
out_channels=out_channels,
n_layers=n_layers,
input_drop=input_drop,
task_level=task_level,
).to(device)
Training the neural network#
First, we specify the hyperparameters of the training process.
Note: The number of epochs below have been kept low to facilitate debugging and testing. Real use cases should likely require more epochs.
[9]:
num_epochs = 5
test_interval = 5
Next, we can generate the corresponding model, optimizer, and loss function with corresponding sizes.
[10]:
# Optimizer and loss
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# Categorial cross-entropy loss
loss_fn = torch.nn.CrossEntropyLoss()
# Accuracy
def acc_fn(y, y_hat):
return (y == y_hat).float().mean()
Now, we are ready to train the created model and evaluate the performance on the validation set.
[11]:
x_0s = torch.tensor(x_0s)
x_0s, incidence_1, y = (
x_0s.float().to(device),
incidence_1.float().to(device),
torch.tensor(y, dtype=torch.long).to(device),
)
/tmp/ipykernel_7355/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).
x_0s = torch.tensor(x_0s)
/tmp/ipykernel_7355/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).
torch.tensor(y, dtype=torch.long).to(device),
[12]:
for epoch in range(num_epochs):
# set model to training mode
model.train()
y_hat = model(x_0s, incidence_1)
loss = loss_fn(y_hat[train_mask], y[train_mask])
loss.backward()
optimizer.step()
optimizer.zero_grad()
if epoch % test_interval == 0:
model.eval()
y_hat = model(x_0s, incidence_1)
train_loss = loss_fn(y_hat[train_mask], y[train_mask])
loss = loss_fn(y_hat[test_mask], y[test_mask])
print(
f"Epoch: {epoch} \
Train_loss: {train_loss:.4f}, Train_acc: {acc_fn(y_hat[train_mask].argmax(1), y[train_mask]):.4f} \
Test_loss: {loss:.4f}, Test_acc: {acc_fn(y_hat[test_mask].argmax(1), y[test_mask]):.4f}",
flush=True,
)
Epoch: 0 Train_loss: 6.3311, Train_acc: 0.1429 Test_loss: 8.4650, Test_acc: 0.1430
Epoch: 5 Train_loss: 1.7255, Train_acc: 0.6000 Test_loss: 1.7909, Test_acc: 0.4460
Epoch: 10 Train_loss: 1.4779, Train_acc: 0.6714 Test_loss: 1.6235, Test_acc: 0.5080
Epoch: 15 Train_loss: 1.2046, Train_acc: 0.7786 Test_loss: 1.5192, Test_acc: 0.5790
Epoch: 20 Train_loss: 0.8618, Train_acc: 0.8500 Test_loss: 1.4219, Test_acc: 0.6350
Epoch: 25 Train_loss: 0.6326, Train_acc: 0.8643 Test_loss: 1.4752, Test_acc: 0.6700
[ ]: