Module contents
Lesson 7 of 30Core 100 min

Node embeddings: factorization, DeepWalk and node2vec

Study shallow node embeddings, matrix factorization, DeepWalk and node2vec, the NetMF connection, structural roles and the limits that motivate graph neural networks.

After this lesson you can

  • Formulate node embeddings using encoder, decoder, target similarity and loss.
  • Implement DeepWalk and node2vec with biased walks and negative-sampling skip-gram.
  • Derive and numerically check the implicit NetMF matrix.
  • Distinguish proximity from structural-role embeddings and select an appropriate representation.
  • Explain the limits of shallow embeddings and how a shared GNN encoder addresses them.

Before you start

A table of vectors per node

We want to represent a dependency network so nodes with similar contexts have vectors useful to a classifier. An embedding encoder and decoder separates four decisions: which similarity to observe, how to assign vector ziz_i to each node, how to predict that similarity and which loss to minimize. In a shallow embedding the encoder is a free table Z∈Rn×dZ\in\R^{n\times d}: querying node ii returns row ziz_i. A common decoder is σ(zi⊤cj)\sigma(z_i\T c_j) with another context table CC; matrix entries or distances can also be reconstructed.

The choice of positive pairs changes the problem. An edge preserves immediate proximity; a walk introduces multi-hop relationships; a role measure seeks similar patterns even when no short path exists. Two nearby vectors do not prove that two accounts coordinate their actions or that two nodes have identical functions.

Factorizing a similarity

Factorization embeddings start from a target matrix. Laplacian eigenmaps seeks smooth coordinates with scale constraints and discards the constant mode, as studied in the eigenmaps lesson. Another family approximates an adjacency or proximity matrix by low rank. For Katz, S=(I−βA)−1−I=∑k≥1βkAkS=(I-\beta A)^{-1}-I=\sum_{k\ge1}\beta^kA^k when βρ(A)<1\beta\rho(A)<1. On a directed graph, HOPE can use an asymmetric factorization S≈ZorigenZdestino⊤S\approx Z_{\rm origen}Z_{\rm destino}\T and retain direction. Forming a dense inverse or matrix limits scale; its definition does not require explicit construction.

DeepWalk and second-order walks

DeepWalk generates walks and treats each node sequence as a sentence. The DeepWalk objective applies skip-gram to center-context pairs within a window. A negative-sampling variant optimizes

log⁡σ(zu⊤cv)+∑r=1bEw∼qnlog⁡σ(−zu⊤cw).\log\sigma(z_u\T c_v)+\sum_{r=1}^b\mathbb E_{w\sim q_n}\log\sigma(-z_u\T c_w).

The original work uses a hierarchical-softmax variant; here we explicitly study the negative-sampling variant to connect with NetMF. The negative distribution qnq_n is part of the objective: choosing degree raised to 0.75 is not the same as choosing the stationary distribution proportional to degree. Short walks starting uniformly from each node are also not exactly stationary from their first step.

In node2vec, the next step depends on the previous node tt and current node vv. For a candidate neighbor xx of vv, the unnormalized weight is wvx/pw_{vx}/p if x=tx=t, wvxw_{vx} if xx neighbors tt, and wvx/qw_{vx}/q if it is distance two from tt. Probability is that weight divided by the sum over candidates. With p=q=1p=q=1 the ordinary weighted walk is recovered. Small pp favors returning; small qq favors exploring distant candidates and large qq favors remaining nearby. These are sampling biases, not guarantees that results recover communities or roles on any graph.

InteractiveWalk and learn

Los colores agrupan comunidades detectadas; se reutilizan si hay más de ocho.

Click to generate the walk and train from scratch before seeing the projection.

1.00
1.00
1
Color
Starting nodeNapoleon
Positive pairsnot run
Final lossnot run
The Les Misérables character network included in NetworkX: 77 nodes and co-occurrence edges, treated here as unweighted. The layout uses seed 42. The button generates a walk and trains an actual skip-gram table in the browser; the PCA projection and colors are aids, not an external evaluation.

