python
import torch
import torch.nn as nn
import torch.nn.functional as F
# 論文の Algorithm 1 と式 3 どおりの小さな実装(PyTorch 本体には GraphSAGE の層はない)
# 近傍はサンプリング済みで、ノードごとに S 個ずつ並んだ番号の表 neigh_idx [N, S] で渡す
def sample_neighbors(adj_list, nodes, num_samples):
# 各ノードの隣から num_samples 個を一様に選ぶ(隣が少ないときは重複を許して選ぶ)
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(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 # 各近傍を変換 → 要素ごとの最大値
if self.aggr == "lstm":
perm = torch.randperm(h_neigh.size(1)) # 近傍をランダムに並べ替える
_, (h_last, _) = self.lstm(h_neigh[:, perm])
return h_last[-1]
return h_neigh.mean(dim=1) # 平均
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 正規化
class GraphSAGE(nn.Module):
# K = 2 の場合。x はグラフ全体のノードの特徴 [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) # 教師ありの場合の分類の層
def forward(self, x, batch, adj_list, sizes=(25, 10)):
# 深さ 1(v の近傍)と深さ 2(近傍の近傍)を先にサンプリングしておく(付録 A の Algorithm 2)
n1 = sample_neighbors(adj_list, batch, sizes[0]) # [B, S1]
n2 = sample_neighbors(adj_list, n1.flatten(), sizes[1]) # [B*S1, S2]
# k = 1:v と、その近傍 u それぞれの表現を、1 つ先の近傍から作る
nv2 = sample_neighbors(adj_list, batch, sizes[1]) # v 自身の 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:v の表現を、近傍 u の k = 1 の表現から作る
z = self.layer2(h_v1, h_u1.view(len(batch), sizes[0], -1)) # [B, hidden]
return self.classifier(z)
# 使い方(小さな乱数のグラフの例)
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)] # 各ノードの隣の番号
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,)) # バッチサイズ 512
loss = F.cross_entropy(model(x, batch, adj_list), labels[batch])
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval() # この実装は train / eval で挙動が変わらない(サンプリングは推論でも行う)
with torch.no_grad():
pred = model(x, torch.arange(10), adj_list).argmax(dim=1)