Skip to content

Simple Graph Convolution (SGC) on Cora

Author: K3-Node Team
Backend: Multi-Backend
Dataset: Cora (Planetoid)
Description: Classify papers in the Cora citation network by topic.

View in Colab   GitHub source


Simple Graph Convolution (SGC) on Cora

Classify papers in the Cora citation network by topic. SGC (Wu et al., 2019) removes the non-linearities of a GCN: features are smoothed over 2-hop neighborhoods once, then a single linear classifier is trained.

Same model as PyG's examples/sgc.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, 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

dataset = Planetoid("data/Planetoid", name="Cora")
data = dataset[0]
print(data)

Define the model

from k3_node.layers import SGConv


class SGC(keras.Model):
    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.conv = SGConv(in_channels, out_channels, K=2, cached=True)

    def call(self, data):
        return self.conv(data.x, data.edge_index)


model = SGC(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.2, weight_decay=0.005),
    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=100,
    verbose=2,
)

Evaluate

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