The source is the NetworkX co-occurrence graph, based on Stanford GraphBase; we retain its 77 nodes and 254 edges but remove weights. Community color comes from greedy modularity; role color uses only degree ranges. Neither label proves a narrative role. Changing qq can alter sampled context but does not force a particular grouping. In this figure training walks have length 12, fixed window 2, four walks per node, three negatives per positive and three epochs; the highlighted walk has length 18 and another seed. The 2D coordinates project learned six-dimensional vectors.

The alias table converts dd probabilities into two arrays in O(d)O(d); each subsequent draw uses a uniform column and a coin in O(1)O(1). For a second-order walk, precomputing everything requires one table per state (t,v)(t,v): space depends on sums of neighbor degrees and can grow greatly around hubs. The lab builds these tables on demand and reuses them.

The implicit matrix

In a connected undirected graph with positive degrees, P=D−1AP=D^{-1}A, πi=di/vol⁡(G)\pi_i=d_i/\operatorname{vol}(G) and uniform context distance r∈{1,…,T}r\in\{1,\ldots,T\}, the stationary pair has

P(u,v)=πuT∑r=1T(Pr)uv,PMI⁡(u,v)=log⁡[vol⁡(G)T∑r=1T(Pr)uv1dv].\Pr(u,v)=\frac{\pi_u}{T}\sum_{r=1}^T(P^r)_{uv},\qquad \operatorname{PMI}(u,v)=\log\left[\frac{\operatorname{vol}(G)}{T}\sum_{r=1}^T(P^r)_{uv}\frac1{d_v}\right].

The derivation divides the joint distribution by marginals πuπv\pi_u\pi_v. The NetMF connection shows that skip-gram with bb negatives drawn from π\pi ideally targets shifted PMI PMI⁡−log⁡b\operatorname{PMI}-\log b, under the analysis assumptions and without imposing low rank. NetMF factorizes a version truncated at zero, log⁡max⁡(1,exp⁡(PMI⁡)/b)\log\max(1,\exp(\operatorname{PMI})/b); a finite SGD run need not reconstruct each entry exactly. For an impossible pair the untruncated logarithm is −∞-\infty. Qiu and colleagues detail assumptions and extensions to second-order walks.

InteractiveFrom walks to matrix
Theoretical NetMF
1122334455660.30.80.50.00.00.00.80.30.50.00.00.00.50.50.00.00.00.00.00.00.00.00.50.50.00.00.00.50.30.80.00.00.00.50.80.3
Empirical estimate
1122334455660.30.80.50.00.00.00.80.50.50.00.00.00.50.60.00.00.00.00.00.00.00.00.50.50.00.00.00.50.20.80.00.00.00.50.90.4

Graph: two triangles joined by an edge, nodes 1 to 6 in order. Each cell has center by row and context by column; the blue scale is shared.

3
1
10000
Mean absolute difference0.0160
Two triangles connected by an edge. The center is sampled from stationarity and window distance uniformly between 1 and T. Compare truncated NetMF with its empirical estimate using the same b; finite sampling fluctuates.

If the negative is drawn from another distribution qnq_n, the ideal-optimum ratio uses qn(v)q_n(v) instead of πv\pi_v. A corpus of finite walks with endpoints, symmetric windows or another initial distribution can also have different weightings. The stationary-pair experiment isolates the formula; the training lab uses short walks and negatives proportional to degree raised to 0.75, so it is not presented as exactly equal to that matrix.

Proximity, role and new nodes

Structural-role similarity asks, for example, whether two servers are hubs of their networks even if they belong to different components. Walk proximity can group community neighbors without identifying those roles. struc2vec builds contexts from structural similarity at several scales; a degree histogram is a much simpler descriptor and can confuse different structures.

The limits of a shallow table are concrete: it needs O(nd)O(nd) input parameters, provides no row for an unseen node, and excludes attributes unless the objective is modified. Retraining can change old-node coordinates. Even on a fixed graph, a product ZC⊤ZC\T is unchanged under Z↦ZRZ\mapsto ZR and C↦CRC\mapsto CR for an orthogonal matrix RR: comparing coordinates without alignment can mislead. A classifier fitted to old coordinates does not transform automatically when the table changes.

