Sam Austinon November 18, 202614 min read

Link Prediction in Python: Predict Missing Connections in a Network

Link Prediction in Python: Predict Missing Connections in a Network
Contents

Figure 1: Link Prediction in Python: Predict Missing Connections in a Network — the missing edge is the answer, so every evaluation decision is really a decision about how much of the answer you left visible

Your social app suggests "people you may know". A biologist guesses which proteins interact. A librarian predicts which papers should cite each other. All three solve the same problem: given a graph, which connections are missing or about to appear?

That is link prediction, and the surprising part is how far a one-line heuristic gets you before any neural network enters the picture. I ran the heuristics in this article on Karate Club across 20 splits, and the numbers are less flattering than the folklore. They also collapse in a very specific, instructive way once you make the test honest.

Two Versions of the Same Problem

  • Missing links (static): hide some existing edges and ask the model to find them again.
  • Future links (temporal): see the graph at time T and predict which edges appear by T+1.

The temporal version mirrors reality best, because you train on the past and test on the future. The static version works when you lack timestamps, but you must hide edges carefully, as the leakage section below shows.

The Core Setup: Hide Edges, Then Rank Pairs

Every link prediction experiment follows this pattern:

  1. Split the real edges into training edges and held-out test edges.
  2. Build the training graph from training edges only.
  3. Sample negatives — pairs of nodes with no edge between them.
  4. Score each positive and negative pair using only the training graph.
  5. Measure how well the scores separate positives from negatives.

The golden rule: the training graph must not contain any test edge. Break it and your model peeks at the answers. A suspiciously perfect AUC is usually this rule being broken, not a breakthrough.

Heuristics: Free, Fast, and Surprisingly Strong

Heuristics score a node pair from graph structure alone, with no training at all. The classics:

  • Common neighbours — count the friends two people share.
  • Jaccard coefficient — shared neighbours divided by combined neighbours, so high-degree nodes do not dominate.
  • Adamic-Adar — shared neighbours count more when those neighbours have few connections. Sharing a rare friend says more than sharing a celebrity.
  • Resource allocation — like Adamic-Adar but harsher: it weights a shared neighbour by 1/degree instead of 1/log(degree).
  • Preferential attachment — multiply the two nodes' degrees, on the idea that popular nodes attract more links.

These cost nothing to compute and are hard to beat on many networks, which is why they are the baseline every neural model has to clear [1].

Python Example 1: Heuristics With NetworkX

This is the code I ran, on NetworkX 3.7. It scores all five heuristics and prints AUC and average precision:

import random
import numpy as np
import networkx as nx
from sklearn.metrics import roc_auc_score, average_precision_score

def split_edges(G, test_frac=0.2, seed=0):
    rng = random.Random(seed)
    edges = list(G.edges)
    rng.shuffle(edges)
    test_pos = edges[: int(len(edges) * test_frac)]
    G_train = G.copy()
    G_train.remove_edges_from(test_pos)          # hide test edges from the graph
    return G_train, test_pos

def sample_negatives(G, k, seed=0):
    """Sample k node pairs that are NOT edges in the FULL graph G."""
    rng, nodes, neg = random.Random(seed), list(G.nodes), set()
    tries = 0
    while len(neg) < k and tries < 10_000_000:   # guard against an impossible k
        tries += 1
        u, v = rng.sample(nodes, 2)
        if not G.has_edge(u, v) and (v, u) not in neg:
            neg.add((u, v))
    return list(neg)

def score_pairs(G_train, pairs, method):
    if method == "common_neighbors":
        return np.array([len(list(nx.common_neighbors(G_train, u, v))) for u, v in pairs])
    fn = {
        "jaccard": nx.jaccard_coefficient,
        "adamic_adar": nx.adamic_adar_index,
        "resource_allocation": nx.resource_allocation_index,
        "pref_attach": nx.preferential_attachment,
    }[method]
    return np.array([s for _, _, s in fn(G_train, pairs)])   # yields (u, v, score)

G = nx.karate_club_graph()                        # swap in your own graph
G_train, test_pos = split_edges(G, test_frac=0.2, seed=0)
test_neg = sample_negatives(G, len(test_pos), seed=0)    # negatives from the FULL graph

pairs = test_pos + test_neg
y = np.r_[np.ones(len(test_pos)), np.zeros(len(test_neg))]

for m in ["common_neighbors", "jaccard", "adamic_adar",
          "resource_allocation", "pref_attach"]:
    s = score_pairs(G_train, pairs, m)
    print(f"{m:20s} AUC {roc_auc_score(y, s):.3f} | AP {average_precision_score(y, s):.3f}")

