Build a Graph-Based Recommender Using Node2Vec on a User-Item Graph


recommendation-systems classical-ml nlp model-evaluation
View full code for this problem

ML Problem & Solution

Node2Vec On A User-Item Graph

Sampling paths with a random walk, against counting the same paths exactly

⏱ 37 min read 📐 Advanced 🎯 Classical ML

A marketplace has 40 million users, 12 million items and a year of interaction history, and the recommendations are built on item-item collaborative filtering: for each item, the items most often bought by the same people. It works, and it has a hard ceiling that everyone on the team can describe. A user who has touched four items gets recommendations drawn from the neighbourhoods of those four items, and nothing else. There is no mechanism by which the system notices that those four items place the user firmly inside a cluster of two thousand related items, most of which share no direct co-purchaser with anything the user has seen. The signal is there in the data. The model cannot reach it, because it only ever looks one co-occurrence step away.

The graph framing is the obvious response. Lay the log out as a bipartite graph with users on one side and items on the other, and an edge wherever an interaction happened. Item-item collaborative filtering is now visibly a path count: the similarity between two items is the number of length-two paths between them through a shared user. Once it is a path count, the generalisation writes itself. Why stop at two? A path of length four reaches items that share a user with an item that shares a user with yours, which is exactly the cluster-level signal the current system cannot see. The promise of a graph recommender is the whole path distribution rather than its first term.

The trouble is that enumerating long paths is combinatorially hopeless on a real graph, so we sample them instead. That is what node2vec does: take random walks over the graph, treat each walk as a sentence and each node as a word, and hand the corpus to word2vec. The embeddings that fall out put nodes close together when many walks pass through both, which is a sampled estimate of a weighted path count. It is a genuinely clever reduction, and it comes with three traps that are specific to the user-item case and invisible in the training loss. Our measured run spends 17.31 seconds to score 0.4207 recall@20, and the two-hop path count it was supposed to improve on scores 0.4207 in 0.08 seconds. Getting those two numbers to be equal rather than a factor of 12.9 apart is most of the work.

The analogy worth holding onto: a random walk on this graph is a rumour spreading through a party where every conversation is between one person and one topic, and never between two people or two topics. You learn who is interested in what by listening to the chain. But if you forget that the chain strictly alternates, half of what you record is a person standing next to another person, which tells you nothing about topics at all, and you will have spent half your evening on it.

Formally: given a bipartite interaction graph G = (U, I, E) with 42,519 edges over 3,000 users and 1,200 items, learn a d-dimensional embedding per node such that ranking all unseen items by a dot product against the user’s embedding maximises recall@20 on one held-out interaction per user, under the constraint that the method must beat an exact two-hop path count that costs 0.08 seconds.

Framing the Problem

This is a ranking problem fitted through an unsupervised representation learning objective, and the gap between those two sentences is where most of the difficulty lives. Nothing we train optimises recall@20. We train a skip-gram model to predict walk co-occurrences and then hope the geometry it produces happens to rank well, which it does, up to a point, and the point where it stops is measurable.

The target is implicit and positive-only. An edge means a user interacted with an item; the absence of an edge means either disinterest or ignorance and we cannot tell which. There are no ratings, no explicit negatives and no labels in the supervised sense. The held-out label for evaluation is constructed: for each user, the last interaction by timestamp is removed from the graph and becomes the single relevant item for that user’s ranking.

Constraints, which decide most of the design:

  • Transductive is acceptable, inductive is not required. Every node is in the graph at training time. This is a real limitation and it is out of scope here, noted in the alternatives section.
  • Full-catalogue ranking at evaluation. Every item the user has not seen in train is a candidate. With 1,200 items that is affordable. Post 21 measured how badly sampled negatives distort these metrics and we do not reintroduce that.
  • The cold segment must be reported separately. 1,126 of 3,000 test users have 8 or fewer train edges. Post 27 found popularity beating every learned model on cold users at 0.6467 against 0.5382 recall@100, and that result only existed because the segments were not pooled.
  • The baseline is not a formality. Any method here has to beat an exact two-hop count, which is one matrix product.

The success metric is recall@20 on the single held-out item, full catalogue. The guardrail metrics are NDCG@20, which catches a method that fills the slate without ordering it; catalogue coverage and exposure Gini, which catch a method that wins by recommending the same 50 popular items to everyone; and a planted-community purity score, which is the one measurement that separates “recovered the structure” from “ranked well”. Those last two diverge sharply in this post.

Metric That Matters

Recall@20 against a random-guess floor of 20/1200 = 0.0167, with community purity reported beside it against its own floor of 1/8 = 0.125. The purity column is what turns a silent catastrophe into a diagnosis: our worst configuration scores a purity of 0.035, which is below the random floor, so it is anti-correlated with the planted structure rather than merely uninformative. A single recall number would have said only that something was wrong.

Explicitly out of scope: inductive embeddings for items that appear after training, graph neural networks (which subsume this method and are the honest production answer), edge types and weights, and the distributed walk generation that any real graph requires. The last of those is where most production engineering effort actually goes.

Key Insight

The objective we train and the metric we report are different functions, and on this problem they stop agreeing before training converges. Our loss falls monotonically from 1.9536 to 1.2203 between epoch 2 and epoch 8 while recall@20 peaks at epoch 3 and then loses 0.1570. Any early-stopping rule built on the training loss selects the worst model measured.

Data and Features

There is no feature engineering here in the usual sense. The input is a graph and the “features” are the walk corpus we generate from it, which means the pipeline’s leakage surface is unusual and worth being precise about.

The graph, which every number in this post depends on:

3,000 users, 1,200 items, 42,519 edges, density 0.0118
8 planted communities, community purity 0.72
user degree:  mean 14.17, min 3, max 74
item degree:  mean 35.43, median 17, max 1283
top decile of items holds 49.75% of all item degree
split: 39,519 train edges, 3,000 test edges, overlap 0
test users by train degree: 1,126 cold (<=8), 1,313 mid, 561 warm (>=20)

Two of those lines are load-bearing. The top decile of items holding 49.75% of the degree is what makes the popularity baseline a real opponent and what makes the negative-sampling distribution matter as much as it does later. And the median item degree of 17 against a maximum of 1,283 is the skew that any degree-proportional sampling has to contend with.

Users and items live in one shared index space: users are 0 to 2999 and items are 3000 to 4199. This is not a convenience, it is what makes the method possible, since a single embedding table has to cover both sides for a walk to produce comparable vectors. It is also the origin of every trap in this post, because one index space makes it easy to forget that half the indices are a different kind of thing.

# Bipartite adjacency in CSR form: the walk inner loop needs a neighbour slice
# and a degree, and nothing else. A CSR slice is a view rather than a copy.
import numpy as np

class BipartiteGraph:
    def __init__(self, n_users, n_items, edges):
        self.n_users, self.n_items = int(n_users), int(n_items)
        self.n_nodes = self.n_users + self.n_items
        self.edges = edges                      # (m, 2): (user, item_global)
        src = np.concatenate([edges[:, 0], edges[:, 1]])
        dst = np.concatenate([edges[:, 1], edges[:, 0]])
        order = np.argsort(src, kind="stable")
        self.indices = dst[order].astype(np.int32)
        counts = np.bincount(src[order], minlength=self.n_nodes)
        self.indptr = np.zeros(self.n_nodes + 1, dtype=np.int64)
        np.cumsum(counts, out=self.indptr[1:])
        self.degree = counts.astype(np.int64)

    def is_user(self, node):
        return node < self.n_users

    def neighbours(self, node):
        return self.indices[self.indptr[node]:self.indptr[node + 1]]