InteractiveA new node arrives

Two two-dimensional tables are trained on connected cliques; the new node joins nodes 2 and 5. Click to measure the change.

New node in old tableno vector
L2 displacementnot run
Changed old predictionsnot run
Two two-dimensional tables are actually trained with the same seed, before and after adding a node to two connected cliques. The centroid classifier is fitted only on the old table. The Procrustes option aligns the eight shared nodes by translation and orthogonal transformation, without guaranteeing identical relationships.

A shared encoder aggregating attributes and neighbors can calculate a representation for a new node with compatible features and neighborhood without adding an identity-trained row. This does not guarantee generalization under every distribution shift or eliminate neighbor-sampling costs. For link prediction, remove test edges before generating walks or learning embeddings; otherwise evaluation leaks the answer directly.

Lab: alias sampling, walks and factorization

The following functions implement alias tables, second-order walks and skip-gram with three negatives per positive and manual gradients. On the graphs without isolates in these examples, negatives are sampled proportional to degree raised to 0.75; code assigns weight 1 to an isolate if present. Walks start uniformly at each node and use a fixed window, making them one concrete finite variant. Separately, NetMF uses the stationary matrix with degree-proportional negatives and applies SVD to shifted, truncated PMI. Logistic regression is fitted from scratch on training labels with standardization computed only from them.

[ ]Walks and embeddings from scratchBrowser
import numpy as np
import networkx as nx
from scipy.stats import chisquare

def alias_setup(weights):
    weights=np.asarray(weights,dtype=float)
    if len(weights)==0 or np.any(weights<0) or weights.sum()<=0: raise ValueError('pesos inválidos')
    n=len(weights); scaled=weights/weights.sum()*n
    prob=np.ones(n); alias=np.arange(n); small=list(np.flatnonzero(scaled<1)); large=list(np.flatnonzero(scaled>=1))
    while small and large:
        s=small.pop(); l=large.pop(); prob[s]=scaled[s]; alias[s]=l
        scaled[l]-=1-scaled[s]
        (small if scaled[l]<1 else large).append(l)
    return prob,alias

def alias_draw(table,rng):
    prob,alias=table; i=int(rng.integers(len(prob)))
    return i if rng.random()<prob[i] else int(alias[i])

def walks(adj,p,q,num_walks,length,seed):
    rng=np.random.default_rng(seed); cache={}; walks=[]
    for start in range(len(adj)):
        for _ in range(num_walks):
            path=[start]
            while len(path)<length:
                u=path[-1]; prev=path[-2] if len(path)>1 else -1
                if not adj[u]: break
                key=(prev,u)
                if key not in cache:
                    weights=[1. if prev<0 else 1/p if v==prev else 1. if v in adj[prev] else 1/q for v in adj[u]]
                    cache[key]=alias_setup(weights)
                path.append(adj[u][alias_draw(cache[key],rng)])
            walks.append(path)
    return walks

def sgns(adj,p=1.,q=1.,seed=0,dim=8,epochs=3,num_walks=5,length=12):
    rng=np.random.default_rng(seed); n=len(adj); paths=walks(adj,p,q,num_walks,length,seed)
    pairs=[]
    for path in paths:
        for i,u in enumerate(path):
            for j in range(max(0,i-2),min(len(path),i+3)):
                if i!=j: pairs.append((u,path[j]))
    U=rng.normal(0,.1,(n,dim)); V=np.zeros((n,dim)); neg=alias_setup(np.array([max(len(r),1)**.75 for r in adj]))
    losses=[]
    for epoch in range(epochs):
        total=0.
        for index in rng.permutation(len(pairs)):
            u,v=pairs[index]
            for label,j in [(1,v)]+[(0,alias_draw(neg,rng)) for _ in range(3)]:
                score=float(np.clip(U[u]@V[j],-30,30)); prob=1/(1+np.exp(-score)); grad=.025*(label-prob)
                total-=label*np.log(max(prob,1e-15))+(1-label)*np.log(max(1-prob,1e-15))
                previous=U[u].copy(); U[u]+=grad*V[j]; V[j]+=grad*previous
        losses.append(total/(4*len(pairs)))
    return U,losses,len(pairs)

