TGraphX › Insights › Semi-Supervised Node Classification in TGraphX: Label Propagation, GCN and Self-Training
← Back to Insights

Semi-Supervised Node Classification in TGraphX: Label Propagation, GCN and Self-Training

Topic: GNN architectures and learning tasks

Semi-supervised learning on graphs is one of the clearest examples of how graph structure can amplify a small amount of labeled data. A node classification task might have thousands of nodes but only a handful of labels per class. A features-only classifier learns from those labeled nodes alone. Graph methods also use the edges: labeled nodes are connected to unlabeled ones, and information travels between them through label propagation or message passing.

This article implements three methods on the same data (label propagation, a two-layer GCN, and self-training), with masks that cannot overlap, validation-based model selection, and results measured over several splits.

Examples tested with TGraphX 1.5.1 on CPU.


What Semi-Supervised Learning on Graphs Means

In the standard setup you have one graph with N nodes. A small set of nodes has labels (the training set). The goal is to predict labels for the other nodes, including the validation and test sets.

The key difference from ordinary supervised classification is that the unlabeled nodes are not hidden from the model. It sees the full topology and all node features during training, but the loss uses only the training labels. Graph methods then rely on an assumption about structure, usually homophily: connected nodes tend to share labels.


Prerequisites

This article assumes familiarity with:

  • GNN message passing basics
  • The TGraphX Graph object
  • PyTorch training loops

For background on graph construction and feature handling, see the MNIST as a graph tutorial.


Setting Up Train/Val/Test Masks

All nodes stay in one graph, and boolean masks select which nodes contribute to the loss, to model selection and to the final score. Two mistakes are easy to make here:

  • Drawing a separate torch.randperm for each split. The splits then overlap.
  • Calling a random sample "20 per class" when nothing enforces it.

Both are avoided below: one permutation, and training nodes picked class by class. The data is a synthetic stand-in for a citation network, with three properties chosen on purpose: edges are mostly within a class, node features carry a weak class signal, and neither source alone is enough.

python
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import Graph, GCNConv, check_leakage
from tgraphx.estimators import EarlyStopping
from tgraphx.mining import label_propagation
from tgraphx.reproducibility import set_seed

set_seed(0)
NUM_CLASSES = 5

def make_graph(n=2000, d=64, p_in=0.0075, p_out=0.0008, signal=0.2, seed=0):
    gen = torch.Generator().manual_seed(seed)
    y = torch.randint(0, NUM_CLASSES, (n,), generator=gen)
    u, v = torch.triu_indices(n, n, offset=1)
    prob = torch.where(y[u] == y[v], p_in, p_out)
    keep = torch.rand(u.numel(), generator=gen) < prob
    e = torch.stack([u[keep], v[keep]])
    prototypes = torch.randn(NUM_CLASSES, d, generator=gen)
    x = signal * prototypes[y] + torch.randn(n, d, generator=gen)
    return Graph(node_features=x, edge_index=torch.cat([e, e.flip(0)], dim=1), y=y)

def make_split(y, seed, per_class=20, n_val=500, n_test=1000):
    perm = torch.randperm(y.numel(), generator=torch.Generator().manual_seed(seed))
    train = torch.zeros(y.numel(), dtype=torch.bool)
    for c in range(NUM_CLASSES):
        train[perm[y[perm] == c][:per_class]] = True      # per_class nodes of class c
    rest = perm[~train[perm]]                             # same permutation, train removed
    val, test = torch.zeros_like(train), torch.zeros_like(train)
    val[rest[:n_val]] = True
    test[rest[n_val:n_val + n_test]] = True
    return train, val, test

g = make_graph()
train_mask, val_mask, test_mask = make_split(g.y, seed=0)

# Raises LeakageError if any two masks share a node. Use keyword arguments.
report = check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
print(report["counts"])                          # {'train': 100, 'val': 500, 'test': 1000}
print(torch.bincount(g.y[train_mask]).tolist())  # [20, 20, 20, 20, 20]
print(f"{(g.y[g.edge_index[0]] == g.y[g.edge_index[1]]).float().mean().item():.2f}")  # 0.71 same-class edges

check_leakage only compares node masks. It cannot detect labels that leak through features, edges or your training code. See masks, splits and leakage.

Using Cora instead

The usual Cora setup (the Planetoid split of Yang et al., 2016) has 2,708 nodes, 7 classes, 20 labeled training nodes per class, 500 validation nodes and 1,000 test nodes. Load it with PyTorch Geometric and pass the masks to Graph yourself:

python
from torch_geometric.datasets import Planetoid
from tgraphx import Graph, check_leakage

data = Planetoid(root="data/Planetoid", name="Cora")[0]
cora = Graph(node_features=data.x, edge_index=data.edge_index, y=data.y,
             train_mask=data.train_mask, val_mask=data.val_mask, test_mask=data.test_mask)
check_leakage(cora)

tgraphx.load_dataset("cora") also goes through PyTorch Geometric, but in 1.5.1 its conversion to a TGraphX Graph does not carry the train, validation and test masks. For a full Cora workflow, see applying TGraphX to citation networks.


Approach 1: Label Propagation

Label propagation is the classical structure-only baseline. It diffuses the one-hot labels of the training nodes over the graph and never looks at node features. The TGraphX signature is label_propagation(edge_index, num_nodes, y, mask, num_classes, alpha=0.9, max_iter=50, tol=1e-4). Only the entries of y selected by mask are read.

python
def accuracy(pred, y, mask):
    return (pred[mask] == y[mask]).float().mean().item()

def run_label_propagation(g, train_mask, val_mask, alphas=(0.5, 0.8, 0.9, 0.99)):
    best = None
    for alpha in alphas:
        scores = label_propagation(g.edge_index, g.num_nodes, g.y, train_mask, NUM_CLASSES,
                                   alpha=alpha, max_iter=200, tol=0.0)
        val_acc = accuracy(scores.argmax(1), g.y, val_mask)
        if best is None or val_acc > best[0]:
            best = (val_acc, alpha, scores)
    return best

val_acc, alpha, scores = run_label_propagation(g, train_mask, val_mask)
print(f"alpha={alpha} val={val_acc:.3f} test={accuracy(scores.argmax(1), g.y, test_mask):.3f}")
# alpha=0.99 val=0.686 test=0.656

alpha is the weight on the propagated neighbor scores; 1 - alpha is the weight that keeps pulling toward the seed labels. We pass tol=0.0 because the default tolerance can stop the loop before labels reach most of a large graph. Nodes with no path to any seed get an all-zero row, and argmax then reports class 0. Both points are explained in the label propagation tutorial.


Approach 2: GCN as Semi-Supervised Learning

Kipf and Welling (2017) presented the graph convolutional network explicitly as a semi-supervised method. Each layer applies a normalized neighborhood average (derived as a first-order approximation of spectral graph convolution) followed by a learned linear map. Propagation never uses labels; labels enter only through the loss on training nodes. Unlabeled nodes still matter, because their features flow into the representations of labeled nodes and their neighbors.

TGraphX ships GCNConv(in_dim, out_dim) for vector features [N, D].

python
class GCN(nn.Module):
    def __init__(self, in_dim, hidden, num_classes):
        super().__init__()
        self.conv1 = GCNConv(in_dim, hidden)
        self.conv2 = GCNConv(hidden, num_classes)

    def forward(self, x, edge_index):
        h = F.relu(self.conv1(x, edge_index))
        h = F.dropout(h, p=0.5, training=self.training)
        return self.conv2(h, edge_index)                 # logits

def train_model(model, g, targets, loss_mask, val_mask, epochs=200, patience=30):
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
    stopper = EarlyStopping(patience=patience, mode="min")   # "min" because we monitor a loss
    best_state = None
    for _ in range(epochs):
        model.train()
        optimizer.zero_grad()
        logits = model(g.x, g.edge_index)                    # forward pass uses all nodes
        F.cross_entropy(logits[loss_mask], targets[loss_mask]).backward()
        optimizer.step()

        model.eval()
        with torch.no_grad():
            val_loss = F.cross_entropy(model(g.x, g.edge_index)[val_mask], g.y[val_mask]).item()
        stop = stopper.step(val_loss)
        if stopper.counter == 0:                             # new best: keep these weights
            best_state = {k: v.clone() for k, v in model.state_dict().items()}
        if stop:
            break
    model.load_state_dict(best_state)
    model.eval()
    with torch.no_grad():
        return model(g.x, g.edge_index)

set_seed(0)
logits = train_model(GCN(64, 64, NUM_CLASSES), g, g.y, train_mask, val_mask)
print(f"GCN test={accuracy(logits.argmax(1), g.y, test_mask):.3f}")   # GCN test=0.854

Note that tgraphx.fit is not used here. It does not apply node masks, so on a single graph it would train on validation and test labels too.


Approach 3: Self-Training

Self-training (pseudo-labeling) trains on the labeled nodes, assigns predicted labels to unlabeled nodes where the model is confident, adds them to the training set and retrains.

