TGraphX › Insights › Link Prediction Scoring Functions: Jaccard, Adamic-Adar, Common Neighbors
← Back to Insights

Link Prediction Scoring Functions: Jaccard, Adamic-Adar, Common Neighbors

Topic: Graph mining, generation, optimization and RL

Link prediction asks whether a missing or future edge should exist between two nodes in a graph. It is one of the fundamental graph mining tasks, with applications in recommendation (friend suggestions), biological network completion (protein-protein interactions) and knowledge base completion. Before graph neural networks became common, classical scoring functions were the standard approach. Understanding what they compute, when they work and where they fail remains valuable, because they are the baselines any learned method should beat.

TGraphX provides these scorers in tgraphx.mining.link_prediction. This article covers the definitions, the exact call signature, a leakage-free evaluation, and two traps that change the numbers you report.

Examples tested with TGraphX 1.5.1, networkx and scikit-learn.


What Link Prediction Scoring Functions Do

A scoring function takes a pair of nodes (u, v) that are not currently connected and returns a number. A higher score means the pair is ranked as a more likely edge. The score is not a probability. These functions train no parameters: they read the neighborhoods of the two nodes in the observed graph.

That makes them interpretable and usable without any training labels. The cost is that they cannot learn complex patterns or use node features.

Below, N(u) is the set of neighbors of u.


Common Neighbors

Common Neighbors counts the nodes adjacent to both u and v:

CN(u, v) = |N(u) ∩ N(v)|

The intuition is direct: two people with many mutual friends are likely to know each other. In citation graphs, papers that cite many of the same references are likely related.

Common Neighbors does not normalize by degree, so high-degree nodes tend to get high scores with many partners.


Jaccard Coefficient

The Jaccard coefficient divides by the size of the union of both neighborhoods:

Jaccard(u, v) = |N(u) ∩ N(v)| / |N(u) ∪ N(v)|

The score lies between 0 and 1, where 1 means identical neighborhoods. This counteracts the degree bias of Common Neighbors: if a hub with 1,000 neighbors and a node with 10 neighbors share those 10, their score is 0.01, while two nodes with the same 10 neighbors and no others score 1. The flip side is that it can underrate links that involve hubs in heavy-tailed graphs.


Adamic-Adar and Resource Allocation

Adamic-Adar weights each shared neighbor w by the inverse logarithm of its degree:

AA(u, v) = Σ_{w ∈ N(u) ∩ N(v)} 1 / log |N(w)|

A shared neighbor with few connections is more informative than one connected to everyone. Adamic and Adar (2003) introduced this weighting to relate people through their web pages, and in Liben-Nowell and Kleinberg's study of co-authorship networks (2007) it was among the stronger neighborhood-based predictors.

Resource Allocation (Zhou, Lü and Zhang, 2009) is the same idea with a stronger penalty:

RA(u, v) = Σ_{w ∈ N(u) ∩ N(v)} 1 / |N(w)|

Note what is penalized: the degree of the shared neighbor w, not the degree of the endpoints u and v. Pairs of hubs can still score high because they have more shared neighbors.


Preferential Attachment

Preferential Attachment multiplies the two degrees:

PA(u, v) = |N(u)| · |N(v)|

It is motivated by the growth model of Barabási and Albert (1999), where new edges attach preferentially to high-degree nodes. It needs no shared neighbors, so after degrees are known it costs O(1) per pair. It also ignores structure between the two nodes: two unrelated hubs get a very high score.


TGraphX Implementation

All five scorers share the signature score(edge_index, pairs, num_nodes=None, directed=False). They take tensors, not a Graph, and pairs has shape [2, P]: one column per candidate pair.

python
import torch
from tgraphx.mining import (
    common_neighbors_score,
    jaccard_score,
    adamic_adar_score,
    resource_allocation_score,
    preferential_attachment_score,
)

# A small undirected graph, each edge listed once
listed = torch.tensor([
    [0, 1, 1, 2, 3, 0, 3],
    [1, 2, 3, 3, 4, 4, 5],
])
# The scorers read out-neighbors only, so add the reverse direction
edge_index = torch.cat([listed, listed.flip(0)], dim=1)

# Four candidate non-edges: (0,2), (1,4), (2,5), (0,5)
candidates = torch.tensor([
    [0, 1, 2, 0],
    [2, 4, 5, 5],
])

scorers = {
    "CN": common_neighbors_score,
    "Jaccard": jaccard_score,
    "AA": adamic_adar_score,
    "RA": resource_allocation_score,
    "PA": preferential_attachment_score,
}
for name, fn in scorers.items():
    scores = fn(edge_index, candidates, num_nodes=6)
    print(f"{name:8s}", [round(s, 3) for s in scores.tolist()])

