Node Embeddings

A node embedding is a short vector for each node, learned from the graph alone. Trained on random walks over a 34-member karate club, two numbers per member place 96% of the other 32 members on the right side, given only members 1 and 34. Trained on shuffled friendships: 55%. Both are averages over 200 runs.

Press Train and watch 34 points sort themselves into two groups. Then train on shuffled friendships. Then we build it piece by piece: the lookup table, the walks, the objective, negative sampling, DeepWalk, node2vec, and the matrix it factorizes.

You need a little Python, what a dot product is and what a probability is. Lecture 1 helps. We build the rest from zero.

Lecture 2, "Node embeddings", of Stanford CS224W, Machine Learning with Graphs (Fall 2026, Jure Leskovec, with Charilaos Kanatsoulis). Previous: Lecture 1, Introduction. Next: Lecture 3, Graph Neural Networks.

Learn a vector for every member

20 epochs

Illustrative toy on real ties: Zachary's 34 members and 78 friendships (via NetworkX). DeepWalk trains in your browser: 10 walks of 10 nodes per member, window 5, 5 negatives, 2 numbers per member, 20 epochs. Training sees no labels. Then each member joins member 1 or member 34, whichever its vector points closer to (cosine). The picture is this run; the 96% and 55% are averages over 200 runs.

Chapter 0

Features Someone Had to Choose

Find two members with the same hand features who join opposite sides

Lecture 1 described each node with numbers a person chose: degree, betweenness, closeness and clustering. Then an ordinary classifier did the rest. That works when the person guesses well. It fails when two nodes look the same on paper.

Take member 13 of the karate club. Its four hand features are degree 2, betweenness 0, closeness 0.37 and clustering 1. Member 15 has exactly the same four numbers. Member 13 joins the instructor, Mr. Hi. Member 15 joins the president. No classifier can split two identical inputs.

Compare two members' hand features

Pick a pair, or tap any two members. The yellow bars are the four features from Lecture 1. Then place every member by hand features alone.

Real ties (Zachary, 1977); features computed with NetworkX 3.5, the same as Lecture 1. "Place everyone" standardizes the four features and puts each member with member 1 or member 34, whichever it is closer to by cosine.

Hand features describe a node's shape, not where it sits. Members 1 and 34 are the two hubs. Ask which hub each member resembles in hand features, and you place 16 of the other 32 right: a coin flip. The lecture also lists richer counts, such as the graphlet degree vector, which counts the small subgraphs a node sits in (73 shapes up to 5 nodes). Richer, but still shape.

The lecture's answer is representation learning: learn the features from the graph itself. A node embedding gives each node v a vector zv of d numbers. Nodes that are similar in the graph should get vectors that are close in space. Nobody decides what each number means; training on the graph does. The same vectors then serve many tasks: node labels, links, clusters, odd nodes.

Symptom: a classifier on hand features cannot separate members 13 and 15, no matter how long it trains.

Measure: compare their inputs. Both are (2, 0, 0.37, 1.0). Members 16, 19, 21 and 23, all on the president's side, have the same four numbers too.

Fix: give the model something that differs between them: their friends. The hero's vectors learn exactly that, and put 13 and 15 on opposite sides.

The road

  1. Encoder: a lookup table of vectors, scored by a dot product.
  2. Walks: two nodes are similar if short random walks join them.
  3. Objective: a softmax over nodes and a loss to minimize.
  4. Negatives: one real partner, k random strangers, two forces.
  5. DeepWalk: walks become sentences; slide a window; take SGD steps.
  6. node2vec: steer each step with p and q.
  7. Matrix view: what DeepWalk factorizes.
  8. Showcase: train the club with every knob.
  9. Uses and limits: links, graphs, and what shallow vectors cannot do.
  10. Field guide: the numbers, the code and the road ahead.
Why can no classifier on hand features separate members 13 and 15?

Chapter 1

A Lookup Table and a Dot Product

Store one column per node, and score a pair of nodes by the dot product of their columns

Every method in this lecture has two parts. The encoder maps a node to its vector. The decoder maps two vectors to a score, and that score should match how similar the two nodes are in the graph.