The leakage route that is specific to graph methods

A leave-one-out split is routine. Enforcing it on a graph method is not, because the leakage propagates further than it does anywhere else in this series. In a matrix factorisation, one test edge left in the training matrix leaks one label into one cell. In a walk-based method, the corpus is generated from the graph, so one surviving test edge appears in every walk that crosses either of its endpoints, and from there it contaminates the embeddings of nodes several hops away. The metric does not spike. It rises smoothly and plausibly, which is the worst possible failure signature.

# Temporal leave-one-out, then an assertion that the graph was rebuilt without
# the held-out edges. The assertion is the only defence against a leak that
# propagates through the corpus instead of appearing in one cell.
def split(log, n_users):
    order = np.lexsort((log[:, 2], log[:, 0]))      # by user, then timestamp
    s = log[order]
    users = s[:, 0]
    last = np.searchsorted(users, np.arange(n_users), side="right") - 1
    first = np.searchsorted(users, np.arange(n_users), side="left")
    has_test = (last >= 0) & (last > first)         # needs 2+ interactions
    test_rows = last[has_test]
    mask = np.ones(s.shape[0], dtype=bool)
    mask[test_rows] = False
    return s[mask], s[test_rows]

def assert_no_leakage(train_log, test_log):
    tr = set(map(tuple, train_log[:, :2].tolist()))
    te = set(map(tuple, test_log[:, :2].tolist()))
    overlap = tr & te
    if overlap:
        raise AssertionError(
            f"{len(overlap)} test edges in the train graph; the walk corpus "
            "would carry them into every nearby embedding")
    return {"train_edges": len(tr), "test_edges": len(te), "overlap": 0}

Users with very little history are kept rather than dropped. Dropping them is the standard move and it deletes the segment where the methods differ most: node2vec’s single clearest win in this post is on cold users, at 0.4716 recall@20 against two-hop’s 0.4636, and pooling would have hidden it.

Key Insight

The train graph is the only graph any model may see, and on a walk-based method that rule has teeth that it lacks elsewhere. The corpus is a function of the graph, so a single leaked edge is not a leaked label, it is a leaked neighbourhood. Build the graph from train edges, then assert the test pairs are absent, and print the assertion's output so a reader can see it ran.

The walk corpus, and the parity rule

Now the first trap. We generate 25,200 walks of length 16 starting from every node with non-zero degree, giving 403,200 tokens at a node coverage of 1.0000. Then we turn walks into skip-gram pairs with a context window, and this is where the bipartite structure asserts itself.

A walk on a bipartite graph alternates sides deterministically. From a user you can only step to an item; from an item only to a user. So the offset between two positions in a walk determines the pair’s type exactly: odd offsets are user-item pairs, even offsets are user-user or item-item pairs. With the symmetric window of 4 that every tutorial uses, roughly half the pairs are same-side, and a recommender that scores a user against an item with a dot product never reads same-side similarity at all.

# Context pairs under an explicit parity rule. On a bipartite graph the offset
# fixes the pair type, so the parity choice decides what fraction of the
# gradient budget trains a user-item score at all.
def context_pairs(walks, window, parity, n_users):
    offsets = range(1, window + 1)
    if parity == "opposite":
        offsets = [o for o in offsets if o % 2 == 1]   # user-item only
    elif parity == "same":
        offsets = [o for o in offsets if o % 2 == 0]   # same-side only
    else:
        offsets = list(offsets)                        # the tutorial default

    centres, contexts = [], []
    L = walks.shape[1]
    for off in offsets:
        if off >= L:
            continue
        a, b = walks[:, :L - off].reshape(-1), walks[:, off:].reshape(-1)
        keep = (a >= 0) & (b >= 0) & (a != b)
        centres += [a[keep], b[keep]]                  # both directions
        contexts += [b[keep], a[keep]]
    centre = np.concatenate(centres).astype(np.int32)
    context = np.concatenate(contexts).astype(np.int32)
    cross = int(((centre < n_users) != (context < n_users)).sum())
    return centre, context, {
        "offsets_kept": list(offsets),
        "n_pairs": int(centre.shape[0]),
        "cross_type_share": cross / max(1, centre.shape[0]),
    }

Measured across the three settings, with everything else identical:

parity offsets pairs cross-type share final loss recall@20 NDCG@20 purity
all 1, 2, 3, 4 2,577,916 0.547 2.0933 0.3960 0.2234 0.929
opposite 1, 3 1,411,200 1.000 1.6007 0.4207 0.2380 0.795
same 2, 4 1,166,716 0.000 1.9730 0.0040 0.0012 0.124

Dropping the even offsets removes 45% of the corpus and gains 0.0247 of recall@20, so it is faster and better at the same time, which is a rare shape for a fix. The same row is the control and it behaves exactly as the argument predicts: a corpus containing no user-item pair at all scores 0.0040, about a quarter of random guessing, at a purity of 0.124 that is the 0.125 random floor to three decimals.

Common Pitfall

Read the loss column against the recall column in that table. The same configuration has a LOWER final loss than all (1.9730 against 2.0933) and 99 times less recall. The loss measures how well the model predicts walk co-occurrences, and on a corpus of same-side pairs that is a genuinely easier prediction problem and a completely useless recommender. This is the first of three places in this post where the loss points the wrong way.

The Naive Baseline

Two baselines, because they answer different questions. Popularity tells us whether the problem is trivial. The two-hop path count tells us whether the walk is necessary, and it is the one that matters.

# Two baselines. two_hop_scores is item-item collaborative filtering written
# as what it is: a count of length-three paths with degree normalisation.
def interaction_matrix(pairs, n_users, n_items):
    R = np.zeros((n_users, n_items))
    R[pairs[:, 0], pairs[:, 1]] = 1.0
    return R

def popularity_scores(pairs, n_users, n_items):
    counts = np.bincount(pairs[:, 1], minlength=n_items).astype(float)
    return np.tile(counts, (n_users, 1))

def two_hop_scores(pairs, n_users, n_items, norm_exponent=0.5, shrinkage=5.0):
    R = interaction_matrix(pairs, n_users, n_items)
    co = R.T @ R                                   # item-item co-counts
    diag = np.diag(co).copy()
    np.fill_diagonal(co, 0.0)                      # an item cannot recommend itself
    denom = (np.power(diag[:, None], norm_exponent)
             * np.power(diag[None, :], norm_exponent)) + shrinkage
    return R @ (co / np.maximum(denom, 1e-12))

Popularity scores 0.2547 recall@20. That is 15 times the random floor of 0.0167, which is the first thing worth knowing: half the apparent skill of any recommender on this graph is available from a single bincount. Its exposure Gini is 0.981 and its catalogue coverage is 0.030, so it achieves that score by showing 36 items to everybody.

The two-hop count scores 0.4207 recall@20 in 0.08 seconds. That is the number the rest of this post has to beat, and it is worth being clear about why it is the right opponent rather than a straw man. Under the opposite parity rule with a window of 4, the walk collects user-item pairs at path lengths 1 and 3. The two-hop baseline counts paths of length 3 exactly. So node2vec is a sampled estimate of a quantity, and the baseline is that quantity. A sampling procedure cannot contain information its estimand lacks.