Always pass num_nodes. Without it the node count is inferred from the candidate pairs, and the call fails if the graph has a higher node id than any candidate.

Direction is your responsibility

The neighborhood of a node is the set of destinations of its outgoing edges in the edge_index you pass. For an undirected graph you must include both directions, as above (tgraphx.transforms.ToUndirected does this for a Graph). In 1.5.1 the directed argument does not change the result.

python
# Directed edges 2->0 and 2->1: nodes 0 and 1 share an in-neighbor, not an out-neighbor
arcs = torch.tensor([[2, 2], [0, 1]])
pair = torch.tensor([[0], [1]])

print(common_neighbors_score(arcs, pair, num_nodes=3))                  # tensor([0.])
print(common_neighbors_score(arcs, pair, num_nodes=3, directed=False))  # tensor([0.])
print(common_neighbors_score(arcs.flip(0), pair, num_nodes=3))          # tensor([1.]): in-neighbors

For directed graphs, decide which neighborhood is meaningful and build edge_index accordingly. With a one-directional edge_index, Adamic-Adar and Resource Allocation also use the out-degree of the shared neighbor, which can be 0 or 1. Adamic-Adar silently skips shared neighbors with out-degree 0 or 1 (1 / log d is undefined there), while Resource Allocation skips only out-degree 0.

Preferential Attachment counts columns of edge_index, not distinct neighbors, so duplicate columns inflate it while the other four scores stay the same. De-duplicate first (for example torch.unique(edge_index, dim=1)), and do not concatenate the reverse edges onto a list that already has both directions.


Evaluating Link Prediction Without Leakage

Evaluation needs held-out edges (positives) and non-edges (negatives). Three rules keep it honest:

  1. Split undirected edges, so the two directions of one edge never land in different splits.
  2. Compute neighborhoods from training edges only.
  3. Draw evaluation negatives from pairs that are not an edge in any split.
python
import networkx as nx
import tgraphx as tgx
from sklearn.metrics import average_precision_score, roc_auc_score
from tgraphx.estimators import edge_train_val_test_split

G = nx.powerlaw_cluster_graph(600, 4, 0.6, seed=0)   # synthetic graph with many triangles
n = G.number_of_nodes()
# One column per undirected edge (u < v)
edges = torch.tensor(sorted(tuple(sorted(e)) for e in G.edges())).t()

def both_ways(e):
    return torch.cat([e, e.flip(0)], dim=1)

train, val, test = edge_train_val_test_split(edges, 0.8, 0.1, 0.1, seed=0)
train_graph = both_ways(train)                        # training edges only

neg = tgx.negative_sampling(both_ways(edges), n, num_neg_samples=val.size(1) + test.size(1),
                            force_undirected=True, seed=0)
val_neg, test_neg = neg[:, :val.size(1)], neg[:, val.size(1):]

test_pairs = torch.cat([test, test_neg], dim=1)
test_y = [1] * test.size(1) + [0] * test_neg.size(1)

def evaluate(scores):
    s = scores.numpy()
    return roc_auc_score(test_y, s), average_precision_score(test_y, s)

for name, fn in scorers.items():
    auc, ap = evaluate(fn(train_graph, test_pairs, num_nodes=n))
    print(f"{name:8s} AUC={auc:.3f} AP={ap:.3f}")
# CN       AUC=0.792 AP=0.777
# Jaccard  AUC=0.776 AP=0.736
# AA       AUC=0.800 AP=0.808
# RA       AUC=0.800 AP=0.808
# PA       AUC=0.716 AP=0.717

These numbers describe one synthetic graph and one split. They say nothing about which scorer is best on your data.

ROC-AUC is the probability that a random positive outranks a random negative (ties counting half). Average precision weights the top of the ranking more heavily, which matters when only the top predictions are acted on. Average precision depends strongly on the ratio of negatives to positives: with one negative per positive it is far higher than it would be against all non-edges. Always report the ratio.

Trap 1: scoring on the full graph

It is tempting to pass the whole graph to the scorer. Then the held-out edges are part of the neighborhoods: other test and validation edges add shared neighbors to test positives, and each test edge raises the degrees of its own endpoints. On this graph the effect is large:

python
# WRONG on purpose: neighborhoods built from all edges, including validation and test
leaky = adamic_adar_score(both_ways(edges), test_pairs, num_nodes=n)
print("AA on full graph: AUC=%.3f AP=%.3f" % evaluate(leaky))
# AA on full graph: AUC=0.877 AP=0.882   (honest: 0.800 / 0.808)

Trap 2: ties in tgraphx.metrics

Neighborhood scores are full of ties, especially zeros. In 1.5.1, tgraphx.metrics.roc_auc and tgraphx.metrics.average_precision do not handle tied scores: tied items receive arbitrary ranks, so the result depends on ordering rather than on the scores. Use scikit-learn for these heuristics.