The simplest encoder is a lookup table. Keep a matrix Z with d rows and one column per node. The encoder for node v returns column v: ENC(v) = zv = Z · v, where v here is a one-hot vector, all zeros except a 1 at position v. Training changes the numbers in Z. This is a shallow encoder: no layers, one free vector per node.

Look up two columns, multiply, add

Each column of the strip is one member's two numbers. Pick a pair, or tap two columns. The arrows are the two vectors; the purple number is their dot product.

The vectors are the hero's default run (real friendships, 20 epochs), so they are one trained toy, not a standard. We round the numbers to two places.

The decoder is the dot product. Call the vectors of nodes u and v zu and zv, each with d entries. Call their i-th entries zu,i and zv,i.

Say it aloud

z-u transpose z-v equals the sum over i from one to d of z-u-i times z-v-i.

zuTzv
z-u transpose z-v the dot product of the two vectors: the decoder's similarity score.
Σi=1d
the sum over i from one to d add one term for each of the d entries. Here d = 2.
zu,i
z-u-i entry i of node u's vector: row i, column u of Z.
zv,i
z-v-i entry i of node v's vector.
In plain words

Look up columns u and v of Z. Multiply them entry by entry, z-u-i times z-v-i. Add the products. The total is large when the vectors point the same way and are long.

With numbers

From the device, rounded to two places: z for member 1 is (1.19, 0.31) and for member 2 is (0.93, 0.44). The products are 1.107 and 0.136, so the dot product is 1.24. Member 34 is (−0.15, 1.40): with member 1, −0.178 + 0.434 = 0.26. Members 1 and 2 are friends on one side; 1 and 34 lead opposite sides.

The goal: zuTzv ≈ similarity(u, v). The rest of the lecture is two choices: what "similar" means, and how to fit Z to it. The training is unsupervised: it uses no labels and no node features, so the vectors serve any task.

Symptom: the embedding table does not fit in memory.

Measure: Z holds |V| × d numbers. The club: 34 × 2 = 68. A graph with 1 billion nodes at d = 128 and 4 bytes per number: 109 × 128 × 4 = 512 GB.

Fix: split the table across machines, or use an encoder whose size does not grow with the node count: a graph neural network (Lecture 3).

In the lookup encoder ENC(v) = Z · v, what does column v of Z hold?

Chapter 2

Similar Means Seen on the Same Walk

Define similarity by where short random walks from a node land

What should "similar" mean? The lecture lists three options: two nodes share an edge, they share neighbours, or they play the same role. Linked is too strict. Two members with ten friends in common but no tie of their own should still sit close.

A random walk answers this. Start at node u. Pick one of its neighbours at random and move there. Repeat. The nodes the walk visits form u's random-walk neighbourhood, NR(u). It is a multiset: a node visited twice appears twice. If walks from u often land on v, then u and v are similar.

Walks buy two things. They see past one hop, so shared friends count. And training only needs the pairs that turn up on walks, not all |V|2 pairs.

Walk from a node and count the visits

Tap a node to start there. Walk once to watch one walk; walk 200 times to fill the blue bars. The outlines are the exact answer, row u of S. Then make the walks longer.

T = 5

Illustrative nine-node graph, the same as the Code Labs: triangles 0, 1, 2 and 6, 7, 8 joined by the chain 2, 3, 4, 5, 6. A walk takes T steps and counts the node it stands on after each step.

We can compute what endless walks would give. Call the number of edges at node u its degree ku. One step from u goes to each neighbour with probability 1/ku. Put these in a matrix M, the transition matrix: Muv = Auv / ku, with A the adjacency matrix. Call the walk length T and the average visit share S.

Say it aloud

S equals one over T, times the sum over r from one to T, of M to the r.

S
S the walk matrix: S-u-v is the share of a T-step walk from u that stands on v.
1/T
one over T divide by the number of steps, so each row of S adds to 1.
Σr=1T
the sum over r from one to T add one term for each step count r.
Mr
M to the r M multiplied by itself r times. Cell (u, v) is the chance that a walk from u stands on v after exactly r steps.
In plain words