Both baselines are tuned rather than cited. The two-hop normalisation exponent of 0.5 is an interior optimum: 0.25 scores 0.4103 and 0.75 scores 0.3117, and the cosine-style 0.5 at 0.4207 sits between them. This matters more than it sounds, and the pitfalls section has the number for what happens when a baseline is left at its defaults.

Key Insight

The naive baseline here is not a weaker model, it is the exact computation of the thing the sophisticated model approximates. That reframing is available whenever a method is described as "sampling" something: ask what it would cost to compute the estimand directly, because at small and medium scale the answer is often one matrix product, and the sampled version then has to justify itself on runtime rather than on quality.

The Solution

A five-stage node2vec pipeline on a user-item graph. Stage one contrasts posts 21 to 28, which treated the log as a 3,000 by 1,200 matrix of density 0.0118 that ALS factorises directly, against post 29's graph of 4,200 nodes in one shared index space with 42,519 edges, 8 planted communities at purity 0.72 and a top decile of items holding 49.75 percent of all item degree, and notes that the graph is bipartite with users 0 to 2999 and items 3000 to 4199, no user-user or item-item edge and no odd cycle, from which every trap follows. Stage two covers walks: 25,200 walks of length 16 from every node giving 403,200 tokens at node coverage 1.0000, and a candidate-class census over 748,080 prev-cur-cand triples finding 40,000 in the return class weighted 1/p, exactly 0 in the same-distance class weighted 1, and 708,080 in the outward class weighted 1/q, so p and q collapse to the ratio q/p and node2vec has one effective parameter rather than two, confirmed by p equals 1 with q equals 4 and p equals 0.25 with q equals 1 agreeing to every digit at a return rate of 0.1681 and recall@20 of 0.4207, and by p equals 1 with q equals 2 and p equals 0.5 with q equals 1 agreeing at 0.0970 and 0.4197, with the whole q/p range from 0.25 to 8 spanning just 0.0127 of recall@20 and DeepWalk at p equals q equals 1 sitting inside it at 0.4137 so the second-order bias buys only 0.0070. Stage three is the parity rule: offsets decide pair type, so parity all with offsets 1 2 3 4 gives 2,577,916 pairs at cross-share 0.547, loss 2.0933 and recall@20 0.3960, parity opposite with offsets 1 and 3 gives 1,411,200 pairs at cross-share 1.000, loss 1.6007 and recall@20 0.4207 for 45 percent less corpus and 0.0247 more recall, and parity same with offsets 2 and 4 gives 1,166,716 pairs at cross-share 0.000, loss 1.9730 and recall@20 0.0040, so same has a lower loss than all and 99 times less recall. Stage four is skip-gram with negative sampling by hand in numpy at dimension 64, 5 negatives, 3 epochs, learning rate 0.025 decaying to 0.0001, over 1,411,200 pairs in 15.7 seconds, with a central-difference gradient check running by default at gradient scale 7.143e-3, absolute error 1.655e-11 and relative error 1.056e-6 passing a 1e-5 tolerance, and a scoring table showing W_user dot V_item which is the loss's own pair at recall@20 0.4207, NDCG@20 0.2380, recall@100 0.6740, purity 0.795 and median rank 36, V_user dot W_item at 0.2833, 0.1148, 0.5810, 0.968 and 68, W_user dot W_item which is node2vec's published convention at 0.0327, 0.0129, 0.1540, 0.035 and 417, and the folklore W plus V fix at 0.3427, 0.1484, 0.6077, 0.938 and 54, with the purity floor at 1/8 equals 0.125 so the convention's 0.035 is anti-correlated rather than uninformative because no gradient ever pushed W_user toward W_item. Stage five is the headline table where popularity scores recall@20 0.2547, NDCG@20 0.1225, recall@100 0.4907, cold 0.2966, warm 0.2228, coverage 0.030, purity 0.061 in 0.00 seconds, two-hop scores 0.4207, 0.2365, 0.6800, 0.4636, 0.3975, 0.373, 0.772 in 0.08 seconds, three-hop scores 0.4227, 0.2363, 0.6777, 0.4689, 0.3904, 0.281, 0.705 in 0.10 seconds, tuned ALS scores 0.4153, 0.2332, 0.6727, 0.4591, 0.3922, 0.219, 0.712 in 1.91 seconds, and node2vec scores 0.4207, 0.2380, 0.6740, 0.4716, 0.3832, 0.269, 0.795 in 17.31 seconds, so four methods sit inside 0.0074 of each other, the fastest of those four is 216 times faster than the slowest, node2vec ties two-hop to four decimals, the exact three-hop path count is the best of the five, and node2vec's real wins are narrow at best NDCG@20, best cold recall and best purity

The approach has three moving parts and each one has a decision inside it that is usually made by default.

Random walks, and the parameter that does not exist here

node2vec biases its walk with two parameters. Having arrived at node cur from node prev, the unnormalised weight of stepping to candidate x is 1/p if x is prev itself, 1 if x is a neighbour of prev, and 1/q otherwise. The paper’s entire breadth-versus-depth story, and the homophily-versus-structural-equivalence interpretation built on it, lives in the contrast between that middle class and the last one: a walk that favours neighbours-of-prev stays inside a neighbourhood, and one that favours everything else leaves it.

Before tuning p and q, we counted how often each class can actually occur:

candidate classes over 748,080 (prev, cur, cand) triples
  return         (weight 1/p)     40,000
  same distance  (weight 1  )          0      <- structurally empty
  outward        (weight 1/q)    708,080

The middle class is empty, and not by accident. A candidate reached from cur is the same type as prev, and every neighbour of prev is the other type, so a candidate can never be a neighbour of prev. A bipartite graph has no odd cycles, and that is the same statement said differently. The weights therefore reduce to 1/p for returning and 1/q for everything else, which means only the ratio q/p can have any effect and node2vec has one effective parameter on this graph rather than two.

The sweep confirms it to every printed digit, which is the point of printing it:

p q q/p return rate items per walk recall@20 recall@100 purity
4.00 1.00 0.25 0.0146 7.72 0.4157 0.6680 0.678
2.00 1.00 0.50 0.0280 7.60 0.4173 0.6690 0.687
1.00 1.00 1.00 0.0536 7.38 0.4137 0.6740 0.720
1.00 2.00 2.00 0.0970 6.95 0.4197 0.6760 0.747
0.50 1.00 2.00 0.0970 6.95 0.4197 0.6760 0.747
1.00 4.00 4.00 0.1681 6.29 0.4207 0.6740 0.795
0.25 1.00 4.00 0.1681 6.29 0.4207 0.6740 0.795
1.00 8.00 8.00 0.2696 5.19 0.4080 0.6737 0.868

The reciprocal pairs are identical in every column. The whole range of q/p from 0.25 to 8 spans 0.0127 of recall@20, and DeepWalk, which is p = q = 1 and needs no second-order machinery at all, sits inside that spread at 0.4137. The biased walk buys 0.0070 of recall@20 and costs a 1.4 second walk generation against a vectorised 0.0 second one.