python
from tgraphx.metrics import roc_auc

cn = common_neighbors_score(train_graph, test_pairs, num_nodes=n)
print(f"share of zero scores: {(cn == 0).float().mean().item():.2f}")
print(f"sklearn AUC: {roc_auc_score(test_y, cn.numpy()):.3f}")
print(f"tgraphx AUC: {roc_auc(cn[:test.size(1)], cn[test.size(1):]):.3f}")
# An input with no information at all should give 0.5
print("all scores equal:", roc_auc(torch.zeros(100), torch.zeros(100)))

In our CPU run the share of zeros was 0.62, scikit-learn gave 0.792, TGraphX gave 0.927, and the all-equal input returned 1.0.


Scoring Function Comparison

Method Combines Down-weights busy shared neighbors Normalizes by endpoint degree Cost per pair
Common Neighbors count of shared neighbors no no O(min(d_u, d_v))
Jaccard overlap ratio no yes O(d_u + d_v)
Adamic-Adar weighted shared neighbors by 1 / log d_w no O(min(d_u, d_v))
Resource Allocation weighted shared neighbors by 1 / d_w no O(min(d_u, d_v))
Preferential Attachment degree product not applicable no (rewards high degree) O(1)

Here d_u is the degree of node u. Each call to a neighborhood-based TGraphX scorer first rebuilds the neighbor sets from edge_index, so score many pairs in one call instead of one pair per call.


Combining Scores

You can combine several scores into one predictor. Instead of hand-picking weights, fit them on validation pairs, still using the training graph for neighborhoods:

python
from sklearn.linear_model import LogisticRegression

def features(pairs):
    return torch.stack([fn(train_graph, pairs, num_nodes=n) for fn in scorers.values()], dim=1)

val_pairs = torch.cat([val, val_neg], dim=1)
val_y = [1] * val.size(1) + [0] * val_neg.size(1)
x_val = features(val_pairs)
mean, std = x_val.mean(0), x_val.std(0).clamp(min=1e-8)      # from validation pairs only
clf = LogisticRegression().fit(((x_val - mean) / std).numpy(), val_y)

combined = clf.decision_function(((features(test_pairs) - mean) / std).numpy())
print("combined: AUC=%.3f AP=%.3f" % (roc_auc_score(test_y, combined),
                                      average_precision_score(test_y, combined)))
# combined: AUC=0.824 AP=0.845

On this graph the combination scored higher than any single heuristic. That is not guaranteed; the five features are strongly correlated, and with few validation pairs the weights are unstable.


Using Scores for Negative Sampling

Heuristic scores can also pick harder training negatives for a GNN: node pairs that look structurally close but are not connected. TGraphX has no sampler driven by a scoring function, but it takes only a few lines: draw candidates with negative_sampling, score them, keep the top ones.

python
pool = tgx.negative_sampling(train_graph, n, num_neg_samples=20_000, force_undirected=True, seed=1)
aa_pool = adamic_adar_score(train_graph, pool, num_nodes=n)
hard = pool[:, aa_pool.topk(train.size(1)).indices]

# Diagnostic only (never use test edges to choose negatives):
held_out = set(map(tuple, torch.cat([val, test], dim=1).t().tolist()))

def held_out_share(p):
    return sum(tuple(sorted(e)) in held_out for e in p.t().tolist()) / p.size(1)

print(f"top-AA negatives: {held_out_share(hard):.1%}, all candidates: {held_out_share(pool):.1%}")
# top-AA negatives: 1.4%, all candidates: 0.3%

This shows the main risk. The pairs a good heuristic ranks highest are exactly the pairs most likely to be real but unobserved edges. Here the "hard negatives" contained held-out edges several times more often than the candidate pool did. Consider sampling from a middle band of scores, or mixing hard and uniform negatives, and compare on validation data.

TGraphX also ships hard_negative_sampling, which ranks random candidate pairs by embedding similarity (cosine or dot product), not by a graph heuristic:

python
adj = torch.zeros(n, n)
adj[train_graph[0], train_graph[1]] = 1.0
U, S, _ = torch.svd_lowrank(adj, q=16)
embeddings = U * S.sqrt()                 # any [N, D] node embeddings, e.g. from your model

hard_emb = tgx.hard_negative_sampling(
    train_graph, embeddings, num_nodes=n, num_neg_samples=200,
    candidate_pool_size=5000, force_undirected=True, seed=0,
)
print(hard_emb.shape)                     # torch.Size([2, 200])

Limitations vs GNN Approaches

They cannot use node features. If a citation network has a text embedding for each paper, these scores ignore it. A GNN can use both structure and features.

