Attention-based GNN (AGNN) on Cora
Author: K3-Node Team
Backend: Multi-Backend
Dataset: Cora (Planetoid)
Description: Classify papers in the Cora citation network by topic.
Attention-based GNN (AGNN) on Cora
Classify papers in the Cora citation network by topic. AGNN (Thekumparampil et al., 2018) replaces fully-connected layers by attention-based propagation: each paper averages its neighbors, weighted by how similar they are.
Same model as PyG's examples/agnn.py.
Install K3-Node, then choose a backend: "tensorflow", "torch" or "jax"
Load the data
data holds one graph: node features x, edges edge_index, labels y, and masks marking the training, validation and test nodes.
import keras
from keras import ops
from k3_node.datasets import Planetoid
from k3_node.loader import FullGraphDataset
from k3_node.transforms import NormalizeFeatures
dataset = Planetoid("data/Planetoid", name="Cora", transform=NormalizeFeatures())
data = dataset[0]
print(data)
Define the model
from k3_node.layers import AGNNConv
class AGNN(keras.Model):
def __init__(self, in_channels, out_channels):
super().__init__()
self.dropout = keras.layers.Dropout(0.5)
self.lin1 = keras.layers.Dense(16, activation="relu")
self.prop1 = AGNNConv(requires_grad=False)
self.prop2 = AGNNConv(requires_grad=True)
self.lin2 = keras.layers.Dense(out_channels)
def call(self, data, training=False):
x = self.dropout(data.x, training=training)
x = self.lin1(x)
x = self.prop1(x, data.edge_index)
x = self.prop2(x, data.edge_index)
x = self.dropout(x, training=training)
return self.lin2(x)
model = AGNN(dataset.num_features, dataset.num_classes)
Train
FullGraphDataset feeds the whole graph to Keras; mask selects which nodes count in the loss and the accuracy.
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=0.01, weight_decay=0.0005),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
weighted_metrics=["accuracy"],
)
model.fit(
FullGraphDataset(data, mask="train_mask"),
validation_data=FullGraphDataset(data, mask="val_mask"),
epochs=200,
verbose=2,
)