We implement the bias by rejection sampling rather than by the paper’s precomputed per-edge alias tables. Alias tables cost memory proportional to the sum of squared degree, which is fine here and is not fine on a graph with hub items. Rejection sampling is exact, allocates nothing per edge, and keeps the three candidate classes visible in the code, which is how the census above came to be written at all.

# Second-order node2vec bias by rejection sampling: draw a uniform neighbour,
# accept with probability w/w_max. Exact, and O(1) memory per edge.
def random_walks(graph, walks_per_node, walk_length, p, q, seed):
    rng = np.random.default_rng(seed)
    starts = np.repeat(np.where(graph.degree > 0)[0].astype(np.int32),
                       walks_per_node)
    rng.shuffle(starts)
    walks = np.full((starts.shape[0], walk_length), -1, dtype=np.int32)
    walks[:, 0] = starts
    indptr, indices, degree = graph.indptr, graph.indices, graph.degree

    if abs(p - 1.0) < 1e-12 and abs(q - 1.0) < 1e-12:
        cur = walks[:, 0].astype(np.int64)          # DeepWalk: vectorised
        for t in range(1, walk_length):
            d = degree[cur]
            offs = np.minimum((rng.random(cur.shape[0]) * d).astype(np.int64),
                              np.maximum(d - 1, 0))
            nxt = np.where(d > 0, indices[indptr[cur] + offs], cur)
            walks[:, t] = nxt
            cur = nxt.astype(np.int64)
        return walks

    nb_sets = [set(graph.neighbours(n).tolist()) for n in range(graph.n_nodes)]
    w_max = max(1.0 / p, 1.0, 1.0 / q)
    acc_p, acc_q, acc_1 = (1.0 / p) / w_max, (1.0 / q) / w_max, 1.0 / w_max
    for w in range(walks.shape[0]):
        cur = int(walks[w, 0])
        nb = indices[indptr[cur]:indptr[cur + 1]]
        prev, cur = cur, int(nb[rng.integers(len(nb))])
        walks[w, 1] = cur
        for t in range(2, walk_length):
            nb = indices[indptr[cur]:indptr[cur + 1]]
            if len(nb) == 0:
                walks[w, t:] = cur
                break
            prev_nb = nb_sets[prev]
            while True:
                cand = int(nb[rng.integers(len(nb))])
                thr = acc_p if cand == prev else (
                    acc_1 if cand in prev_nb else acc_q)
                if thr >= 1.0 or rng.random() < thr:
                    break
            prev, cur = cur, cand
            walks[w, t] = cur
    return walks

Skip-gram with negative sampling, and why we wrote it out

The corpus is now a word2vec problem. For a pair (c, x) with K sampled negatives the loss is

L = -log sigmoid(w_c . v_x) - SUM_k log sigmoid(-w_c . v_nk)

with two tables: an input table W and an output table V. The analogy before the code: the objective is a tug of war in which every observed co-occurrence pulls one input vector towards one output vector, and K sampled items pull it away. A node’s position is the equilibrium of the pulls it participates in, and nothing else.

The negative sampling distribution is degree ** exponent, normalised. This is worth dwelling on because it is the same quantity post 27 called the logQ correction, approached from the opposite direction. A two-tower model keeps its proposal distribution and corrects the loss for it. word2vec does not correct the loss; it reshapes the proposal with an exponent, and the published value of 0.75 is a constant almost nobody re-derives for their own data. Both are fixing the same bias, which is that a popular item appears as a true context far more often than a rare one, so the model spends its capacity pushing down exactly the items it most needs to be able to rank up.

# SGNS: one sparse SGD step over a batch of pairs. np.add.at is the only
# correct scatter here, because a batch contains repeated node ids and fancy
# index assignment would keep one update per id and silently drop the rest.
def step(self, c, x, lr):
    neg = self.sample_negatives((c.shape[0], self.negatives)).astype(np.int64)
    wc, vx, vn = self.W[c], self.V[x], self.V[neg]
    pos_z = np.einsum("bd,bd->b", wc, vx)
    neg_z = np.einsum("bd,bkd->bk", wc, vn)

    gpos = _sigmoid(pos_z) - 1.0                      # (B,)
    gneg = _sigmoid(neg_z)                            # (B, K)
    dwc = gpos[:, None] * vx + np.einsum("bk,bkd->bd", gneg, vn)
    dvx = gpos[:, None] * wc
    dvn = gneg[:, :, None] * wc[:, None, :]

    np.add.at(self.W, c, -lr * dwc)
    np.add.at(self.V, x, -lr * dvx)
    np.add.at(self.V, neg.reshape(-1), (-lr * dvn).reshape(-1, self.dim))
    loss = -(_log_sigmoid(pos_z).sum() + _log_sigmoid(-neg_z).sum())
    return loss / c.shape[0]

The hyperparameters that actually move the number, with their swept values: the negative-sampling exponent at 0.5 (not word2vec’s 0.75, which costs 0.0250 of recall@20 here), the epoch count at 3 (where 5 costs 0.0370 and 8 costs 0.1570), the context window at 4 so the kept offsets are 1 and 3, and the dimension at 64, which turns out to be nearly irrelevant: at dimension 8 the method already scores 0.4140. Every one of those is an interior optimum of its grid, which the pitfalls section explains the need for.

A central-difference gradient check runs in the default pipeline rather than behind a flag. Post 27 shipped an L2-normalisation backward pass that was missing its projection term, which halved recall@100 from 0.2417 to 0.1237 while the loss curve looked perfectly healthy. The check costs a fraction of a second and reports a gradient scale of 7.143e-3, a worst absolute error of 1.655e-11 and a worst relative error of 1.056e-6.

Scoring, which is a one-word decision worth a factor of 12.9

The model has two tables and the loss only ever touches W_a . V_b. node2vec’s published convention is to keep the input table, discard the output table, and score any pair of nodes with W_a . W_b. On a homogeneous graph that is defensible: same-type nodes do co-occur in walks, so the objective does push their W rows together. On a bipartite graph under the opposite parity rule, a user and an item never occupy an even offset from one another, so no gradient in the entire run ever pushes W_user towards W_item.

scoring rule recall@20 NDCG@20 recall@100 median rank purity
W_user . V_item, the loss’s own pair 0.4207 0.2380 0.6740 36 0.795
V_user . W_item, the mirror 0.2833 0.1148 0.5810 68 0.968
W_user . W_item, node2vec’s convention 0.0327 0.0129 0.1540 417 0.035
V_user . V_item 0.0047 0.0014 0.0187 1038 0.093
(W+V) on both sides, the folklore fix 0.3427 0.1484 0.6077 54 0.938

All five rows come from the same trained model at the same final loss of 1.6007. The convention scores 0.0327 against 0.4207, a factor of 12.9, and its purity of 0.035 is below the 0.125 random floor, which means it is anti-correlated with the planted structure rather than merely uninformative. The mechanism is worth stating because it is not obvious: the one thing W_user and W_item genuinely have in common is having been pushed away from the same popular negatives, so the convention ranks items by how little they resemble the user’s own repulsion pattern. The folklore W+V fix works, and for an unglamorous reason: two of its four cross terms are the quantity the loss actually trained.

Key Insight

The single design decision that mattered most was not the walk, the bias, the dimension or the negative distribution. It was scoring with the pair of tables the objective actually optimised, which is one word in a config file and worth 12.9 times the recall of the published convention. When a method's loss is defined over one quantity and you evaluate a different one, no amount of training fixes it and no training-time metric reveals it.