def netmf(A,T,b,dim):
    degree=A.sum(axis=1); P=A/degree[:,None]; vol=degree.sum()
    power=np.eye(len(A)); total=np.zeros_like(A,dtype=float)
    for _ in range(T): power=power@P; total+=power
    M=np.log(np.maximum(1.,(vol/(T*b))*total/degree[None,:]))
    U,s,Vt=np.linalg.svd(M,full_matrices=False)
    return U[:,:dim]*np.sqrt(s[:dim]),M

def logistic_score(X,y,train,test):
    mean=X[train].mean(axis=0); std=X[train].std(axis=0); std=np.where(std>1e-9,std,1)
    Z=(X-mean)/std; Z=np.column_stack((Z,np.ones(len(Z)))); w=np.zeros(Z.shape[1])
    for _ in range(800):
        p=1/(1+np.exp(-np.clip(Z[train]@w,-30,30)))
        grad=Z[train].T@(p-y[train])/len(train); grad[:-1]+=.01*w[:-1]; w-=.1*grad
    return float(np.mean((Z[test]@w>=0)==y[test]))

We check a three-weight distribution using 50 000 samples and a chi-square test. A high p-value does not prove the generator perfect; this particular test detects some discrepancies and depends on seed and size. Construction takes linear time in the number of choices, and each subsequent draw takes constant time.

[ ]Check alias samplingBrowser
weights=np.array([2.,1.,.5]); table=alias_setup(weights); rng=np.random.default_rng(3)
samples=np.bincount([alias_draw(table,rng) for _ in range(50000)],minlength=3)
stat,pvalue=chisquare(samples,50000*weights/weights.sum())
print('alias: recuentos',samples.tolist(),'chi-cuadrado',round(float(stat),4),'p',round(float(pvalue),4))
assert pvalue>.001

The Karate Club graph uses the club label included in NetworkX. Embeddings are learned using the full topology, then a classifier is fitted with eight labeled nodes per class; the remaining 18 are test. This is transductive node evaluation, not link prediction. Displayed losses average each epoch’s updates; methods have different objectives and negatives, so one accuracy does not prove general superiority.

[ ]Three embeddings and classificationBrowser
G=nx.karate_club_graph(); A=nx.to_numpy_array(G,nodelist=range(34),weight=None)
adj=[list(np.flatnonzero(row)) for row in A]; truth=np.array([0 if G.nodes[i]['club']=='Mr. Hi' else 1 for i in range(34)])
selection=np.random.default_rng(11); train=[]
for c in (0,1): train.extend(selection.permutation(np.flatnonzero(truth==c))[:8].tolist())
train=np.array(train); test=np.array([i for i in range(34) if i not in set(train)])
for name,p,q in [('DeepWalk',1.,1.),('node2vec',.5,2.)]:
    embedding,loss,pairs=sgns(adj,p,q,seed=8,epochs=2,num_walks=2,length=8)
    print(name,'pares',pairs,'pérdida primera/última época',round(loss[0],5),round(loss[-1],5),'exactitud test',round(logistic_score(embedding,truth,train,test),4))
embedding,M=netmf(A,T=3,b=3,dim=8)
print('NetMF: forma',M.shape,'exactitud test',round(logistic_score(embedding,truth,train,test),4))

Each walk training uses two walks of length eight per node and two epochs. In the execution with stated seeds, DeepWalk correctly classified 13 of 18 test nodes, node2vec 12 and NetMF 10. Mean losses decreased from 0.69084 to 0.65482 and from 0.69126 to 0.65920 in the first two. This is a small graph, one split and a short budget; comparing NetMF with SGD also changes the objective and negative distribution. Repeat splits and budgets before generalizing, and distinguish unlabeled training from classifier fitting.

