learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Algorithm Selection

Select an algorithm and generate steps to begin visualization

node2vec and DeepWalk Visualizer

Random walks as sentences, vertices as words

Turns random walks into vectors: vertices that often appear close together in walks get similar vectors. The parameters p and q make the walks stay local or roam outward

Time: O(r · l · n) to walk, plus training
Space: O(n · d)
Use Case: Recommendation, link prediction, node classification, features for machine learning on graphs
Showing the example graph for this algorithm.
Walk bias

p = 1, q = 1. A small q sends the walks away from where they came from, a large q keeps them close.

Algorithm Execution

Select an algorithm and generate steps to begin visualization

About node2vec and DeepWalk (Node Embeddings)

node2vec learns a vector for every vertex so that vertices which play similar parts in the graph get similar vectors. It borrows the idea of word2vec: a word is known by the words around it. DeepWalk (Perozzi, Al-Rfou and Skiena, 2014) first turned random walks into sentences and vertices into words, and node2vec (Grover and Leskovec, 2016) made the walks tunable. Two parameters bias each step by where the walk just came from: the return parameter p controls stepping back, the in-out parameter q controls moving away. A small q makes the walks roam outward like a depth-first search and the vectors capture communities, a large q keeps them near their start like a breadth-first search and the vectors capture local roles. With p = q = 1 node2vec is DeepWalk.

How it works

From every vertex the visualizer starts several short walks. At each step the next vertex is drawn with a weight that depends on its distance to the previous vertex: 1/p to go back, 1 to stay next to it and 1/q to move farther, and the badges show the resulting chances. It then counts, over all walks, how often two vertices appear within a small window of each other, corrects the counts for how common each vertex is with pointwise mutual information, and factorizes the matrix into short vectors, which is what skip-gram training computes implicitly, as Levy and Goldberg showed. On the example, two rings of six joined by two edges, 120 walks of 8 vertices give vectors of 4 numbers. The vertices most similar to A are F, E and B, all in its own ring, though no step looked for communities.

Applications

Node embeddings turn a graph into features that any machine learning model can use. Recommender systems embed users and items from interaction graphs and suggest the nearest items, link prediction scores a missing edge by the similarity of its two ends, and node classification feeds the vectors to a simple classifier to label proteins, accounts or papers. Fraud teams embed transaction graphs to find accounts that behave alike, and knowledge graph and biology pipelines use them to suggest new links between drugs, genes and diseases. Neo4j Graph Data Science, PyTorch Geometric and many other libraries ship node2vec. Graph neural networks have since taken over many of these tasks, but random walk embeddings remain a fast, unsupervised baseline that needs no vertex features.

Pseudocode

Biased walks, co-occurrence counts, then a factorization into short vectors.

node2vec(G, p, q, r, l, w, d):
    walks = []
    repeat r times, for each vertex s:
        walk = [s, a random neighbour of s]
        while length(walk) < l:
            t = walk[-2], v = walk[-1]
            weight of each neighbour x of v:
                1/p if x = t, 1 if x is next to t, 1/q otherwise
            append a neighbour drawn with these weights
        add walk to walks
    C(a, b) = times a and b appear within w steps in a walk
    M = positive PMI of C
    return the best rank-d factorization of M   // one d-vector per vertex

The original node2vec trains skip-gram with negative sampling on the walks. Levy and Goldberg showed that this implicitly factorizes a shifted PMI matrix of co-occurrences, so the visualizer factorizes the positive PMI matrix directly. It gives the same kind of vectors without random training.

Worked example, step by step

The twelve-vertex example loaded on this page, with the DeepWalk preset.

Example graph: Two rings of six, A to F and G to L, with chords A–C, B–E, H–K and I–L, joined by B–G and C–L. p = q = 1, 10 walks of 8 vertices from each vertex, window 2.

  1. First walk. From A each neighbour B, C and F has a chance of 33%. The walk picks C, then L, K, L, K, J, I: A C L K L K J I. It crosses to the other ring through C–L.
  2. All walks. 120 walks in all, 10 from each of the 12 vertices.
  3. Counting. Within 2 steps of A, F turns up most often, 52 times. PMI then lowers the weight of vertices that turn up everywhere.
  4. Vectors. Factorizing the positive PMI matrix gives each vertex a vector of 4 numbers. The panel plots the first two.
  5. Similar vertices. Cosine similarity with A: F 0.97, E 0.8 and B 0.69, all in A's ring.

With the outward preset (q = 0.5) the closest vertices stay F, E and B. With the local preset (q = 2) they become F, B and C, the vertices next to A: the walks stay close, so the vectors reflect A's immediate surroundings.

Complexity, and where it comes from

Time: O(r · l · n) to walk, plus O(r · l · n · w · d) for skip-gram training · Space: O(n · d)

With alias tables precomputed for each pair of previous and current vertex, a step costs O(1), so the walks cost O(r · l · n). Skip-gram then visits every position of every walk with the 2w positions in its window and updates d-dimensional vectors, plus a few negative samples. The alias tables of the second-order walk take O(Σ deg(v)²) memory, the bottleneck on graphs with hubs. Factorizing a dense PMI matrix, as on this page, costs O(n³) and only suits small graphs.

When to use node2vec and DeepWalk (Node Embeddings), and when not to

Other ways to turn vertices into vectors.

AlternativePrefer it whenCost
DeepWalkNo tuning is wanted. It is node2vec with p = q = 1, uniform walks.O(r · l · n) plus training
Spectral embeddingThe graph is small and a deterministic embedding is preferred: eigenvectors of the Laplacian, as in spectral partitioning.O(n³) dense, less with sparse solvers
GCN or GraphSAGEVertices have features and new vertices keep arriving. A trained network embeds unseen vertices, node2vec cannot.O(k · E · f) per pass

Common pitfalls

  • Reading q backwards. A large q keeps walks close, like BFS, and gives local, structural vectors. A small q sends them away, like DFS, and gives community vectors. The names return parameter and in-out parameter are easy to swap.
  • Embedding a new vertex. node2vec is transductive: a vertex added later has no vector until the embedding is trained again, and a retrained embedding is rotated, so old and new vectors cannot be compared directly.
  • Comparing raw counts. Hubs co-occur with everyone. Without the PMI correction, or the negative sampling of skip-gram, every vertex looks similar to the busiest one.

Frequently asked questions

What do p and q mean?
After stepping from t to v, a walk returns to t with weight 1/p, moves to a neighbour of t with weight 1 and moves farther from t with weight 1/q. p controls backtracking, q controls whether the walk explores outward or stays near.
How long should the walks be?
The original paper uses 10 walks of length 80 per vertex, a window of 10 and 128 dimensions. Longer walks and windows capture wider context at higher cost. This page keeps everything small so the steps stay readable.
Is node2vec still useful next to graph neural networks?
Yes, as an unsupervised baseline and when vertices have no features. It needs no labels, scales well with parallel walks, and its vectors plug into any classifier or nearest-neighbour index.

Related algorithms: Graph Convolutional Network (Message Passing), Node Similarity (Jaccard), Link Prediction, Personalized PageRank, Louvain Community Detection

Built by Mohammed Islam HadjoudjWork with me

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 12
Edges: 18