Raise M to each power r from 1 to T. Add the T matrices and divide by T. Row u of S says where a T-step walk from u spends its steps.

With numbers

The device's graph, from node 0, T = 5. The chance of standing on node 1 after steps 1 to 5 is 0.50, 0.17, 0.29, 0.21 and 0.23. Their average, S-0-1, is 0.28. Node 5, four hops away, gets S-0-5 = 0.0125.

Symptom: the two triangles get the same walk profile, so their vectors cannot separate.

Measure: from node 0, the share of steps in its own triangle. T = 5: 83%, and 0.4% in the far triangle. T = 100: 43% and 28%. At T = 1,000 the walk forgets its start, and each node's share tends to its degree over 20.

Fix: keep walks short. DeepWalk pairs each node only with the nodes within 10 steps of it.

In a random-walk embedding, what is NR(u)?

Chapter 3

Make the Seen Nodes Likely

Turn dot products into a probability over nodes, and the walks into a loss

Now fit Z to the walks. For each node u, its vector should predict the nodes in NR(u). Call the model's chance that a walk from u visits v P(v | zu).

The lecture uses the softmax: raise e to each dot product, then divide by the total, so the chances are positive and add to 1. Call the set of all nodes V and any node in it n.

Say it aloud

P of v given z-u equals exp of z-u transpose z-v, over the sum over n in V of exp of z-u transpose z-n.

P(v | zu)
P of v given z-u the model's chance that a walk from u visits v.
exp(zuTzv)
exp of z-u transpose z-v e raised to the dot product: always positive, and larger for aligned vectors.
Σn∈V
the sum over n in V add one term for every node n in the graph, u included.
exp(zuTzn)
exp of z-u transpose z-n the same score for node n.
In plain words

Take the dot product of z-u with every node's vector. Raise e to each one. Divide v's term by the sum of all the terms.

With numbers

With made-up numbers: three nodes, z-u = (1, 0), z-a = (0.8, 0.6), z-b = (−0.6, 0.8). The dot products with z-u are 1, 0.8 and −0.6. Their exps are 2.72, 2.23 and 0.55, with total 5.49. So P(a | z-u) = 2.23 / 5.49 = 0.41, and P(b | z-u) = 0.10.

A good Z makes the visited nodes likely. Call the total cost L. For every node u and every visit v in NR(u), add the surprise: minus the log of P.

Say it aloud

L equals the sum over u in V, of the sum over v in N-R of u, of minus log P of v given z-u.

L
L the loss: the total surprise over all walks. Training makes it small.
Σu∈V
the sum over u in V one term for each start node u.
Σv∈NR(u)
the sum over v in N-R of u one term for each visit on walks from u, repeats included.
−log P(v | zu)
minus log P of v given z-u the surprise: 0 if the model was sure of v.
In plain words

For each start u and each visit v on its walks, take minus the log of P(v | z-u). Add them all. L is low when the vectors predict the walks.

With numbers

Same made-up vectors, and N-R(u) = a, a, b. Minus log 0.41 is 0.90, twice; minus log 0.10 is 2.30. So u adds 0.90 + 0.90 + 2.30 = 4.11 to L, most of it from b, the visit the vectors did not expect.

Drag one vector and watch the softmax

Each dot is one node's vector. Drag the ringed one, z-u. Purple bars are P(v | z-u); blue outlines are the walk shares it should match. Bring the loss down.

Illustrative vectors, placed by hand round a circle of radius 1.8. The loss is the surprise per step: the walk shares S (T = 5) times minus log P, added over the nine nodes.

Training moves every vector downhill on L. For zu the slope is "observed minus expected": it pulls zu toward the nodes its walks saw and away from the P-weighted average of all nodes. Word vectors use the same gradient; CS224N Lecture 2 derives it step by step.

Symptom: one pass over the walks of a large graph takes days.

Measure: the denominator adds |V| terms for every visit, so the cost grows as |V|2. With 1 million nodes: a million exponentials per pair.

Fix: approximate the denominator with a few random nodes: negative sampling, next chapter.

Why is the exact softmax too slow on a graph with a million nodes?

Chapter 4

