Graph Attention Network (GAT) on Cora
Author: K3-Node Team
Backend: Multi-Backend
Dataset: Cora (Planetoid)
Description: Classify papers in the Cora citation network by topic.
Graph Attention Network (GAT) on Cora
Classify papers in the Cora citation network by topic. A GAT (Veličković et al., 2018) learns how much attention each paper should pay to each of the papers it is linked to, using 8 attention heads in the first layer.
Same model as PyG's examples/gat.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 GATConv
class GAT(keras.Model):
def __init__(self, in_channels, hidden_channels, out_channels, heads):
super().__init__()
self.dropout = keras.layers.Dropout(0.6)
self.conv1 = GATConv(in_channels, hidden_channels, heads=heads, dropout=0.6)
self.conv2 = GATConv(hidden_channels * heads, out_channels, heads=1, concat=False, dropout=0.6)
def call(self, data, training=False):
x = self.dropout(data.x, training=training)
x = ops.elu(self.conv1(x, data.edge_index, training=training))
x = self.dropout(x, training=training)
return self.conv2(x, data.edge_index, training=training)
model = GAT(dataset.num_features, hidden_channels=8, out_channels=dataset.num_classes, heads=8)
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.005, 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,
)