To check the pair formula, this separate experiment draws centers from the stationary distribution, chooses a uniform distance and simulates steps. The L1 norm compares the full joint distribution with the formula without taking logarithms of empty cells. This numerically checks one realization; it is not an asymptotic proof.

[ ]Stationary pairs and formulaBrowser
# Pares independientes generados en régimen estacionario para contrastar la fórmula.

G6=nx.barbell_graph(3,0); A6=nx.to_numpy_array(G6,nodelist=range(6),weight=None)
degree=A6.sum(axis=1); P=A6/degree[:,None]; pi=degree/degree.sum(); T=3; samples=100000
rng=np.random.default_rng(22); counts=np.zeros((6,6))
u=rng.choice(6,size=samples,p=pi); v=u.copy(); r=rng.integers(1,T+1,size=samples)
for step in range(T):
    selected=np.flatnonzero(r>step); cumulative=np.cumsum(P[v[selected]],axis=1)
    v[selected]=np.minimum((rng.random(len(selected))[:,None]>cumulative).sum(axis=1),5)
np.add.at(counts,(u,v),1)
power=np.eye(6); total=np.zeros((6,6))
for _ in range(T): power=power@P; total+=power
joint=pi[:,None]*total/T
error=np.abs(counts/samples-joint).sum()
print('pares estacionarios: error L1 empírico',round(float(error),5))
assert error<.04

The execution of 100 000 pairs produced L1L^1 error 0.01022 between empirical and theoretical joint distributions. That error is not directly compared with the difference between truncated matrices in the interactive: logarithm, shift and truncation change the scale.

PyG Node2Vec on Cora

The local runtime is independent of Pyodide: hidden setup redefines the necessary NumPy functions. The visible cell requires PyTorch, PyTorch Geometric, pyg-lib, torch-cluster and scikit-learn. It downloads Cora to the system temporary directory on first use. The largest connected component is used, with official train and test masks restricted to its nodes; the full graph of that component is visible during transductive embedding learning.

The installed PyG version defaults to the pyg-lib operator, which in this environment only supports uniform walks. To test p=0.5p=0.5 and q=2q=2, the torch-cluster walk operator is explicitly assigned to this Node2Vec instance. This is version-specific and should be checked when libraries are updated, not treated as a universal API. Walks are sampled on CPU and the table and optimizer use CUDA if available. Training is short: three epochs for each of two seeds, not a converged result.

The NumPy comparison uses the same component and p,qp,q, but one epoch, separate input and context tables, another negative distribution and another window construction; PyG uses one shared table. This is neither a controlled efficiency comparison nor loss equivalence. Both methods use the same logistic classifier and masks for evaluation. Procrustes centers shared vectors and chooses an orthogonal transformation before measuring relative discrepancy; it does not remove scale or geometry differences.

[ ]Node2Vec and alignment on CoraLocal GPU
from pathlib import Path
import tempfile
import torch
import torch_cluster
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import Node2Vec
from torch_geometric.utils import to_networkx
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from scipy.linalg import orthogonal_procrustes
from threadpoolctl import threadpool_limits