One detail decides whether the result is valid: the added nodes must be trained on the predicted labels. If the loss is computed against g.y for them, the ground truth of unlabeled nodes, including test nodes, enters training and every later accuracy is meaningless.

python
def self_train(g, train_mask, val_mask, rounds=3, threshold=0.9):
    targets = g.y.clone()               # entries outside loss_mask are never used by the loss
    loss_mask = train_mask.clone()
    for _ in range(rounds):
        logits = train_model(GCN(64, 64, NUM_CLASSES), g, targets, loss_mask, val_mask)
        confidence, pseudo = logits.softmax(dim=1).max(dim=1)
        # never touch true training labels, and keep validation nodes out of training
        new = (confidence > threshold) & ~loss_mask & ~val_mask
        targets[new] = pseudo[new]      # predicted labels, NOT g.y
        loss_mask |= new
        print(f"  added {int(new.sum())} pseudo-labeled nodes")
    return train_model(GCN(64, 64, NUM_CLASSES), g, targets, loss_mask, val_mask)

set_seed(0)
logits = self_train(g, train_mask, val_mask)
print(f"self-training test={accuracy(logits.argmax(1), g.y, test_mask):.3f}")
# added 818, 146 and 44 pseudo-labeled nodes over the three rounds; self-training test=0.883

Test nodes may receive pseudo-labels here. Their true labels are never read, which is acceptable in a transductive study; if you also want to make a claim about nodes that training never saw, exclude them too. Pseudo-labels are added permanently, so an early confident mistake is never revisited.


Measured Comparison over Five Splits

One split is not enough to compare methods with 100 labels. The loop below draws five splits of the same graph. A features-only MLP is included to show what the edges add.

python
class MLP(nn.Module):
    def __init__(self, in_dim, hidden, num_classes):
        super().__init__()
        self.lin1 = nn.Linear(in_dim, hidden)
        self.lin2 = nn.Linear(hidden, num_classes)

    def forward(self, x, edge_index):                    # edge_index ignored on purpose
        h = F.dropout(F.relu(self.lin1(x)), p=0.5, training=self.training)
        return self.lin2(h)

results = {"MLP (features only)": [], "label propagation (edges only)": [],
           "GCN": [], "GCN + self-training": []}
for seed in range(5):
    tr, va, te = make_split(g.y, seed)
    check_leakage(train_mask=tr, val_mask=va, test_mask=te)
    set_seed(seed)
    mlp = train_model(MLP(64, 64, NUM_CLASSES), g, g.y, tr, va)
    _, _, lp = run_label_propagation(g, tr, va)
    set_seed(seed)
    gcn = train_model(GCN(64, 64, NUM_CLASSES), g, g.y, tr, va)
    set_seed(seed)
    st = self_train(g, tr, va)
    for name, out in zip(results, (mlp, lp, gcn, st)):
        results[name].append(accuracy(out.argmax(1), g.y, te))

for name, values in results.items():
    v = torch.tensor(values)
    print(f"{name:32s} {v.mean().item():.3f} +/- {v.std().item():.3f}")

Test accuracy (mean and standard deviation over the five splits) from our CPU run:

Method Test accuracy
MLP (features only) 0.539 ± 0.025
Label propagation (edges only) 0.627 ± 0.023
GCN 0.860 ± 0.010
GCN + self-training 0.886 ± 0.003

Read these numbers for what they are. The graph is synthetic, it was built so that features and structure are each weak and complementary, and its homophily is exactly what GCN and label propagation assume. Self-training benefits here because confident predictions are mostly correct on this data. None of this transfers automatically to a real dataset. The script is the useful part: run the same comparison on your graph.


Using GIN or Other Layers

TGraphX's tensor layers, including TensorGINLayer, expect spatial features [N, C, H, W]. For vector features, add two unit axes and flatten the output:

python
from tgraphx import TensorGINLayer

class GINNodeClassifier(nn.Module):
    def __init__(self, in_dim, hidden, num_classes):
        super().__init__()
        self.gin1 = TensorGINLayer(in_dim, hidden, train_eps=True, use_batchnorm=True)
        self.gin2 = TensorGINLayer(hidden, num_classes, train_eps=True)

    def forward(self, x, edge_index):
        x = x[:, :, None, None]                          # [N, D] -> [N, D, 1, 1]
        x = F.relu(self.gin1(x, edge_index))
        return self.gin2(x, edge_index).flatten(1)       # [N, num_classes]