Evaluation and Metrics

Recall@20 on a single held-out item per user, ranked against the full catalogue of 1,200 items minus that user’s train history. With exactly one relevant item, recall@k is the share of users whose held-out item lands in the top k, and NDCG@k collapses to 1 / log2(rank + 1) averaged over users. Reporting both is still worth it, because recall says whether the item made the slate and NDCG says whereabouts in it, and several results in this post move those two by different amounts.

Ties are broken pessimistically: an item scoring equal to the held-out item counts as ranked above it. Without that, the popularity baseline collects a free win on every zero-degree item, since they all tie at zero, and a constant scorer would post a respectable recall@100.

# Full-catalogue ranking with pessimistic tie-breaking. Train items are masked
# to -inf. Post 21 measured how much sampled negatives distort this; we rank
# every candidate every time instead.
def rank_metrics(scores, train_pairs, test_pairs, *, k_values=(10, 20, 100),
                 users=None):
    s = scores.copy()
    s[train_pairs[:, 0], train_pairs[:, 1]] = -np.inf
    test_u, test_i = test_pairs[:, 0], test_pairs[:, 1]
    if users is not None:                  # the cold / mid / warm segmenting
        keep = np.isin(test_u, users)
        test_u, test_i = test_u[keep], test_i[keep]
    target = s[test_u, test_i]
    better = (s[test_u] > target[:, None]).sum(axis=1)
    ties = (s[test_u] == target[:, None]).sum(axis=1) - 1
    rank = better + ties + 1                        # pessimistic
    out = {"mean_rank": float(rank.mean()),
           "median_rank": float(np.median(rank))}
    for k in k_values:
        hit = rank <= k
        out[f"recall@{k}"] = float(hit.mean())
        out[f"ndcg@{k}"] = float(
            np.where(hit, 1.0 / np.log2(rank + 1.0), 0.0).mean())
    return out

The headline comparison, with every method tuned with comparable effort:

method recall@10 recall@20 NDCG@20 recall@100 cold recall@20 warm recall@20 coverage purity fit seconds
popularity 0.1817 0.2547 0.1225 0.4907 0.2966 0.2228 0.030 0.061 0.00
two-hop count 0.3300 0.4207 0.2365 0.6800 0.4636 0.3975 0.373 0.772 0.08
three-hop count 0.3307 0.4227 0.2363 0.6777 0.4689 0.3904 0.281 0.705 0.10
ALS, tuned 0.3327 0.4153 0.2332 0.6727 0.4591 0.3922 0.219 0.712 1.91
node2vec, tuned 0.3310 0.4207 0.2380 0.6740 0.4716 0.3832 0.269 0.795 17.31

Four methods sit inside 0.0074 of each other on recall@20, and the fastest of them is 216 times faster than the slowest. node2vec ties the two-hop count to four decimal places. The exact three-hop count is the best of the five. node2vec’s wins are real and narrow: the best NDCG@20 at 0.2380, so it orders the slate slightly better than it fills it; the best cold-user recall at 0.4716; and the best recovery of the planted community structure at 0.795. None of those is worth 17.31 seconds against 0.08 on a graph this size.

Where higher-order connectivity stops paying

The window is literally a cap on path order under the parity rule, since a window of w collects user-item pairs at path lengths 1, 3, 5 and so on up to w. So we can ask what each additional order is worth:

walk length window path orders pairs recall@20 recall@100 purity
8 1 1 352,800 0.2530 0.4423 0.062
8 3 1, 3 604,800 0.2560 0.4910 0.065
16 1 1 756,000 0.3333 0.5453 0.220
16 4 1, 3 1,411,200 0.4207 0.6740 0.795
16 6 1, 3, 5 1,965,600 0.4180 0.6707 0.841
24 8 1, 3, 5, 7 4,032,000 0.4007 0.6713 0.908

At a fixed walk length of 16, adding order 3 to order 1 is worth 0.0874 of recall@20. Adding order 5 costs 0.0027. Going to order 7 with 2.9 times the corpus costs 0.0200 while purity rises to 0.908. The signal in a user-item graph is one and three edges away, which is exactly what item-item collaborative filtering has always computed, and the longer paths trade discrimination for community identity. This is the strongest single piece of evidence that the walk is not collecting new information here, and it is why the three-hop count tops the table.

Key Insight

Purity and recall are not the same axis, and three separate sweeps in this post show them moving in opposite directions. The configuration with the highest purity in the window table (0.908 at order 7) has a recall 0.0200 below the best, and the highest-purity scoring rule (0.968 for the mirror) ranks 0.1374 worse than the best. A model can know exactly which neighbourhood a user lives in and have stopped knowing which door is theirs.

Metric That Matters

The metric that would catch a silent regression here is NOT the training loss, and this post measures that twice. In the epoch sweep the loss falls monotonically from 1.9536 to 1.2203 while recall@20 drops 0.1570 after its peak. In the negative-exponent sweep the loss is MINIMISED at exponent 0.00, whose recall@20 of 0.2937 is 0.1270 below the best setting, and the three lowest losses in that table belong to exponents 0.00, 0.25 and 1.50, whose recalls are 0.2937, 0.3893 and 0.0623, the last being the worst number measured anywhere in this work. Selecting a model by its loss would pick exponent 0.00. Monitor segmented recall@k against a popularity baseline recomputed on the same split, and alert on the cold segment separately, because that is the segment that moves first.

Common Pitfalls and Failure Modes