Two details in that code carry most of the correctness.

First, negatives come from the full graph. If you sampled them from the training graph, a held-out true edge could be drawn as a "negative" — you would be training against the answer.

Second, nx.common_neighbor_centrality is not the same thing as counting shared neighbours. NetworkX has both. On Karate Club, for a pair with one common neighbour, plain counting returns 1 and common_neighbor_centrality returns 4.2. Pick deliberately; the names are close enough that this is an easy mistake.

I also added a tries counter to sample_negatives. The obvious version loops until it has k negatives, which hangs forever on a dense graph where k exceeds the number of available non-edges. The guard turns an infinite loop into a short list you can notice.

What the Heuristics Actually Score on Karate Club

Karate Club has 34 nodes, 78 edges, and density 0.139 — small, dense, and dominated by two hubs. One split tells you nothing, so I ran 20 and averaged:

Method AUC AP
Preferential attachment 0.725 ± 0.065 0.745 ± 0.072
Resource allocation 0.711 ± 0.059 0.732 ± 0.059
Adamic-Adar 0.705 ± 0.060 0.727 ± 0.057
Common neighbours 0.670 ± 0.061 0.652 ± 0.058
Jaccard 0.602 ± 0.089 0.581 ± 0.083

Two results run against the usual advice.

Jaccard is the worst of the five, at 0.602 — barely above chance. Jaccard divides by the union of the two neighbourhoods, so it punishes exactly the pairs Karate Club rewards: links to its hubs. The advice to "start with Adamic-Adar or Jaccard" is half right on this graph.

Preferential attachment wins, at 0.725 — the dumbest measure in the list. On a graph with two dominant hubs, "popular nodes get more popular" is the true generative rule, and the model that encodes it directly wins.

That is the real lesson of the table: the heuristic that matches your graph's generative process beats the heuristic that is more sophisticated. It is also why you run the comparison instead of trusting a ranking.

Measuring Success: AUC Isn't Enough

The usual metrics:

  • AUC-ROC — the chance a random positive outscores a random negative.
  • Average precision — area under the precision-recall curve.
  • Hits@K — the fraction of true edges landing in the top K predictions.
  • MRR — the mean of 1/rank for the true edge among competing candidates.

AUC is the weakest of the four for this task, and the most reported. It answers a question nobody asks in production: if I picked one true edge and one non-edge at random, would the true one score higher? Recommendation systems show a shortlist, so Hits@K and MRR match deployment far better [1].

Here is a Hits@K implementation, which I ran — it ranks each positive against its own pool of negatives:

def hits_at_k(pos_scores, neg_scores_per_pos, k=10):
    """neg_scores_per_pos: one array of negative scores for each positive."""
    hits = 0
    for p, negs in zip(pos_scores, neg_scores_per_pos):
        rank = 1 + int((negs >= p).sum())      # ties count against you (pessimistic)
        hits += rank <= k
    return hits / len(pos_scores)

Scoring Adamic-Adar against 100 corrupted pairs per positive, over 10 splits:

Hits@10: 0.320
Hits@50: 0.673

A third of true edges reach the top 10, and two thirds reach the top 50. That is a very different story from an AUC of 0.705, and it is the honest one.

The Biggest Pitfall: Easy Negatives

This is where link prediction results go wrong most often, and it is worth its own experiment.

The mechanism: standard evaluation samples random node pairs as negatives. On a sparse graph, a random pair almost always has no common neighbour at all, so any neighbour-counting score separates it from a real edge without learning anything. The metric measures the sampling, not the model.

In my Karate Club run, 60% of random negatives (9 of 15) shared zero neighbours with the positive. And Karate Club is dense by real-world standards.

So I re-ran the same experiment with hard negatives — non-edges that share at least one neighbour in the training graph, which is the fix the benchmarking literature calls HeaRT (Heuristic Related Sampling Technique) [1]:

Method AUC, random negatives AUC, hard negatives AP, random AP, hard
Common neighbours 0.670 0.416 0.652 0.526
Adamic-Adar 0.705 0.503 0.727 0.624
Resource allocation 0.711 0.513 0.732 0.633
Jaccard 0.602 0.241 0.581 0.421

Every heuristic collapses, and two of them fall to or below chance. Adamic-Adar drops from 0.705 to 0.503 — from "useful" to "a coin flip". Jaccard drops to 0.241, which means it ranks hard negatives above true edges.

