GraphSAGE (SAmple and aggreGatE) is a model that builds node embeddings by repeatedly sampling a fixed number of neighbors for each node, aggregating their features, concatenating the result with the node's own features, and passing it through a fully connected layer. It was proposed in 2017 by Hamilton, Ying, and Leskovec.
Most earlier node embedding methods, such as DeepWalk, learned a dedicated vector for each individual node. With this approach, when new nodes are added after training, they have no vectors, so training has to be redone. This is inconvenient for graphs that gain nodes every day, such as new posts on a social network or newly listed products.
GraphSAGE learns not a vector per node but a function that builds embeddings from neighbor features. Because it is a function, it can produce embeddings for nodes not seen during training, as long as their neighbor features are available. This kind of use is called inductive, in contrast to transductive, which predicts only within the graph used for training.
As an analogy, learning a vector per node is like "memorizing a class roster," while GraphSAGE learns "a way to infer what a person is like from their friends." Once you know the method, you can apply it to people you are meeting for the first time.
GraphSAGE can also be seen as an extension of GCN that works on new nodes. By letting the neighbor aggregation be chosen from mean, LSTM, or pooling, and by keeping the cost of each mini-batch constant through neighbor sampling, it made graphs with hundreds of thousands of nodes tractable.
Theory: sampling and aggregation
GraphSAGE starts from the features xv of node v and gathers information from neighbors at each depth k=1,…,K (Algorithm 1 of the paper).
Initialization: set hv0=xv.
Sample neighbors: from the nodes adjacent to v, choose a fixed number Sk uniformly at random and call them N(v). A separate draw is made at each depth k.
Aggregate neighbors: combine the previous-depth representations of the chosen neighbors with an aggregator function.
Concatenate with itself and transform: concatenate (CONCAT) the node's own previous representation with the aggregated vector, and pass it through a fully connected layer with weights Wk and an activation function σ (ReLU in the paper).
Normalize the length: divide the result by its L2 norm so that its length is 1.
Repeat steps 2 to 5 K times and use the final hvK as the embedding zv.
Written as equations, steps 3 to 5 are as follows.
The number of neighbors varies greatly from node to node, from a few to several thousand. Using all neighbors makes the computation and memory of a mini-batch unpredictable, and in the worst case it covers the whole graph (O(∣V∣)). Choosing a fixed number fixes the cost per node at O(∏k=1KSk). The experiments in the paper used K=2, S1=25, and S2=10.
Three aggregator functions (Section 3.3 of the paper)
Because neighbors have no natural order, the paper states that the aggregator should ideally be independent of input order (giving the same result when the order is shuffled).
Mean: take the element-wise mean of the neighbor vectors.
LSTM: feed the neighbor vectors into an LSTM one after another. Since an LSTM's output depends on order, the neighbors are randomly permuted before being fed in. It is more expressive but lacks order independence.
Pooling: pass each neighbor through the same fully connected layer and activation function, then take the element-wise maximum (max pooling) (Equation 3 of the paper).
This borrows the idea of PointNet, which handles sets of points: the fully connected layer extracts various properties from the neighbor features, and the maximum picks out the most prominent ones.
As a baseline, the paper also tests a "GCN-style" variant (GraphSAGE-GCN) that replaces steps 3 and 4 with the following equation. The node itself is averaged together with its neighbors, and no concatenation is done. It is a GCN layer recast so that it also works on new nodes.
hvk=σ(W⋅MEAN({hvk−1}∪{huk−1:u∈N(v)}))
Training
GraphSAGE can be trained either unsupervised, without labels, or supervised, with labels.
Unsupervised training (Equation 1 of the paper)
It uses a loss that "makes nodes close on the graph have similar embeddings and distant nodes have different ones."
Here v is a node that appears nearby on a fixed-length random walk starting from u, vn is a negative sample drawn from the distribution Pn, Q is the number of negative samples, and σ is the sigmoid function. The first term increases the inner product with nearby nodes, and the second term decreases the inner product with negative samples.
The loss has the same form as DeepWalk's, but differs in that zu is not a dedicated per-node vector but is computed from neighbor features. This is why embeddings can also be produced for new nodes after training.
Supervised training
When the task is fixed, such as classification, the model is trained with a task loss such as cross-entropy instead of (or in addition to) the loss above.
Mini-batch computation (Appendix A of the paper)
In a mini-batch, starting from the nodes whose embeddings are needed, the neighbors up to depth K are sampled first, and only the representations of the required nodes are computed. Because the whole graph is never computed at once, even large graphs fit in GPU memory.
50 random walks of length 5 from each node, 20 negative samples
How it works and why it is effective
GraphSAGE works on new nodes and is also accurate mainly for the following three reasons.
It looks at "features and surroundings," not a node's "identity": embeddings are computed only from the features of the node and its neighbors. Because the same weights are shared across all nodes, the same computation can be done for nodes absent during training, as long as they have features and neighbors. In the PPI experiment in the paper, the model was applied directly to graphs from other tissues that were not used for training.
It keeps the node's own features without mixing them into its neighbors': averaging a node together with its neighbors, as in the GCN-style variant, dilutes its own features. GraphSAGE concatenates its own representation with the neighbor aggregate before transforming, so "what the node itself is like" and "what its surroundings are like" are handled by separate weights. The paper notes that this can be seen as a simple skip connection between depths and identifies it as a key factor in the large performance gain.
The aggregation itself can be learned: the mean is a fixed computation, but pooling and LSTM have trainable weights in the aggregation itself. In the experiments, pooling and LSTM were also significantly better than the GCN-style variant.
Relation to the Weisfeiler-Lehman procedure
The paper describes GraphSAGE as a continuous version of "the Weisfeiler-Lehman (WL) procedure used for graph isomorphism testing." Setting K=∣V∣, making the weights identity matrices, and using a hash function as the aggregator turns Algorithm 1 into exactly the WL procedure. GraphSAGE replaces this hash function with a trainable neural network.
Section 5 of the paper shows theoretically that GraphSAGE, even though it computes only from node features, can learn graph structure. Specifically, it proves that with the pooling aggregator, the fraction of a node's neighbor pairs that form triangles (the clustering coefficient) can be approximated to arbitrary precision.
Experimental results
Classification on new nodes and new graphs (Table 1 of the paper, micro-F1)
Three datasets were used. In all of them, the evaluated nodes were not seen during training.
Citation: 302,424 papers in 6 fields of biology. The model is trained on papers from 2000 to 2004 and predicts the field of papers from 2005.
Reddit: 232,965 posts from September 2014 (posts commented on by the same user are connected by an edge). The model is trained on the first 20 days and predicts the community of posts from the remaining days.
PPI: protein-protein interaction graphs from various human tissues. The model is trained on 20 graphs and predicts protein functions (121 types) on 2 other graphs.
Method
Citation (unsupervised)
Citation (supervised)
Reddit (unsupervised)
Reddit (supervised)
PPI (unsupervised)
PPI (supervised)
Features only
0.575
0.575
0.585
0.585
0.422
0.422
DeepWalk
0.565
0.565
0.324
0.324
—
—
DeepWalk + features
0.701
0.701
0.691
0.691
—
—
GraphSAGE-GCN
0.742
0.772
0.908
0.930
0.465
0.500
GraphSAGE-mean
0.778
0.820
0.897
0.950
0.486
0.598
GraphSAGE-LSTM
0.788
0.832
0.907
0.954
0.482
0.612
GraphSAGE-pooling
0.798
0.839
0.892
0.948
0.502
0.600
GraphSAGE greatly outperformed features-only and DeepWalk in every setting. Supervised GraphSAGE raised F1 by 51% on average compared with classification using features only. DeepWalk cannot be used on PPI because its embedding spaces are not aligned across different graphs.
Comparison of aggregators (Section 4.4 of the paper)
Across the 6 settings (3 datasets × unsupervised and supervised), LSTM, pooling, and mean were all statistically significantly better than the GCN-style variant. There was no significant difference between LSTM and pooling, but since LSTM is about 2 times slower than pooling, the paper considers pooling to have a slight advantage.
Speed and depth (Section 4.3 of the paper)
Training time was about the same as DeepWalk. When producing embeddings for new nodes, however, DeepWalk had to sample new random walks and retrain, making it 100 to 500 times slower than GraphSAGE.
Setting K=2 improved accuracy by about 10 to 15% on average over K=1. Going beyond K=2 gave only 0 to 5% more, while runtime grew by 10 to 100 times.
Sampling more neighbors improved accuracy, but with diminishing returns.
Caveats in practice
When using GraphSAGE, keep the following points in mind.
Start with depth K=2: in the paper, increasing K beyond 2 barely improved accuracy while greatly increasing computation time. The paper reports that sample sizes of around S1⋅S2≤500 gave sufficient accuracy.
Sampling makes results vary: because neighbors are chosen at random, the embedding of the same node changes slightly each time it is computed. To stabilize predictions, you can sample more neighbors at inference time or use all neighbors.
Node features are required: GraphSAGE builds embeddings from features, so for graphs without features, supply features derived from structure, such as node degree.
The LSTM aggregator is not order-independent: because neighbors are randomly permuted before being fed in, the same neighbors can give different results depending on their order. If you need an order-independent aggregator, use mean or pooling.
Where to get it in PyTorch: it is not in PyTorch itself. Besides writing it as in the code example below, you can use SAGEConv (choose the aggregator with the aggr argument) and NeighborLoader (neighbor sampling) in PyTorch Geometric, or SAGEConv in DGL. Library layers are sometimes written as the sum "transform of self + transform of neighbors" instead of a concatenation, which is the same computation as a concatenation with the weights split in two.
The unsupervised loss (Equation 1) trains nodes that are close on the graph to have similar embeddings. In graphs where connected nodes are not similar (for example, graphs connecting different kinds of nodes, such as sellers and buyers), this assumption does not hold, and unsupervised embeddings may not help the task. If task labels are available, train with a supervised loss instead or in addition.
Comparison with other methods
Comparing four representative graph neural network methods from the same angles gives the following.
Hundreds of thousands of nodes or more, or nodes added every day: GraphSAGE suits this, since neighbor sampling and mini-batches keep computation in check.
A small graph whose nodes do not grow: GCN is simpler and can be trained on the whole graph at once.
Neighbors likely differ in importance and you want to see all of them: try GAT. In the GAT paper, it outperformed GraphSAGE on PPI.
You want to distinguish the shapes of entire graphs: GIN is suitable. The GIN paper shows that some graphs cannot be distinguished with pooling (max) or mean aggregation.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
# A small implementation following Algorithm 1 and Equation 3 of the paper (PyTorch itself has no GraphSAGE layer)
# Neighbors are pre-sampled and passed as an index table neigh_idx [N, S] with S entries per node
def sample_neighbors(adj_list, nodes, num_samples):
# Uniformly choose num_samples neighbors of each node (with replacement when there are few neighbors)
out = []
for v in nodes.tolist():
nbrs = torch.tensor(adj_list[v])
pick = torch.randint(len(nbrs), (num_samples,))
out.append(nbrs[pick])
return torch.stack(out) # [len(nodes), num_samples]
class SAGELayer(nn.Module):
def __init__(self, in_dim, out_dim, aggr="mean", pool_dim=512):
super().__init__()
self.aggr = aggr
if aggr == "pool":
self.pool = nn.Linear(in_dim, pool_dim) # W_pool, b
agg_dim = pool_dim
elif aggr == "lstm":
self.lstm = nn.LSTM(in_dim, in_dim, batch_first=True)
agg_dim = in_dim
else:
agg_dim = in_dim
self.linear = nn.Linear(in_dim + agg_dim, out_dim) # W^k (applied after CONCAT)
def aggregate(self, h_neigh): # h_neigh: [B, S, in_dim]
if self.aggr == "pool":
return F.relu(self.pool(h_neigh)).max(dim=1).values # transform each neighbor -> element-wise max
if self.aggr == "lstm":
perm = torch.randperm(h_neigh.size(1)) # randomly permute the neighbors
_, (h_last, _) = self.lstm(h_neigh[:, perm])
return h_last[-1]
return h_neigh.mean(dim=1) # mean
def forward(self, h_self, h_neigh):
h = torch.cat([h_self, self.aggregate(h_neigh)], dim=-1) # CONCAT(h_v^{k-1}, h_N(v)^k)
h = F.relu(self.linear(h))
return F.normalize(h, p=2, dim=-1) # L2 normalization
class GraphSAGE(nn.Module):
# The case K = 2. x is the node features of the whole graph [N, in_dim]
def __init__(self, in_dim, hidden_dim=256, num_classes=50, aggr="pool"):
super().__init__()
self.layer1 = SAGELayer(in_dim, hidden_dim, aggr)
self.layer2 = SAGELayer(hidden_dim, hidden_dim, aggr)
self.classifier = nn.Linear(hidden_dim, num_classes) # classification layer for the supervised case
def forward(self, x, batch, adj_list, sizes=(25, 10)):
# Sample depth 1 (neighbors of v) and depth 2 (neighbors of neighbors) in advance (Algorithm 2 in Appendix A)
n1 = sample_neighbors(adj_list, batch, sizes[0]) # [B, S1]
n2 = sample_neighbors(adj_list, n1.flatten(), sizes[1]) # [B*S1, S2]
# k = 1: build representations of v and of each neighbor u from the next hop of neighbors
nv2 = sample_neighbors(adj_list, batch, sizes[1]) # neighbors of v itself for k = 1
h_v1 = self.layer1(x[batch], x[nv2]) # [B, hidden]
h_u1 = self.layer1(x[n1.flatten()], x[n2]) # [B*S1, hidden]
# k = 2: build the representation of v from the k = 1 representations of its neighbors u
z = self.layer2(h_v1, h_u1.view(len(batch), sizes[0], -1)) # [B, hidden]
return self.classifier(z)
# Usage (example on a small random graph)
num_nodes, in_dim = 1000, 300
x = torch.rand(num_nodes, in_dim)
adj_list = [torch.randint(num_nodes, (8,)).tolist() for _ in range(num_nodes)] # neighbor indices of each node
labels = torch.randint(0, 50, (num_nodes,))
model = GraphSAGE(in_dim)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
for step in range(100):
model.train()
batch = torch.randint(num_nodes, (512,)) # batch size 512
loss = F.cross_entropy(model(x, batch, adj_list), labels[batch])
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval() # this implementation behaves the same in train / eval (sampling is also done at inference)
with torch.no_grad():
pred = model(x, torch.arange(10), adj_list).argmax(dim=1)
FAQ
Q. What is the biggest difference between GraphSAGE and GCN?
A.
GCN computes all nodes at once using the normalized adjacency matrix of the whole graph, and the original paper evaluates it in a setting that classifies nodes within the training graph. GraphSAGE learns a function that samples a fixed number of neighbors and concatenates the node's own features with the neighbor aggregate. As a result, it can be trained on large graphs with mini-batches and applied directly to nodes unseen during training and to other graphs.
Q. Which aggregator should I choose: mean, LSTM, or pooling?
A.
In the paper's experiments, LSTM and pooling performed best, with no significant difference between them. LSTM is about 2 times slower than pooling and its result depends on neighbor order, so it is best to start with pooling or the simpler mean. All of them outperformed the GCN-style aggregation.
Q. How should I decide the number of neighbors to sample?
A.
The paper used S1=25 and S2=10 at depth K=2, and reports that around S1⋅S2≤500 gave sufficient accuracy. Sampling more improves accuracy, but the gains shrink gradually, and the cost grows in proportion to S1⋅S2.