Five node2vec traps with the number each cost, four of them invisible in the loss curve and three specific to the graph being bipartite. Trap one is scoring with the table the library hands you, costing a factor of 12.9: from one trained model at an identical final loss of 1.6007, W_user dot V_item which is the loss's own pair scores recall@20 0.4207, NDCG@20 0.2380, recall@100 0.6740, purity 0.795 and median rank 36, W_user dot W_item which is node2vec's published convention and what gensim's wv lookup returns scores 0.0327, 0.0129, 0.1540, 0.035 and 417, and the folklore W plus V fix scores 0.3427, 0.1484, 0.6077, 0.938 and 54, so identical loss hides a 12.9 times recall difference and the convention's purity of 0.035 is below the 1 over 8 equals 0.125 random floor meaning anti-correlated rather than uninformative. Trap two is a symmetric context window on an alternating graph, costing 0.0247: parity all with offsets 1 2 3 4 gives 2,577,916 pairs at cross-share 0.547, loss 2.0933, recall@20 0.3960 and recall@100 0.6600, parity opposite with offsets 1 and 3 gives 1,411,200 pairs at cross-share 1.000, loss 1.6007, recall@20 0.4207 and recall@100 0.6740, and parity same with offsets 2 and 4 gives 1,166,716 pairs at cross-share 0.000, loss 1.9730, recall@20 0.0040 and recall@100 0.0197 at a purity of 0.124 that is the random floor to three decimals, so same has a lower loss than all and 99 times less recall while dropping even offsets removes 45 percent of the corpus and gains recall, making it faster and better with no trade-off. Trap three is tuning p and q which are one parameter here, costing 127 seconds and a wrong story: the middle same-distance candidate class is structurally empty at 0 of 748,080 sampled triples because a bipartite graph has no odd cycles, so only the ratio q over p acts, and DeepWalk at p equals q equals 1 scores return rate 0.0536, 7.38 items per walk and recall@20 0.4137 while p equals 1 with q equals 4 and p equals 0.25 with q equals 1 both score return rate 0.1681, 6.29 items per walk and recall@20 0.4207 identically to every digit, with the whole q over p range 0.25 to 8 spanning 0.0127 of recall@20 and the second-order bias buying only 0.0070 over DeepWalk at the cost of a 1.4 second walk against a vectorised 0.0 second one, so the homophily versus structural equivalence distinction is not available on this graph shape. Trap four is trusting the loss, which points the wrong way twice, costing 0.1570 and 0.0250: the epoch sweep gives loss 3.1024 and recall@20 0.2473 at epoch 1, loss 1.9536 and 0.3280 at epoch 2, loss 1.6007 and 0.4207 at epoch 3, loss 1.4017 and 0.3837 at epoch 5 where purity peaks at 0.938, and loss 1.2203 and 0.2637 at epoch 8 at purity 0.919, while the negative exponent sweep gives loss 1.5390 and recall@20 0.2937 at exponent 0.00, loss 1.5742 and 0.3893 at 0.25, loss 1.6007 and 0.4207 at 0.50, loss 1.6305 and 0.3957 at word2vec's published 0.75, loss 1.6413 and 0.2550 at 1.00, and loss 1.5755 and 0.0623 at 1.50, so the loss is minimised at the two worst rows for recall, both effects having one cause in degree-proportional negatives acting as a popularity-debiasing device, meaning early stopping must use the ranking metric since loss and purity both say keep going at every epoch measured, and the exponent is simultaneously a diversity dial moving Gini from 0.979 to 0.781 and coverage from 0.102 to 0.583. Trap five is comparing a tuned model against cited defaults, costing the conclusion: before, ALS at its cited defaults of alpha 40 and regularisation 0.02 scored 0.2283 recall@20 against tuned node2vec's 0.4073 suggesting the walk won by 0.1790, and the first ALS grid's best cell sat on the grid boundary at alpha 1.0 and regularisation 10.0 which is a wall rather than an optimum, while after sweeping ALS to an interior optimum at alpha 2.0 and regularisation 30.0 it scores 0.4153 against node2vec's 0.4207 for a 0.0054 gap, and at matched dimension ALS is actually ahead at dimensions 8, 16 and 32 by 0.0003, 0.0010 and 0.0010 and behind by only 0.0053 at 64, so tuning the baseline erased 97 percent of the apparent win and every node2vec knob also selects an interior point with negative exponent 0.5 inside 0.25 and 0.75, q over p 4 inside 2 and 8, epochs 3 inside 2 and 5, and window orders 1 and 3 inside order 1 alone and orders 1 3 5
Pitfall Why It Happens How to Detect How to Fix
Scoring with the input table on both sides It is node2vec’s published convention and what gensim’s wv[node] hands you; on a homogeneous graph it is correct Community purity below the 1/n_communities floor, median rank far worse than popularity’s, while the loss looks normal Score W_user . V_item, the pair the loss trained. Costs 0.0327 against 0.4207 if you get it wrong
A symmetric context window on a bipartite graph Every tutorial uses one, and the graph’s alternation is invisible in the corpus Compute the share of pairs that are cross-type; 0.547 instead of 1.000 is the signature Keep odd offsets only. Removes 45% of the corpus and gains 0.0247 recall
Tuning p and q as two parameters The paper presents them as independent breadth and depth dials Census the three candidate classes; a zero count in the distance-1 class proves the collapse Tune the single ratio q/p, or use DeepWalk and spend the time elsewhere
Early stopping on the training loss The loss is the only thing training reports and it falls monotonically Loss and recall@20 diverge after epoch 3; purity keeps rising while recall falls Early stop on segmented recall@k. The loss selects epoch 8, which costs 0.1570
Citing word2vec’s negative-sampling exponent 0.75 is published, ubiquitous and rarely re-derived Sweep it; 0.5 is the interior optimum here and 0.75 costs 0.0250 Sweep the exponent on your own degree distribution and watch coverage alongside recall
Test edges left in the graph before walking The corpus is built from the graph, so the leak propagates through walks rather than appearing in one cell Metric rises smoothly with no spike; assert test pairs are absent from the train edge set Rebuild the graph from train edges and assert zero overlap, printing the result
Comparing a tuned model against cited-default baselines Tuning your own method is the interesting work; tuning the baseline is not Check whether each sweep’s optimum is interior; a boundary argmax is a wall Sweep every method with equal effort. Tuning ALS moved it from 0.2283 to 0.4153

The fifth and seventh rows are the same mistake in two costumes, and the seventh is the one that nearly produced a wrong post. Our first headline table had ALS at its commonly cited settings of alpha = 40 and regularization = 0.02, where it scores 0.2283, against node2vec at 0.4073, so the walk appeared to win by 0.1790 and the conclusion wrote itself. Sweeping ALS properly moved it to alpha = 2.0, regularization = 30.0 and 0.4153, which is 0.0054 behind rather than 0.1790 behind. The first ALS grid also found a wall rather than an optimum: its best cell sat at the very corner, alpha = 1.0 and regularization = 10.0 with the grid stopping at 10, and extending it to 300 moved the optimum to an interior cell. Tuning the baseline erased 97% of the apparent win.

Key Insight

Four of these seven pitfalls are invisible in the training loss, and three of them are consequences of a single structural fact: a bipartite graph has no odd cycles. That fact empties node2vec's distance-1 candidate class, makes half a symmetric context window the wrong entity type, and breaks the published scoring convention. When a method is ported to a graph shape its authors did not have in mind, the useful first move is not to tune it but to ask which of its assumptions the new shape violates, because the violations arrive together.

Common Pitfall

The single most common mistake on this exact problem is taking the embeddings out of a library by the obvious accessor and scoring with them. gensim's wv[node] returns the input table, never mentions that an output table exists, and on a bipartite user-item graph that one default is the difference between 0.4207 and 0.0327 at an identical training loss. The failure is silent, it is catastrophic, and no amount of walk tuning or dimension tuning recovers any of it. Before trusting any embedding, score the training objective's own pair and check it against a popularity baseline.

Scaling and Productionizing

What changes between this notebook and a real deployment is mostly about which object stops fitting, and the answer is not the graph.

The graph is cheap. A CSR adjacency stores two int32 entries per edge, so our 42,519 edges are about 400 KB and 100 million edges would be roughly 800 MB, which still fits on one machine. What stops fitting is the dense score matrix: our 3,000 by 1,200 float64 array is 28 MB, and the evaluation code builds it without thinking. At a million items it is 24 GB for the same 3,000 users, and at a realistic user count it is the 40 TB in the envelope below, so full-catalogue ranking has to become per-user-batch retrieval against an approximate nearest neighbour index, which is post 27’s subject and inherits its recall-versus-latency trade directly. The item-item matrix the two-hop baseline builds has the same problem sooner: 1,200 squared is 11.5 MB and a million squared is 8 TB, which is precisely the point at which the walk becomes the only option and the comparison in this post inverts.