Negative Sampling: One Partner, k Strangers

Replace the sum over all nodes by a few random ones, and see the two forces it makes

Negative sampling asks a yes-or-no question instead: is (u, v) a real walk pair, or noise? A real pair should score high; a few random nodes, the negative samples, should score low.

The yes-or-no score uses the sigmoid, σ(s) = 1/(1 + e−s), which maps any number into the range 0 to 1. Call the walk partner v, the number of negatives k, and the negatives n1 to nk. The lecture draws each negative in proportion to its degree. Call the loss for one pair ℓ.

Say it aloud

Ell equals minus log sigma of z-u transpose z-v, minus the sum over i from one to k, of log sigma of minus z-u transpose z-n-i.

ℓ
ell the loss for one walk pair (u, v) and its k negatives.
−log σ(zuTzv)
minus log sigma of z-u transpose z-v the cost of doubting the real pair.
Σi=1k
the sum over i from one to k one term for each negative sample.
log σ(−zuTzni)
log sigma of minus z-u transpose z-n-i the log chance that negative n-i is noise.
In plain words

The sigmoid of z-u dot z-v should be near 1, and so should the sigmoid of minus z-u dot each z-n-i. Add minus the log of each score to get ell.

With numbers

With made-up numbers: z-u = (1, 0), partner z-v = (0.8, 0.6), k = 2 negatives (−0.6, 0.8) and (0.6, −0.8). Dot products 0.8, −0.6 and 0.6. The terms are −log σ(0.8) = 0.37, −log σ(0.6) = 0.44 and −log σ(−0.6) = 1.04. So ell = 1.85.

Its slope for zu, ∂ℓ/∂zu, uses one fact: the slope of log σ(s) is 1 − σ(s).

Say it aloud

The partial of ell with respect to z-u equals minus, one minus sigma of z-u transpose z-v, times z-v, plus the sum over i of sigma of z-u transpose z-n-i, times z-n-i.

∂ℓ/∂zu
the partial of ell with respect to z-u the direction that raises ell fastest.
−(1 − σ(zuTzv)) zv
minus, one minus sigma of the pair score, times z-v the pull toward z-v, harder when the pair scores low.
Σi
the sum over i one term per negative.
σ(zuTzni) zni
sigma of z-u transpose z-n-i, times z-n-i the push away from z-n-i, harder when the stranger looks similar.
In plain words

Scale z-v by one minus sigma, how much the real pair still doubts, and subtract. Scale each z-n-i by sigma, how similar it looks, and add. Step z-u against this sum.

With numbers

Same numbers: −0.31 × (0.8, 0.6) + 0.35 × (−0.6, 0.8) + 0.65 × (0.6, −0.8) = (−0.07, −0.42). A finite-difference check agrees to 2 × 10−10. One step with rate 0.1 moves z-u to (1.007, 0.042), and ell falls from 1.846 to 1.828.

Pull one partner, push k strangers

The nine vectors start random on a circle. Train and watch the two triangles move apart. The arrows on node 0 are one step's forces: blue pulls toward its partner, dashed grey pushes from strangers. Then set k to 0.

k = 5

Illustrative toy, the same loop as Code Lab 2: 150 epochs; each node takes one neighbour as its partner and k uniform negatives; rate 0.2; every vector goes back onto the unit circle after each epoch. Averages over 200 starts: separation 1.56 with k = 5, 1.73 with k = 1, 0.65 with k = 0.

k sets the cost: k + 1 dot products per pair instead of |V|, with k = 5 to 20 in practice. A larger k gives steadier estimates but weights negatives more. Strictly, this is noise contrastive estimation, not the softmax objective.

Symptom: all vectors drift to one spot.

Measure: with k = 0 the triangles' centres end 0.65 apart on average, some at 0.00; with k = 5, 1.56.

Fix: keep negatives. With pulls alone, the best answer is all vectors equal.

In the negative-sampling gradient, what does each negative sample do to z-u?

Chapter 5

DeepWalk: Walks Become Sentences

Generate the walks, slide a window over each, and take one gradient step per pair