Why Jaccard inverts is instructive. A hard negative is a pair that shares a neighbour but is not linked, which usually means both nodes have small neighbourhoods. Jaccard divides by the size of the union, so small neighbourhoods produce large Jaccard scores — the measure rewards the negatives more than the positives.

What survives: average precision stays well above chance for the degree-aware measures (0.624 for Adamic-Adar), so the signal is real, just far weaker than the random-negative number suggested. AUC near 0.5 with AP near 0.63 is what "some signal, badly ranked" looks like.

What to do about it:

  1. Sample hard negatives — non-edges sharing a neighbour, or within two hops.
  2. Report ranking metrics (MRR, Hits@K) beside AUC.
  3. Tune baselines seriously — the benchmarking paper's first pitfall is baselines reported below their real performance [1].
  4. State your split and negative protocol, so someone can reproduce it.

Python Example 2: A Graph Autoencoder in PyTorch Geometric

For learned embeddings, the classic neural baseline is the graph autoencoder (GAE): a GCN encoder produces node embeddings and a dot-product decoder scores a pair [2]. PyTorch Geometric is not installed in my environment, so I could not run this — check the API against the current docs:

import torch
import torch.nn.functional as F
import torch_geometric.transforms as T
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import GCNConv, GAE

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

transform = T.Compose([
    T.NormalizeFeatures(),
    T.ToDevice(device),
    T.RandomLinkSplit(num_val=0.05, num_test=0.10, is_undirected=True,
                      split_labels=True, add_negative_train_samples=False),
])
dataset = Planetoid(root="data/Cora", name="Cora", transform=transform)
train_data, val_data, test_data = dataset[0]

class GCNEncoder(torch.nn.Module):
    def __init__(self, in_ch, hidden, out_ch):
        super().__init__()
        self.conv1 = GCNConv(in_ch, hidden)
        self.conv2 = GCNConv(hidden, out_ch)

    def forward(self, x, edge_index):
        return self.conv2(F.relu(self.conv1(x, edge_index)), edge_index)

model = GAE(GCNEncoder(dataset.num_features, 64, 32)).to(device)
opt = torch.optim.Adam(model.parameters(), lr=0.01)

def train():
    model.train(); opt.zero_grad()
    z = model.encode(train_data.x, train_data.edge_index)
    loss = model.recon_loss(z, train_data.pos_edge_label_index)   # samples negatives internally
    loss.backward(); opt.step()
    return float(loss)

@torch.no_grad()
def test(data):
    model.eval()
    z = model.encode(data.x, data.edge_index)         # message passing uses only allowed edges
    return model.test(z, data.pos_edge_label_index, data.neg_edge_label_index)  # (AUC, AP)

for epoch in range(1, 201):
    loss = train()
    if epoch % 20 == 0:
        auc, ap = test(val_data)
        print(f"epoch {epoch:3d} | loss {loss:.3f} | val AUC {auc:.3f} AP {ap:.3f}")

print("test AUC, AP:", test(test_data))

What RandomLinkSplit buys you: it hides validation and test edges from the training graph, and is_undirected=True keeps both directions of each hidden edge in the same split. That last flag is the difference between a valid result and a leak, and it is the single most common bug in link prediction notebooks.

Cora's random negatives are easy, so do not be shocked by a high AUC. Compare the GAE against Adamic-Adar on the same split, then repeat with hard negatives. If the neural model cannot beat the heuristic under the harder test, it is not earning its complexity.

For stronger learned approaches, SEAL is the reference point: it extracts the local subgraph around each candidate pair and runs a GNN over that, which lets it learn heuristics rather than apply one [3].

Once the heuristics work, stack them. For each candidate pair, compute several scores — common neighbours, Jaccard, Adamic-Adar, preferential attachment, shortest-path length, degrees — and train a classifier such as logistic regression or gradient boosting.

Two rules keep this honest:

  1. Compute training features on a graph that excludes the training target edges too, not just the test edges. Otherwise the features encode the labels.
  2. Split by time when you can. Train on edges that appeared in one window and test on edges from a later one.

Leakage Checklist

Run through this before you trust any number:

  • Test edges stay out of the training graph, including the message-passing graph for GNNs.
  • Both directions of an undirected edge land in the same split.
  • Negatives come from non-edges of the full graph, so no held-out positive sneaks in as a negative.
  • Features for training pairs exclude their own target edge.
  • Embeddings train on the training graph only. Random walks over the full graph already contain your test edges.
  • Node features cannot encode the label. An edge count computed on the full graph leaks.
  • Time order is respected in temporal tasks.
  • Duplicate and self-loop edges do not straddle splits.