back of envelope, 10M users and 1M items, 500M edges
  CSR adjacency                 500M * 4B * 2 directions     ~4.0 GB
  walk corpus, 10 per node, L16 11M nodes * 10 * 16 * 4B     ~7.0 GB
  skip-gram pairs, parity 1,3   ~3.5e9 pairs                 streamed, not stored
  embedding table, dim 128      11M * 128 * 4B               ~5.6 GB
  item-item two-hop matrix      1e6 ^ 2 * 8B                 8.0 TB  (does not exist)
  dense score matrix            1e7 * 1e6 * 4B               40 TB   (does not exist)

Retraining cadence is set by graph churn rather than by drift in the usual sense. The embeddings are transductive, so any item added since the last training run has no vector at all, which means the retrain interval is an upper bound on how long a new item stays invisible. On a marketplace with daily new listings, a weekly retrain means up to seven days of invisibility for new inventory, and that is usually unacceptable, which is the single strongest practical argument for replacing this method with a feature-based GNN rather than for tuning it.

The monitoring signal that catches this model degrading silently is the share of served impressions whose items were in the last training corpus, tracked daily, alongside segmented recall@20 on a rolling holdout split the same way as training. The first catches the transductive failure, where coverage of the live catalogue erodes as new items accumulate and the model quietly recommends only the old ones. The second catches the quality failure. Neither is the training loss, which this post measured going the wrong way twice. Exposure Gini belongs on the same dashboard, since the negative-sampling exponent moves it from 0.979 to 0.781 across its range and a retrain that lands on a different exponent changes the concentration of the whole product surface.

Key Insight

The production question is not "is node2vec good", it is "at what catalogue size does the exact path count stop being computable". Below that size the exact count wins on every axis including quality. Above it the exact count does not exist. Compute the crossover for your own catalogue before adopting either, because it is a memory arithmetic problem with a definite answer rather than a modelling preference.

Real World

Pinterest's PinSage (Ying et al., KDD 2018) is this class of problem solved at 3 billion nodes and 18 billion edges, and it is instructive that it is not node2vec. PinSage keeps the random walks, and uses them for importance-weighted neighbour sampling inside a graph convolution rather than as a word2vec corpus, so the embedding becomes a function of node features and is therefore inductive. Alibaba's billion-scale commodity embedding work (Wang et al., KDD 2018) took the other branch, keeping the walk-plus-skip-gram structure and attacking cold start by adding side-information embeddings. Both production systems kept the walk and replaced the part this post measures as weakest: learning identity-only embeddings that cannot generalise to a node the corpus never contained.

Alternative Approaches

approach recall@20 measured here training cost serving cost handles new items interpretability best fit
Popularity 0.2547 0.00s, one bincount trivial, one sorted list yes, immediately total a floor you must beat, and the cold-start fallback
Two-hop path count 0.4207 0.08s, one matrix product O(items squared) memory partially, once it has one edge high, every score traces to shared users catalogues under roughly 100k items
Three-hop path count 0.4227 0.10s O(items squared) memory partially moderate, two chained similarities same, when the graph is sparse enough that two hops misses
ALS matrix factorisation 0.4153 1.91s dot product, ANN-friendly fold-in possible for users low, latent factors large sparse catalogues with a stable item set
node2vec 0.4207 17.31s dot product, ANN-friendly no, transductive low very large graphs where the exact count does not fit
LightGCN or PinSage not measured here hours on a GPU dot product plus feature lookup yes, inductive low production, when new items must be served immediately

On this graph, with 1,200 items, we would ship the three-hop path count. It is the best number in the table, it runs in 0.10 seconds, every score is traceable to a set of shared users, and it has no hyperparameters that a retrain can silently move. Choosing node2vec here would be paying 173 times the fit time for a tie on the headline metric and a 0.0020 loss against the best.

The point at which we would switch is specific and it is not about quality. When the item-item matrix stops fitting in memory, somewhere around 100,000 to 500,000 items depending on sparsity, the exact count stops being an option and the walk becomes the cheapest estimator of the same quantity. And if new items must be servable within hours rather than at the next retrain, we would skip node2vec entirely and go to a feature-based GNN, because the transductive limitation is architectural rather than a tuning problem. The honest summary of this post is that node2vec occupies a real but narrow band: graphs large enough that exact path counting is impossible, and item sets stable enough that transductive embeddings are acceptable.

Key Insight

Four methods spanning a 216-fold range in fit time land inside 0.0074 of each other on recall@20, and at matched dimension ALS is ahead of node2vec at 8, 16 and 32 dimensions. When several unrelated methods converge to the same number, the ceiling is being set by the information in the data rather than by any model, and further model work has no headroom to find. The useful response is to go and get more signal: edge types, timestamps, item features, or a diversity objective, which is the next post.

Key Takeaways

  • The graph framing is a reframing, not a new source of signal. Item-item collaborative filtering is already a path count. Writing it as a graph makes the generalisation to longer paths visible, and on this graph the longer paths turn out to be worth 0.0027 at order 5 and negative 0.0200 at order 7.

  • A walk samples what a matrix product counts. Under the parity rule the walk collects paths of length 1 and 3, and the two-hop baseline computes exactly those. The sampled estimate tied the exact count at 0.4207 and cost 216 times more. A walk earns its place when the exact count stops fitting in memory, which is a statement about catalogue size.

  • Bipartite graphs have no odd cycles, and that one fact breaks three things in node2vec. The distance-1 candidate class is empty, so p and q collapse to the ratio q/p. Half of a symmetric context window trains same-side pairs. And the published scoring convention compares two vectors that no gradient ever brought together.

  • Score the pair the objective trained. W_user . V_item gives 0.4207; W_user . W_item, which is the convention and the library default, gives 0.0327 at an identical loss of 1.6007, with a purity of 0.035 beneath the 0.125 random floor.

  • The training loss is actively misleading here, twice. It falls monotonically while recall drops 0.1570 after epoch 3, and across the negative-exponent sweep its minimum sits at exponent 0.00, which ranks 0.1270 below the best setting. Early stopping and model selection must use a segmented ranking metric.

  • Tune the baseline with the same effort as the model. ALS went from 0.2283 at its cited defaults to 0.4153 when swept, which erased 97% of node2vec’s apparent advantage. A sweep whose optimum sits on a grid boundary has found a wall, not an optimum.

  • Report the structure metric and the ranking metric side by side. Three separate sweeps here show purity rising while recall falls. The highest-purity scoring rule ranks 0.1374 worse than the best, and purity of 0.908 at order 7 comes with 0.0200 less recall.

  • Transductive is the limitation that actually decides adoption. No vector exists for an item the corpus never contained, so the retrain interval is an upper bound on new-item invisibility. Both billion-scale production systems that kept the walk replaced exactly this property.

The counter-intuitive lesson is about which numbers a method asks you to choose and which it chooses for you. Moving each advertised knob from its conventional value to its swept optimum was worth very little: 0.0070 for the second-order bias over DeepWalk, 0.0127 across the entire q/p range, and 0.0250 for replacing word2vec’s published negative exponent of 0.75 with the measured 0.5. Meanwhile the one quantity node2vec does not present as a choice at all, which table you score with, was worth 0.3880. That is not an argument that hyperparameters do not matter, and the same exponent sweep proves it: pushed to 1.5 it costs 0.3584, which is nearly as much as the scoring bug. It is an argument that the published defaults of a mature method are usually already close, so the variance that bites you lives in the decisions nobody wrote down as decisions. The only way to find those is to measure the quantity you are going to serve rather than the one the library reports.