DeepWalk (Perozzi, Al-Rfou and Skiena, KDD 2014) puts the pieces together. Its walks are uniform: each step picks a neighbour with probability 1/k. It treats each walk as a sentence and each node as a word, and trains word2vec's skip-gram on them. CS224N Lecture 2 builds skip-gram for words; here the words are member numbers.

  1. Run R walks of L nodes from every node.
  2. Slide a window of width w along each walk. Every node within w places of u forms a pair (u, v).
  3. For each pair, draw k negatives and take one step on ℓ with a learning rate η: zu ← zu − η ∂ℓ/∂zu. One step per pair is stochastic gradient descent (SGD).

Turn one walk into training pairs

A new walk traces blue across the club, then appears as a sentence of member numbers. Slide the window along it: each lit box pairs with the centre one. Change the window width.

w = 5
place 1

Real ties (Zachary, 1977). Walks of 10 nodes, uniform steps, as in the hero.

A walk of L = 10 nodes with window w = 5 gives 70 pairs: a node in the middle has 10 partners, the ends fewer. The hero's corpus is 34 × 10 = 340 walks, so 23,800 pairs per epoch. The DeepWalk paper used 80 walks per node of length 40, a window of 10 and d = 128.

Two details from real code. DeepWalk itself replaced the softmax with a hierarchical softmax, a binary tree over the nodes; node2vec and this lecture use negative sampling, as this page does. And word2vec keeps two tables: z for a node as the centre u, and a second "context" vector for a node as the partner v. The lecture writes z for both to keep the maths short. The embedding is z.

Symptom: train the same graph twice and the coordinates differ completely.

Measure: hero runs 1 and 2 (seeds 5 and 6): member 1's vector points at 15° in one and −133° in the other. Yet the cosines between all 561 pairs of members agree, with correlation 0.99.

Fix: compare embeddings by dot products or cosines, never by raw coordinates. The loss sees only dot products, so any rotation of all vectors is equally good. The lecture lists this as a limitation.

What makes DeepWalk's walks "uniform"?

Chapter 6

node2vec: Steer the Walk With p and q

Weight each next step by its distance from the previous node, and move between a near view and a far one

Uniform walks fix one idea of a neighbourhood. node2vec (Grover and Leskovec, KDD 2016) adds two knobs that slide between BFS, breadth-first search, which samples the nodes near the start, and DFS, depth-first search, which runs far out.

The node2vec walk is second-order: the next step depends on where the walk came from. Say it just moved from node t to node w. Each neighbour x of w is at distance dtx = 0, 1 or 2 from t. It gets a weight α(t, x) set by the return parameter p and the in-out parameter q. Call the neighbours of w N(w).

Say it aloud

P of x given t and w equals alpha of t and x, over the sum over y in N of w of alpha of t and y. Alpha is one over p, one, or one over q, for d-t-x of zero, one or two.

P(x | t, w)
P of x given t and w the chance that the walk, at w and just in from t, steps to x.
α(t, x)
alpha of t and x x's unnormalized weight, set by its distance from t.
Σy∈N(w) α(t, y)
the sum over y in N of w of alpha of t and y the total weight of w's neighbours.
1/p
one over p the weight to step back to t.
1/q
one over q the weight to step away from t.
dtx
d-t-x the hop distance from t to x: 0, 1 or 2.
In plain words

Stand at w. Give t weight 1 over p, each neighbour that also touches t weight 1, and the rest weight 1 over q. Divide by the total and step at random.

With numbers

From the device, on the real club: the walk came from member 1 to member 3. Member 3's neighbours are member 1 (return), members 2, 4, 8, 9 and 14 (also friends of 1) and members 10, 28, 29 and 33 (away). With p = 1 and q = 0.5 the weights total 1 + 5 × 1 + 4 × 2 = 14. Each away step gets 2/14 = 14%, and moving away overall 57%, against 40% for a uniform walk.

Bias the next step with p and q

The walk just came from member 1 to member 3. Blue bars are the chances of each next step, grouped by distance from member 1. Move p and q, then run 10-step walks and see how far they go.

p = 1
q = 0.5

