Skip to content

Graph Convolutional Network (GCN) on Cora

Author: K3-Node Team
Backend: Multi-Backend
Dataset: Cora (Planetoid)
Description: Classify scientific papers in the Cora citation network into 7 topics.

View in Colab   GitHub source


Graph Convolutional Network (GCN) on Cora

Classify scientific papers in the Cora citation network into 7 topics. Each paper is a node with a bag-of-words feature vector, and citations are edges. Only 140 papers are labeled; a GCN (Kipf & Welling, 2017) learns from these labels together with the citation links to predict the topic of every other paper.

Same model and settings as PyG's examples/gcn.py.

Install K3-Node, then choose a backend: "tensorflow", "torch" or "jax"

!pip install k3-node[examples]
import os
os.environ["KERAS_BACKEND"] = "tensorflow"

Load the data

data holds one graph: node features x, citation links 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.layers import GCNConv
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

Two GCN layers with dropout. training is passed to Dropout so it is only active while training.

class GCN(keras.Model):
    def __init__(self, in_channels, hidden_channels, out_channels):
        super().__init__()
        self.dropout = keras.layers.Dropout(0.5)
        self.conv1 = GCNConv(in_channels, hidden_channels)
        self.conv2 = GCNConv(hidden_channels, out_channels)

    def call(self, data, training=False):
        x = self.dropout(data.x, training=training)
        x = ops.relu(self.conv1(x, data.edge_index))
        x = self.dropout(x, training=training)
        return self.conv2(x, data.edge_index)


model = GCN(dataset.num_features, hidden_channels=16, out_channels=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=5e-4),
    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,
)

Evaluate

loss, accuracy = model.evaluate(FullGraphDataset(data, mask="test_mask"), verbose=0)
print(f"Test accuracy: {accuracy:.4f}")