They are local. Common Neighbors, Jaccard, Adamic-Adar and Resource Allocation are nonzero only when a path of length 2 connects the pair. Longer paths are invisible to them. Path-based indices such as Katz, or multi-layer GNNs, look further.

They do not learn. The same formula is applied to every graph, regardless of the domain.

They break on bipartite graphs. In a user-item graph, a user and an item never share a neighbor: every neighbor of the user is an item and every neighbor of the item is a user. So Common Neighbors, Jaccard, Adamic-Adar and Resource Allocation score every candidate user-item edge 0. Two items can share neighbors (users), but that is not the pair you are trying to predict. Preferential Attachment still returns a value, based on popularity and activity alone.

For learned link prediction on ordinary graphs, see VGAE for link prediction; for relational triples, see knowledge graph embedding with tensor features.


Scalability Considerations

The neighborhood-based TGraphX scorers (all except Preferential Attachment, which is a tensor operation on degrees) are CPU baselines: they build a Python set of neighbors per node and loop over the candidate pairs. Moving tensors to a GPU does not make the intersections run there. Time grows with the number of pairs and with node degrees.

Sparse matrix operations. For larger query sets, shared neighbors can be computed with sparse rows of the adjacency matrix. This reproduces TGraphX's values:

python
import numpy as np
import scipy.sparse as sp

rows, cols = train_graph.numpy()
A = sp.csr_matrix((np.ones(rows.size), (rows, cols)), shape=(n, n))   # no duplicate edges
deg = np.asarray(A.sum(axis=1)).ravel()
u, v = test_pairs.numpy()

shared = A[u].multiply(A[v]).tocsr()          # [P, N]: 1 where w is a shared neighbor
cn_sparse = np.asarray(shared.sum(axis=1)).ravel()
aa_weight = np.where(deg > 1, 1.0 / np.log(np.maximum(deg, 2)), 0.0)
aa_sparse = shared @ aa_weight

assert np.allclose(cn_sparse, common_neighbors_score(train_graph, test_pairs, num_nodes=n).numpy())
assert np.allclose(aa_sparse, adamic_adar_score(train_graph, test_pairs, num_nodes=n).numpy(),
                   atol=1e-5)

Score very large candidate sets in chunks so that A[u] fits in memory.

MinHash and locality-sensitive hashing. Jaccard similarity can be estimated from fixed-size MinHash signatures, trading exactness for a per-pair cost that does not grow with degree.

Candidate pre-filtering. There are O(n²) node pairs, so scoring all of them quickly becomes impractical. For Preferential Attachment, the top k pairs can be found from the sorted degree list with a heap in about O(n log n + k log k), plus the cost of skipping pairs that are already edges. For the other scorers, restrict candidates to nodes two hops apart, since all other pairs score zero.

For sampling-based training on large graphs, see the neighbor sampling article.


Frequently Asked Questions

When should I use classical scoring functions instead of a GNN? When there are no informative node features, training budget is limited, or you need scores you can explain. Use them as baselines in any case.

Do these functions work on directed graphs? They work on whatever out-neighborhoods your edge_index defines. Use edge_index for out-neighbors, edge_index.flip(0) for in-neighbors, or concatenate both and de-duplicate the columns to ignore direction. The directed flag does not do this for you.

How many candidate pairs can I score? It depends on degrees and hardware. Time a sample of your candidates, and switch to sparse operations or candidate filtering if the full set is too slow.

Is Adamic-Adar always better than Common Neighbors? No. If every node had the same degree d > 1, Adamic-Adar would equal Common Neighbors divided by log d, giving the identical ranking. They can differ more when degrees vary widely, and which one ranks better is an empirical question.


What This Article Builds On

This article assumes familiarity with edge_index graph representation. If you are new to TGraphX, the shape-aware validation guide covers data construction and validation. For learned link prediction with embeddings of relational data, see the knowledge graph embedding tutorial.


Classical Scoring Functions as Baselines

When you propose or evaluate a GNN link predictor, compare it against Adamic-Adar and Resource Allocation on the same split, with the same negatives and the same metric implementation. The computation is cheap next to GNN training, and it shows how much of the task is explained by local structure alone. If a model barely beats these baselines, either it is not learning much beyond local overlap or the task mostly depends on it.


References

  • Adamic, L. A. and Adar, E. (2003). Friends and neighbors on the Web. Social Networks, 25(3).
  • Barabási, A.-L. and Albert, R. (1999). Emergence of scaling in random networks. Science, 286.
  • Liben-Nowell, D. and Kleinberg, J. (2007). The link-prediction problem for social networks. JASIST, 58(7).
  • Zhou, T., Lü, L. and Zhang, Y.-C. (2009). Predicting missing links via local information. European Physical Journal B, 71.