Real ties (Zachary, 1977). p and q take the paper's grid: 0.25, 0.5, 1, 2, 4. "How far" is the average hop distance from member 3 after 10 steps, over 2,000 walks that start with the step from member 1.

The paper links DFS-like walks to homophily: nodes in one community embed together. It links BFS-like walks to structural equivalence: nodes with the same role embed together. On the Les Misérables network (77 characters, 254 edges), q = 0.5 grouped characters by sub-plot and q = 2 by role, both with p = 1. With p = q = 1, node2vec is DeepWalk.

On the karate club the choice barely matters. Over 200 runs, q = 2 places 97% of the 32 members right, q = 1 places 96% and q = 0.5 places 94%.

Symptom: node2vec runs out of memory on a dense graph.

Measure: it stores step chances for every edge (t, w) and neighbour of w: O(a2 |V|) memory, a the average degree. At a = 50 and 1 million nodes, about 2.5 × 109 entries.

Fix: sample each step on the fly, or use uniform steps, which need no table.

You want node2vec walks to roam far from where they came from. Which setting does that?

Chapter 7

The Matrix DeepWalk Factorizes

See that a d-number embedding is a rank-d copy of a matrix built from walks

Go back to the plainest similarity: u and v are similar if they share an edge. Then we want zuTzv = Auv for every pair, which is ZTZ = A. With d far smaller than the node count, an exact fit is impossible. So the lecture minimizes the gap ‖A − ZTZ‖: the square root of the summed squared cell errors. The dot-product decoder with edge similarity is matrix factorization of A.

Qiu et al. (WSDM 2018, NetMF) showed what DeepWalk with negative sampling factorizes, in the limit of many walks. Name the parts. vol(G), the volume, is the sum of all degrees. D is the diagonal matrix of degrees, so D−1A is the transition matrix M. T is the window size and b the number of negatives.

Say it aloud

Log of: vol of G, times one over T, times the sum over r from one to T of D-inverse A to the r, times D-inverse; minus log b.

log( )
log of the natural log, taken of every cell on its own.
vol(G)
vol of G the volume: all degrees added, twice the edge count.
1/T
one over T divide by the window size T.
Σr=1T
the sum over r from one to T one term per step count.
(D−1A)r
D-inverse A to the r the transition matrix M to the r: the r-step walk chances. With the 1/T and the sum, this is S from Chapter 2.
D−1
D-inverse divide each column v by the degree k-v, so busy nodes do not win by visits alone.
log b
log b the log of the number of negatives, taken off every cell.
In plain words

Build the walk matrix S. Divide each column v by the degree k-v and multiply by vol(G). Take the log of every cell and subtract log b. DeepWalk's dot products z-u transpose z-v approximate this matrix.

With numbers

On the nine-node graph: vol(G) = 20, T = 5, b = 5. S-0-1 = 0.278 and k-1 = 2, so the inner cell is 20 × 0.278 / 2 = 2.78. Then log 2.78 − log 5 = 1.02 − 1.61 = −0.59. Cell (0, 8) is 0, which has no log, so NetMF clips small cells before the log.

Keep d directions of a matrix

Left is the target matrix; right is its best copy built from d directions, the most a d-number embedding can store. Slide d. Then switch the target from walks to edges.

d = 1

Illustrative nine-node graph. The copy is the truncated eigen-decomposition (the best rank-d fit in squared error), computed live; Code Lab 3 does the same with an SVD. S here is a simpler cousin of the NetMF matrix: no degree division and no log.

With d = 1 the copy keeps one direction, the same for both triangles: relative error 0.68, and the mass inside the triangles equals the mass across them. With d = 2 the error is 0.28, and with d = 3 it is 0.15 and the triangles stand apart. An embedding of width d holds a rank-d copy of its similarity matrix.

Symptom: a one-number embedding cannot tell the two communities apart.

Measure: in the rank-1 copy of S, the mass inside the triangles and across them are both 2.11.

Fix: give the embedding room for the community directions. Here d = 3 brings the error to 0.15.

If two nodes are called similar only when they share an edge, what does fitting z-u transpose z-v to that become?

Chapter 8

Train the Club With Every Knob