Frequently Asked Questions

Q: Why not just use DeepWalk, if p and q collapse to one parameter anyway?

A: On a purely bipartite graph you should strongly consider it. DeepWalk is p = q = 1, scores 0.4137 against the best biased walk’s 0.4207, needs no neighbour-set lookups, and runs on a fully vectorised code path that generated our corpus in 0.0 seconds against 1.4 for the biased version. The 0.0070 of recall is real but it is the smallest effect of any decision in this post. The argument for keeping the machinery is that real interaction graphs are usually not purely bipartite once you add item-item edges from a taxonomy or user-user edges from a social graph, and the moment any odd cycle exists the distance-1 class is non-empty and p and q separate again.

Q: Why not ALS, which is simpler, better understood and ran 9 times faster?

A: On this graph that is close to the right answer, and at matched dimension it is the right answer: ALS is ahead at 8, 16 and 32 dimensions by 0.0003, 0.0010 and 0.0010, and behind by only 0.0053 at 64. The case for the walk is that it extends where ALS does not. ALS factorises the adjacency matrix and so only ever sees order-1 structure; the walk corpus can include any path length you choose to sample, which matters on graphs with heterogeneous node types (users, items, queries, sellers, categories) where the useful signal genuinely is five hops away. On a plain user-item bipartite graph where order 3 is where the information stops, that flexibility has nothing to do.

Q: Why not a graph neural network, since you keep saying it is the real answer?

A: Because it is, and it changes the problem rather than improving this solution. LightGCN or PinSage propagate over the same graph but learn the propagation and consume node features, which makes the embedding a function rather than a lookup, and therefore inductive: a new item gets a vector from its features immediately instead of waiting for a retrain. That solves the limitation this post identifies as decisive. What it does not do is beat the ceiling. Four unrelated methods converge within 0.0074 here, which says the graph’s information content is the binding constraint, and our honest expectation is that a GNN would land in the same band on this data. That expectation is not measured in the companion codebase and is labelled an expectation for that reason.

Q: Why is recall@20 the headline rather than NDCG or recall@100?

A: Because with one held-out item per user, recall@20 answers the question a product surface actually poses: did the right item make a 20-slot shelf. NDCG is reported beside it and is the better metric for ordering within the slate, and it is also the one place node2vec clearly wins at 0.2380, so dropping it would have hidden a real result. Recall@100 is reported because it separates retrieval failure from ranking failure: a method with good recall@100 and poor recall@20 has the item in the candidate set and is ordering it badly, which is a different repair. What we would not do is report accuracy-style aggregates or pool the user segments, since the cold segment carries 1,126 of 3,000 test users and moves independently.

Q: How do you keep this from degrading silently in production?

A: Not with the training loss, which this post measured going the wrong direction in two separate sweeps. Track the share of served impressions whose items were present in the last training corpus, which is the signal that catches the transductive failure as new inventory accumulates and the model quietly stops recommending anything recent. Track segmented recall@20 against a popularity baseline recomputed on the same rolling split, so a regression is measured against a moving floor rather than a fixed historical number. And track exposure Gini, because the negative-sampling exponent moves it from 0.979 to 0.781 and a retrain that lands differently reshapes the whole surface’s concentration without changing recall much.

Q: The walk corpus is huge. Does it have to be materialised?

A: No, and at production scale it must not be. We hold 1,411,200 pairs in memory because it is 11 MB and convenient, but the pairs are consumed in shuffled minibatches and never re-read as a whole, so the natural production form is a generator that emits walks and derives pairs on the fly, which is how gensim and every distributed implementation work. The arithmetic above puts a 500-million-edge graph at roughly 3.5 billion pairs, which is streamed rather than stored. The piece that genuinely has to be materialised is the embedding table, at about 5.6 GB for 11 million nodes at dimension 128.

Interview Questions

Q: You train node2vec on a user-item bipartite graph and the recommendations are worse than random, but the loss curve looks textbook. Walk me through your diagnosis.

Expected depth: the candidate should separate “the objective is wrong” from “the thing I am evaluating is not the objective”. The specific answer is the two-table problem: SGNS optimises W_a . V_b and the conventional accessor returns W, so scoring W_user . W_item evaluates a quantity no gradient ever touched, which on a bipartite graph is uncorrelated or worse. Strong answers reach for a structure diagnostic against a known floor (community purity against 1/n_communities, or a degree-correlation check) to distinguish “uninformative” from “anti-correlated”, and note that an identical loss across all scoring rules is the tell that the bug is after training.

Q: Derive what the parameters p and q do on a bipartite graph, and say how many free parameters node2vec really has there.

Expected depth: the three candidate weights (1/p for returning to prev, 1 for a neighbour of prev, 1/q otherwise), then the key observation that a candidate reached from cur has the same bipartition class as prev while all of prev’s neighbours are in the other class, so the distance-1 set is empty. Equivalently, a bipartite graph has no odd cycles. Hence the weights are 1/p and 1/q only, the walk depends on the ratio q/p, and there is one free parameter. The best answers predict that reciprocal pairs like (1, 4) and (0.25, 1) must be exactly equivalent, and note that any item-item or user-user edge restores the second parameter.

Q: Your context window is 4 and your graph is bipartite. What fraction of skip-gram pairs is usable for user-to-item scoring, and what do you do about it?

Expected depth: a walk alternates sides, so offset parity determines pair type; offsets 1 and 3 are user-item and offsets 2 and 4 are same-side. With a symmetric window roughly half the pairs are same-side, measured at a cross-type share of 0.547. The fix is to emit only odd offsets, which removes 45% of the corpus and improves recall@20 by 0.0247, so it is simultaneously cheaper and better. Candidates should also recognise that same-side pairs are not worthless in general, since item-item similarity is exactly what an item-to-item recommendation surface needs, and the right framing is that they train a different model which should be scored separately rather than mixed in.

Q: Someone shows you a table where their walk-based recommender beats ALS by 0.18 recall@20. What do you ask?

Expected depth: whether both sides were tuned with comparable effort, and specifically whether the ALS sweep’s optimum was interior or on a grid boundary. Candidates should name the implicit-ALS parameters that matter (confidence weight alpha and regularisation, with factors and iterations second) and note that cited defaults such as alpha = 40 are dataset-specific. The concrete number here: ALS moved from 0.2283 at cited defaults to 0.4153 when swept, so 97% of the gap was the sweep rather than the method. Strong answers add the matched-capacity check, comparing at equal dimension, and ask for across-seed spread before believing any gap of that size.

Q: How would you decide between an exact two-hop similarity and a walk-based embedding for a given catalogue?

Expected depth: this is a memory and latency arithmetic question, not a quality one. The exact count needs an items-by-items matrix, so the crossover is where n_items squared stops fitting: 1,200 items is 11.5 MB, a million is 8 TB. Below the crossover the exact count wins on quality, interpretability and cost (measured at 0.4207 in 0.08 seconds against 0.4207 in 17.31 seconds). Above it the exact count does not exist and the walk is the cheapest estimator of the same quantity. Candidates should also raise sparsity, since a very sparse graph makes two hops reach too little and pushes toward longer paths, and should flag the transductive constraint as a separate and often decisive axis: if new items must be served before the next retrain, neither option works and the answer is a feature-based GNN.

View full code for this problem