gin = GINNodeClassifier(64, 64, NUM_CLASSES)
print(gin(g.x, g.edge_index).shape)                      # torch.Size([2000, 5])

GIN uses sum aggregation and was motivated by graph-level discrimination, so compare it with GCN rather than assuming it helps for node labels. GATv2Conv and APPNP accept [N, D] features directly.


Method Comparison

Method Uses features Uses edges Training Scoring nodes added later
Label propagation no yes no gradient training re-run propagation on the new graph
MLP yes no yes forward pass
GCN, GAT, GIN, GraphSAGE yes yes yes forward pass on a graph that contains them
Self-training as base model as base model several rounds as base model

A trained GNN has shared weights, so it can be applied to new nodes or a new graph with the same feature space. How well that works under a changed distribution has to be measured.


Inductive vs Transductive Settings

The setup in this article is transductive: test nodes, their features and their edges are visible during training, and only their labels are withheld. In inductive evaluation, test nodes are absent from the training graph and appear only at inference time. To simulate that, train on the subgraph without them and then run the model on the full graph.

Neighbor sampling, associated with GraphSAGE, is useful for large graphs and fits inductive workflows well. See neighbor sampling for large graphs. Sampling by itself does not make an evaluation inductive.


Limitations and Honest Notes

Transductive results do not describe new data. If nodes are added after training, evaluate that situation explicitly.

Label propagation assumes homophily. On heterophilic graphs, where connected nodes tend to have different labels, it propagates misleading information, and GCN-style averaging can also hurt.

Self-training is sensitive to the threshold and the number of rounds. Confidence calibration in GNNs is often poor (Wang et al., NeurIPS 2021, report that common GNNs tend to be under-confident), so a softmax threshold is not a reliability guarantee. Select the threshold on validation data.

The 20-labels-per-class benchmark setup is a convention. Real tasks differ in class balance, label noise and structure.


Reproducibility in Semi-Supervised Experiments

With very few labeled nodes, which nodes you pick can change results noticeably. This is why benchmark datasets ship fixed splits. When you create your own:

  1. Generate each split from its own seeded generator, as make_split does, so it does not depend on what ran before.
  2. Report the split strategy (random, stratified, fixed) and the number of labels per class.
  3. Run several seeds and report mean and standard deviation.

tgraphx.reproducibility.set_seed seeds the Python, NumPy and PyTorch generators; identical seeds are still not a guarantee of identical results across hardware. For an unstratified split, tgraphx.estimators.node_train_val_test_split(num_nodes, 0.8, 0.1, 0.1, seed=...) returns three disjoint boolean masks. See the GNN research reproducibility guide.


Measuring Semi-Supervised Performance Honestly

Accuracy can change substantially with the label rate, so state:

  • the number of labeled nodes per class, not just the total;
  • what the validation set was used for (early stopping, alpha, threshold);
  • whether test results were looked at before the design was final.

Note that 500 validation labels is five times the 100 training labels used here. A method that needs a large validation set is not really using only 100 labels, and your report should say so.


What This Article Builds On

This article assumes basic GNN message passing and the TGraphX Graph object. The mask-based setup is a foundational pattern in graph learning and a prerequisite for inductive evaluation and heterophilic graph learning. For sampling-based training, see the neighbor sampling guide.

The label propagation approach covered in the "Approach 1" section is the classical non-neural baseline. It is covered in more depth in the label propagation tutorial.


Frequently Asked Questions

What label rate counts as "semi-supervised"? There is no exact threshold. The widely used citation benchmarks label 20 nodes per class and treat the rest as unlabeled.

Does semi-supervised GNN learning work on heterophilic graphs? Standard averaging layers often struggle there, because they mix representations of nodes with different labels. Compare against a features-only model before concluding that the edges help.

Should I use dropout? It is common, since a small labeled set is easy to overfit; Kipf and Welling used 0.5 on the citation datasets. Treat it as a hyperparameter.

How do I get Cora as a TGraphX graph? Use PyTorch Geometric's Planetoid loader and construct a Graph with the three masks, as in "Using Cora instead" above.


References

  • Yang, Z., Cohen, W. W. and Salakhutdinov, R. (2016). Revisiting semi-supervised learning with graph embeddings. ICML.
  • Kipf, T. N. and Welling, M. (2017). Semi-supervised classification with graph convolutional networks. ICLR.
  • Wang, X., Liu, H., Shi, C. and Yang, C. (2021). Be confident! Towards trustworthy graph neural networks via confidence calibration. NeurIPS.