Choose the walks, the window and the negatives, train, and find what breaks the embedding

Here is the whole pipeline on the karate club, with the knobs of the last five chapters. Pick a walk: uniform DeepWalk, node2vec that stays close (q = 2), or node2vec that goes far (q = 0.5). Set the window w and the negatives k. Train. The vectors, the loss and the score update as it learns.

Train the club your way

Fill is the predicted side; red rings are wrong. Choose a walk, set w and k, then press Train. Try w = 1, k = 0, and shuffled friendships.

w = 5
k = 5

Illustrative toy on real ties, computed live with the hero's code: 10 walks of 10 nodes per member, d = 2, 20 epochs. Averages over 200 runs, of the other 32 members: DeepWalk 96%, stay close 97%, go far 94%, w = 1 90% (worst run 11 of 32), k = 0 78% (worst run 9 of 32), shuffled 55%; before training, 50%.

Three things to find. With w = 1 the pairs are only edges: the average falls to 90%, and some runs split the club badly. With k = 0 nothing pushes the vectors apart: the average falls to 78%, and the worst run places 9 of 32. With shuffled friendships, each member keeps its number of friends but not who they are, and the score falls to 55%: the signal was in who knows whom.

Symptom: member 9 lands on the wrong side in 198 of 200 runs.

Measure: member 9 has 5 friends: 1, 3, 31, 33 and 34. Three of them are on the president's side, so its walks spend most of their steps there.

Fix: no walk setting fixes it, because the ties point the other way. Zachary's data shows member 9 joined Mr. Hi anyway. An embedding learns structure, and some labels do not follow structure.

Training on shuffled friendships (same number of friends each, different friends) drops the score from 96% to 55%. What does that show?

Chapter 9

Using Embeddings, and Where They Stop

Score links, build a graph vector, and meet three things shallow embeddings cannot do

Once you have the vectors, any ordinary model can use them. To cluster nodes, cluster their z. To label a node, feed its z to a classifier. To predict an edge (i, j), combine zi and zj and score the result. The lecture lists four ways to combine: concatenate them, multiply them entry by entry (the Hadamard product), add or average them, or take their distance.

To embed a whole graph or a part of one, there are three routes. Sum or average its node vectors, zG = Σv zv; Duvenaud et al. used this to classify molecules. Or add a virtual node joined to every node of the subgraph, and use its embedding. Or cluster the nodes in levels and pool level by level, as DiffPool does.

Ask the embedding three questions

Score links: the dashed blue pairs have the largest dot products among unlinked members. Mirror roles: two nodes with the same role. New member: a member the table has never seen.

K = 10

Score links uses the hero's default vectors. Mirror roles trains DeepWalk on the nine-node graph live (10 walks of 10 nodes per node, window 5). Illustrative toys.

The link scores work. In the hero's run, the top 20 unlinked pairs by dot product all join members of one side; of all 483 unlinked pairs, 42% do. The lecture then names three limits.

Symptom: a new user signs up, and the model has no vector for them.

Measure: Z has 34 columns. Member 35 needs a 35th, and training it means new walks through the old members, so their vectors move too.

Fix: an encoder that computes a node's vector from its neighbours and features, so a new node gets one at once. That is a graph neural network, Lecture 3.

Why can DeepWalk not give a vector to a node added after training?

Chapter 10

Field Guide

Keep the numbers, the code and the road to graph neural networks

A node embedding is a column of a lookup table, scored against other columns by a dot product. Random walks define which nodes should score high. The softmax objective says how to fit them, negative sampling makes it cheap, and DeepWalk and node2vec differ only in how they walk. Underneath, the vectors are a low-rank copy of a matrix of walk statistics.

