Node2Vec turns nodes in a graph into numerical vectors that reflect their network context. Use the vectors to visualize groups, cluster similar nodes, or supply features to a machine learning model. It is especially useful when the graph is known up front and its connections carry meaningful information. section 2.1 section 2.1.4
The workflow has three parts:
- Walk through the graph from each node. Walk length sets how far a walk goes; the number of walks sets how often each node is sampled. section 2.1.1
- Bias the walks with p, which controls returning to the previous node, and q, which steers exploration toward nearby or farther-away nodes. Unlike DeepWalk’s unbiased walks, this lets Node2Vec vary the network context it samples. section 2.4.3
- Train on the resulting node sequences to predict neighboring nodes. The learned representation becomes each node’s embedding; its dimension controls the vector size. section 2.4.3 section 2.1.1
Political books and co-purchases
Represent books as nodes and frequent Amazon co-purchases as edges. Load the GML graph with NetworkX, generate embeddings with the Node2Vec Python library, then project them into two dimensions with UMAP. The projection helps inspect whether books with related co-purchase patterns form groups; the full embeddings can instead become features for classification, recommendation, or clustering. section 2.1 section 2.1.1 section 2.1.4
Listing 2.1 Generating N2V embeddings
import NetworkX as nx
from Node2Vec import Node2Vec
books_graph = nx.read_gml('PATH_TO_GML_FILE') #1
node2vec = Node2Vec(books_graph, dimensions=64,
walk_length=30, num_walks=200, workers=4) #2
model = node2vec.fit(window=10, min_count=1,\
batch_words=4) #3
embeddings = {str(node): model.wv[str(node)]\
for node in gml_graph.nodes()} #4
The listing shows the practical sequence: read a graph, set embedding and walk parameters, fit the model, and retrieve a vector for each node. Keep the graph variable name consistent when adapting it. section 2.1.1
Node2Vec is transductive: its embeddings belong to the graph used for training, so new nodes or graphs require the method to be reapplied. That makes it a better fit for stable graphs than for frequently changing ones. Graph neural networks offer an alternative when embeddings must adapt to unseen nodes or incorporate node features. section 2.1.4 section 2.2.2