data=Planetoid(str(Path(tempfile.gettempdir())/'oryon-graph-datasets'/'cora'),'Cora')[0]
G=to_networkx(data,to_undirected=True,remove_self_loops=True)
keep=sorted(max(nx.connected_components(G),key=len)); index={v:i for i,v in enumerate(keep)}
H=G.subgraph(keep); n=len(keep)
edge_pairs=[(index[u],index[v]) for u,v in H.edges() for u,v in ((u,v),(v,u))]
edge_index=torch.tensor(edge_pairs,dtype=torch.long).t().contiguous()
adj=[[] for _ in range(n)]
for u,v in edge_pairs:adj[u].append(v)
y=data.y.numpy()[keep]; train_idx=np.flatnonzero(data.train_mask.numpy()[keep]); test_idx=np.flatnonzero(data.test_mask.numpy()[keep])
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('componente',n,'aristas',len(edge_pairs)//2,'train/test',len(train_idx),len(test_idx),'dispositivo',device)
if device.type=='cuda': print('GPU:',torch.cuda.get_device_name(0))
def score(z):
    scaler=StandardScaler().fit(z[train_idx]); zz=scaler.transform(z)
    with threadpool_limits(limits=1):
        clf=LogisticRegression(max_iter=1000,random_state=0).fit(zz[train_idx],y[train_idx])
        return float(clf.score(zz[test_idx],y[test_idx]))

embeddings=[]
for seed in (0,1):
    torch.manual_seed(seed)
    model=Node2Vec(edge_index,embedding_dim=16,walk_length=6,context_size=3,walks_per_node=1,
                   num_negative_samples=3,p=.5,q=2.,sparse=True).to(device)
    model.random_walk_fn=torch.ops.torch_cluster.random_walk
    loader=model.loader(batch_size=256,shuffle=True,num_workers=0)
    optimizer=torch.optim.SparseAdam(model.parameters(),lr=.01)
    losses=[]
    for epoch in range(3):
        total=0.; count=0
        for pos,neg in loader:
            optimizer.zero_grad(); loss=model.loss(pos.to(device),neg.to(device)); loss.backward(); optimizer.step()
            total+=float(loss.detach())*len(pos);count+=len(pos)
        losses.append(total/count)
    z=model().detach().cpu().numpy(); embeddings.append(z)
    print('PyG semilla',seed,'pérdidas',np.round(losses,5).tolist(),'exactitud test',round(score(z),4))

own,loss,pairs=sgns(adj,p=.5,q=2.,seed=0,dim=16,epochs=1,num_walks=1,length=6)
print('NumPy: pares',pairs,'pérdida época',round(loss[0],5),'exactitud test',round(score(own),4))
X=embeddings[0]-embeddings[0].mean(axis=0);Y=embeddings[1]-embeddings[1].mean(axis=0)
R,_=orthogonal_procrustes(Y,X)
print('desplazamiento relativo crudo/alineado',round(float(np.linalg.norm(Y-X)/np.linalg.norm(X)),5),round(float(np.linalg.norm(Y@R-X)/np.linalg.norm(X)),5))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In an execution on an RTX 3060, the component had 2485 nodes and 5069 edges, with 122 training and 915 test nodes in the restricted masks. After three epochs, PyG accuracies were 0.1541 and 0.1475 for the two seeds; the one-epoch NumPy run obtained 0.1421. Centered relative displacement fell from 1.41118 to 1.36581 after Procrustes. These are short-training results with a large residual difference and no evidence of convergence; they are not a benchmark comparable to published results or proof that rotation explains all variation.

Exercises

Proof
Prove: Derive the PMI of center-context pairs in a stationary walk with uniform window.
0
Connected undirected graph, π_i = d_i/vol(G), distance r uniform from 1 to T.

Step 1 of 2. What is the joint probability of center u and context v?

Numeric
You reach v from t and have three equal-weight candidates: return to t, a common neighbor and one at distance two from t. If p=0.5 and q=2, what is the normalized return probability?
Quiz
You seek servers with similar structural roles in two disconnected networks. Which representation is a more suitable starting point?
Quiz
Two training runs produce different vectors but similar inner products and quality. Which comparison helps interpret them?
Code
Implement alias_setup(weights) and alias_draw(table, rng). weights contains nonnegative values with positive sum. Build a (prob, alias) table in O(n) and draw a category using a uniform column and a coin in O(1).
import numpy as np
def alias_setup(weights):
  pass
def alias_draw(table, rng):
  pass
Shift+Enter to run

Key ideas

Key idea
DeepWalk and node2vec learn tables from walk contexts; the sampling rule defines which relationships are targeted for preservation.

The implicit matrix clarifies the connection to factorization. Structural roles and new nodes require additional decisions that an identity table cannot solve by itself.