A Practical Protocol

  1. Define the task: static missing links, or temporal future links.
  2. Split properly, with a temporal split if timestamps exist.
  3. Run heuristic baselines — Adamic-Adar, resource allocation, Jaccard, preferential attachment.
  4. Add a supervised model on heuristic features.
  5. Try a GAE or GNN, on the same splits and the same negatives.
  6. Evaluate with hard negatives and ranking metrics beside AUC.
  7. Run several seeds and report mean and spread.
  8. Inspect the failures. The true links that everything misses usually sit in sparse regions with no shared neighbours, where structural heuristics have nothing to count.

Common Pitfalls

  • Letting test edges into the training graph. The classic leak, and the one that produces a 0.99 AUC.
  • Sampling negatives from the training graph. You can label a hidden true edge as a non-edge.
  • Relying on random negatives only. They were 60% neighbour-free in my run, so they measure the sampler.
  • Reporting only AUC. Add MRR and Hits@K; my Adamic-Adar went from 0.705 AUC to 0.320 Hits@10.
  • Skipping tuned heuristic baselines. Preferential attachment beat Adamic-Adar on Karate Club.
  • Using one random split. Spread across 20 splits was ±0.06 AUC.
  • Training embeddings on the full graph. Train on the training graph only.
  • Ignoring time. A random split of temporal data lets the model read the future.
  • Comparing against untuned baselines. Under-reported baselines are the first pitfall in the benchmarking literature [1].

Best Book to Read

CoverBookDescriptionGet it
Cover of “Networks” Networksby Mark Newman the standard reference for the measures in this article, from degree distributions to similarity indices and the structure that makes one heuristic beat another. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read it alongside the code, not instead of it. The book explains why preferential attachment wins on a hub-dominated graph; only the experiment tells you that your graph is one.

Wrapping Up

Link prediction comes down to hiding edges honestly, scoring candidate pairs, and judging results with realistic negatives and ranking metrics.

The numbers from my run: on Karate Club with random negatives, preferential attachment reached 0.725 AUC, Adamic-Adar 0.705, Jaccard 0.602. With hard negatives, Adamic-Adar fell to 0.503 and Jaccard to 0.241 — the same models, a fairer test, a completely different conclusion.

So run the NetworkX example on a graph you care about this week, then re-run it with hard negatives. If your scores collapse, you just discovered how much easy negatives were flattering you. If they hold, you have a result that survives a harder test.

Frequently Asked Questions

Link prediction estimates whether an edge exists between two nodes, or will exist soon. The static version hides some real edges and asks the model to recover them; the temporal version trains on the graph at time T and predicts edges that appear by T+1. Both come down to scoring candidate pairs.

On Karate Club across 20 splits, preferential attachment scored highest at 0.725 AUC, followed by resource allocation at 0.711 and Adamic-Adar at 0.705. Jaccard was worst at 0.602. The ordering is graph-dependent, which is why you should run the comparison rather than assume.

Because random negatives are easy. In my Karate Club run, 60% of random negatives shared no neighbour with the positive, so any neighbour-counting score separates them trivially. When I required each negative to share at least one neighbour, Adamic-Adar fell from 0.705 to 0.503 AUC and Jaccard fell to 0.241, below chance.

Report both. AUC answers whether a random positive outranks a random negative, which is not how recommendations are consumed. Hits@K and MRR answer whether the true edge lands in the shortlist you would actually show, so they match deployment better and are far less flattering.

How do I stop test edges leaking into training?

Keep every held-out edge out of the graph used for scoring, keep both directions of an undirected edge in the same split, and draw negatives from the full graph so a hidden true edge cannot be labelled a non-edge. For temporal data, split by time instead of at random.

Sources

  • [1] Li et al., Evaluating Graph Neural Networks for Link Prediction: Current Pitfalls and New Benchmarking — under-reported baselines, inconsistent splits, easy negatives, and the HeaRT hard-negative protocol: arxiv.org
  • [2] Kipf and Welling, Variational Graph Auto-Encoders — the GCN encoder with an inner-product decoder for link prediction: arxiv.org
  • [3] Zhang and Chen, Link Prediction Based on Graph Neural Networks — SEAL, which learns a heuristic from the local enclosing subgraph: arxiv.org
  • [4] Grover and Leskovec, node2vec: Scalable Feature Learning for Networks — random-walk embeddings, and why walks over the full graph leak test edges: arxiv.org

What are You Looking For?

esc