IdeaRuleThis lesson's number
DecoderzuTzv = Σ zu,i zv,imembers 1 and 2: 1.24; 1 and 34: 0.26
Walk matrixS = (1/T) Σ MrS-0-1 = 0.28 at T = 5
SoftmaxP(v | zu) ∝ exp(zuTzv)toy: P(a | z-u) = 0.41
Walk lossL = Σu Σv −log P(v | zu)toy node u adds 4.11
Negative samplingℓ = −log σ(zuTzv) − Σ log σ(−zuTzn)toy: 1.85, and k + 1 dot products per pair
Gradientpull −(1 − σ) zv, push +σ zntoy: (−0.07, −0.42)
node2vec stepweights 1/p, 1, 1/qfrom member 3, q = 0.5: away 57%
NetMFlog(vol(G) S D−1) − log btoy cell (0, 1): −0.59
Karate resultcosine to member 1 or 3496% real, 55% shuffled, 50% hand features
MethodSimilarityCostNew nodes?
Adjacency factorizationshare an edge: ZTZ ≈ Aevery pair, |V|2no
DeepWalkseen on the same uniform walkpairs on walks onlyno
node2vecseen on the same biased walk (p, q)same, plus step tablesno
Graph neural networklearned from neighbours and featuresgrows with edges, not a table per nodeyes

The whole method in code: walks, pairs, two tables and SGD on the negative-sampling loss, in NumPy. We ran it.

python
import networkx as nx, numpy as np
G = nx.karate_club_graph(); n = 34
nbr = [list(G[v]) for v in range(n)]
deg = np.array([len(a) for a in nbr], float)
rng = np.random.default_rng(0)

walks = []                                          # 1. ten uniform walks of 10 nodes per member
for _ in range(10):
    for s in range(n):
        w = [s]
        while len(w) < 10: w.append(rng.choice(nbr[w[-1]]))
        walks.append(w)
pairs = [(w[i], w[j]) for w in walks for i in range(10)      # 2. window of 5
         for j in range(max(0, i - 5), min(10, i + 6)) if j != i]

d, k = 2, 5
Z = (rng.random((n, d)) - 0.5) / d                  # the embeddings z
C = np.zeros((n, d))                                # word2vec's context vectors
sig = lambda s: 1 / (1 + np.exp(-s))
for ep in range(20):                                 # 3. SGD on the negative-sampling loss
    lr = 0.025 * (1 - ep / 20) + 0.002
    for t in rng.permutation(len(pairs)):
        u, v = pairs[t]
        negs = rng.choice(n, size=k, p=deg / deg.sum())  # in proportion to degree
        g = np.zeros(d)
        for x, lab in [(v, 1)] + [(m, 0) for m in negs if m != v]:
            gg = lab - sig(Z[u] @ C[x])                 # +pull for the partner, -push for a negative
            g += gg * C[x]; C[x] += lr * gg * Z[u]
        Z[u] += lr * g

y = np.array([1 if G.nodes[v]["club"] == "Mr. Hi" else -1 for v in range(n)])
cos = lambda a, b: a @ b / np.linalg.norm(a) / np.linalg.norm(b)
pred = [1 if cos(Z[v], Z[0]) >= cos(Z[v], Z[33]) else -1 for v in range(n)]
print(sum(pred[v] == y[v] for v in range(1, 33)), "of 32 right")

It prints 31 of 32 right, with NumPy's own random numbers; only member 9 is wrong, as in the hero. For real work, PyTorch Geometric ships torch_geometric.nn.Node2Vec, which takes edge_index, the walk length, the window, p, q and the number of negatives.

The road through CS224W, Fall 2026

LecturesTopic
1Introduction: graphs, tasks, hand features and a first round of message passing
2Node embeddings: this lesson
3 to 5Graph neural networks, a general perspective, augmentation and training: the deep encoder that replaces the lookup table
6 to 8Theory of GNNs, powerful graph encoders, graph Transformers
9 to 11Heterogeneous graphs, knowledge graphs, GNNs for recommender systems

Keep going

Read next

The habit. Before you trust an embedding, ask what "similar" meant when it was trained. Walks that measure nearness give vectors that measure nearness, and nothing else.
In one sentence, what does DeepWalk learn?

Now teach it: press Present or Teach. Explain what a lookup encoder is, why walks define similarity, how negative sampling makes training cheap, and what p and q do. Then go back to the club, train on shuffled friendships, and say why the score falls before you look.

Node Embeddings · Stanford CS224W, Lecture 2
Previous: Introduction · Next: Graph Neural Networks · Course site · Back to Gleams