1


图神经网络入门示例:使用PyTorch Geometric 进行节点分类

基于图的神经网络是强大的模型,可以学习网络中的复杂模式。在本文中,我们将介绍如何为同构图数据构造PyTorch Data对象,然后训练不同类型的神经网络来预测节点所属的类。这种类型的预测问题通常被称为节点分类。

我们将使用来自Benedek Rozemberczki, Carl Allen和Rik Sarkar于2019年发布的“Multi-scale Attributed Node Embedding”论文中的Facebook Large Page-Page Network¹数据集。

该数据集包含22,470个Facebook页面,按主题分为四类。由不同大小的特征向量表示。数据集还包含Facebook pages 上跟随其他page的信息。网络中有171,992个链接或边。

数据集

第一步是从URL下载数据集。如果手动下载也是可以的,我们这里是为了方便演示

  1. wget https://snap.stanford.edu/data/facebook_large.zip

解压后的数据集包含三个独立的文件:

musae_facebook_edges.csv:该文件包含具有两列的Facebook页面之间的连接图,表示id_1和id_2列是相互连接的,最直接的说法就是图的边。

musae_facebook_target.csv:该文件包含数据集中22,470个Facebook Page的描述和类型。我们试图预测的标签是page_type列,这是一个多类标签,它将每个Facebook页面分为四个类之一,这就是我们图数据的节点。

musae_facebook_features.json:这个文件包含每个Facebook Page的特征向量。键是上面文件的节点id,值是特征向量。

创建PyTorch同构数据对象

为了在PyTorch中训练神经网络,我们必须创建一个数据对象。由于我们的数据集包含相同类型的所有节点,我们将创建一个描述同构图的数据对象。

说明:如果数据集包含多种类型的节点或边,则需要创建一个描述异构图的HeteroData数据对象。

第一步是使用pandas读取CSV文件中的节点数据作然后从json文件中提取特征

但是我们导入JSON文件后发现特征向量大小不一致,嵌入的大小从3到31个不等。

一半情况下模型都期望节点属性或特征具有一致的大小,因此我们需要一些特征转操作。我们将从节点特征中创建张量。由于嵌入的最大大小是31,所以以最大值为例

如果一个节点的特征小于31,将用值0填充剩余的元素。然后,对每个节点的特征进行归一化。下面是所有的代码:

  1. from torch.nn.utils.rnn import pad_sequence
  2. def load_node_csv(path, index_col, **kwargs):
  3. df = pd.read_csv(path, **kwargs)
  4. mapping = {i: node_id for i, node_id in enumerate(df[index_col].unique())}
  5. # Load node features
  6. with open(os.path.join(data_dir, "musae_facebook_features.json"), "r") as json_file:
  7. features_data = json.load(json_file)
  8. xs = []
  9. for index, node_id in mapping.items():
  10. features = features_data.get(str(index), [])
  11. if features:
  12. # Create tensor from feature vector
  13. features_tensor = torch.tensor(features, dtype=torch.float)
  14. xs.append(features_tensor)
  15. else:
  16. xs.append(torch.zeros(1, dtype=torch.float))
  17. # Pad features to have vectors of the same size
  18. padded_features = pad_sequence([torch.tensor(seq) for seq in xs], batch_first=True, padding_value=0)
  19. mask = padded_features != 0 # mask to indicate which features were padded
  20. # Create tensor of normaized features for nodes
  21. mean = torch.mean(padded_features[mask].float())
  22. std = torch.std(padded_features[mask].float())
  23. x = (padded_features - mean) / (std + 1e-8) # final x tensor with normalized features
  24. return x
  25. x = load_node_csv(path=os.path.join(data_dir, "musae_facebook_target.csv"), index_col="facebook_id")

上面创建了包含22,470个Facebook Page的特征向量的张量x。

下面就是加载边的数据,也就是建立节点直接的连接

  1. def load_edge_csv(path, src_index_col, dst_index_col, **kwargs):
  2. df = pd.read_csv(path, **kwargs)
  3. src = df[src_index_col].values
  4. dst = df[dst_index_col].values
  5. edge_index = torch.tensor([src, dst])
  6. return edge_index
  7. edge_index = load_edge_csv(path=os.path.join(data_dir, "musae_facebook_edges.csv"), src_index_col="id_1", dst_index_col="id_2")

得到了一个长度为2的PyTorch张量,一个用于源节点,另一个用于目标节点,总计171,002条边。

清理完数据并将其转换为正确的类型后,我们现在可以为同构图创建PyTorch data对象了:

  1. # Create homogeneous graph using PyTorch's Data object
  2. data = Data(x=x, edge_index=edge_index, y=y)

结果数据对象包含22,470个节点,每个节点由大小为31的特征向量表示,在删除重复项和自循环后,节点之间有171,002条边:

  1. >>> Data(x=[22470, 31], edge_index=[2, 171002], y=[22470])

分割数据

为了训练和验证,数据集被分成70%用于训练和30%用于测试,前15,728个节点用于训练,最后6,742个节点用于测试集。

  1. # Calculate no. of train nodes
  2. num_nodes = data.num_nodes
  3. train_percentage = 0.7
  4. num_train_nodes = int(train_percentage * num_nodes)
  5. # Create a boolean mask for train mask
  6. train_mask = torch.zeros(num_nodes, dtype=torch.bool)
  7. train_mask[: num_train_nodes] = True
  8. # Add train mask to data object
  9. data.train_mask = train_mask
  10. # Create a boolean mask for test mask
  11. test_mask = ~data.train_mask
  12. data.test_mask = test_mask

我们使用mask来标识训练和验证集

  1. >>> Data(
  2. x=[22470, 31],
  3. edge_index=[2, 171002],
  4. y=[22470],
  5. num_classes=4,
  6. train_mask=[22470],
  7. test_mask=[22470]
  8. )

训练神经网络

我们现在已经可以训练模型了。下面将训练两种不同类型的神经网络,并对它们进行比较。

在训练模型之前我们可以先可视化节点是什么样的

在上面的图表中,似乎有两个大团,但类别区分并不明显。

1、多层感知网络(MLP)

作为对比,我们先训练一个最基础的mlp看看表现

  1. from torch.nn import Linear
  2. import torch.nn.functional as F
  3. class MLP(torch.nn.Module):
  4. def __init__(self):
  5. super().__init__()
  6. torch.manual_seed(123)
  7. self.lin1 = Linear(data.num_features, 32)
  8. self.lin2 = Linear(32, 32)
  9. self.lin3 = Linear(32, 16)
  10. self.lin4 = Linear(16, 8)
  11. self.lin5 = Linear(8, data.num_classes)
  12. def forward(self, x):
  13. x = self.lin1(x)
  14. x = F.relu(x)
  15. x = self.lin2(x)
  16. x = F.relu(x)
  17. x = self.lin3(x)
  18. x = F.relu(x)
  19. x = self.lin4(x)
  20. x = F.relu(x)
  21. x = self.lin5(x)
  22. x = torch.softmax(x, dim=1)
  23. return x

创建对象

  1. class_weights = torch.tensor([1 / i for i in df_agg_classes["proportion"].values], dtype=torch.float)
  2. model = MLP()
  3. criterion = torch.nn.CrossEntropyLoss(weight=class_weights)
  4. optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

最终的结构如下:

  1. >>> MLP(
  2. (lin1): Linear(in_features=31, out_features=32, bias=True)
  3. (lin2): Linear(in_features=32, out_features=32, bias=True)
  4. (lin3): Linear(in_features=32, out_features=16, bias=True)
  5. (lin4): Linear(in_features=16, out_features=8, bias=True)
  6. (lin5): Linear(in_features=8, out_features=4, bias=True)
  7. )

训练循环:

  1. def train():
  2. model.train()
  3. optimizer.zero_grad() # Clear gradients
  4. out = model(data.x) # Perform a single forward pass
  5. loss = criterion(out[data.train_mask], data.y[data.train_mask]) # Compute loss from training data
  6. loss.backward() # Derive gradients
  7. optimizer.step() # Update parameters
  8. return loss

我们训练1000个epoch

  1. for epoch in range(1, 1001):
  2. loss = train()
  3. print(f"Epoch: {epoch:03d}, loss: {loss:.4f}")

然后是验证代码:

  1. def test():
  2. model.eval()
  3. out = model(data.x)
  4. pred = out.argmax(dim=1) # Select class with the highest probability
  5. test_correct = pred[data.test_mask] == data.y[data.test_mask] # Compare to ground truth labels
  6. test_acc = int(test_correct.sum()) / int(data.test_mask.sum()) # Calculate fraction of correct predictions
  7. return test_acc

在测试集上,MLP模型的准确率得分为0.4562,因此该模型能够正确分类46%的节点。

我们可以通过使用TSNE将预测转换为二维并绘制出来,从而将其可视化:

  1. def visualize(h, color):
  2. z = TSNE(n_components=2).fit_transform(h.detach().cpu().numpy())
  3. plt.figure(figsize=(10, 10))
  4. plt.xticks([]) # create an empty x axis
  5. plt.yticks([]) # create an empty y axis
  6. plt.scatter(z[:, 0], z[:, 1], s=70, c=color, cmap="Set2")

可以看到用MLP模型预测的类别之间没有明显的分离。这里的MLP模型是基于特征向量进行训练的,并且不包含节点之间链接的任何信息。

2、图卷积网络(GCN)

让我们看看如果我们保持大多数参数相同,训练一个图卷积网络(GCN)模型。

  1. from torch_geometric.nn import GCNConv
  2. class GCN(torch.nn.Module):
  3. def __init__(self):
  4. super().__init__()
  5. torch.manual_seed(123)
  6. self.conv1 = GCNConv(data.num_features, 32)
  7. self.conv2 = GCNConv(32, 32)
  8. self.conv3 = GCNConv(32, 16)
  9. self.conv4 = GCNConv(16, 8)
  10. self.conv5 = GCNConv(8, data.num_classes)
  11. def forward(self, x, edge_index):
  12. x = self.conv1(x, edge_index)
  13. x = F.relu(x)
  14. x = self.conv2(x, edge_index)
  15. x = F.relu(x)
  16. x = self.conv3(x, edge_index)
  17. x = F.relu(x)
  18. x = self.conv4(x, edge_index)
  19. x = F.relu(x)
  20. x = self.conv5(x, edge_index)
  21. x = F.log_softmax(x, dim=1)
  22. return x

剩下的代码基本类似

  1. model = GCN()
  2. criterion = torch.nn.CrossEntropyLoss(weight=class_weights)
  3. optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
  4. def train():
  5. model.train()
  6. optimizer.zero_grad() # Clear gradients
  7. out = model(data.x, data.edge_index) # Perform a single forward pass
  8. loss = criterion(out[data.train_mask], data.y[data.train_mask]) # Compute losses from training data
  9. loss.backward() # Derive gradients
  10. optimizer.step() # Update parameters
  11. return loss
  12. for epoch in range(1, 1001):
  13. loss = train()
  14. print(f"Epoch: {epoch:03d}, Loss: {loss:.4f}")

模型验证

  1. def test():
  2. model.eval()
  3. out = model(data.x, data.edge_index) # Pass in features and edges
  4. pred = out.argmax(dim=1) # Get predicted class
  5. test_correct = pred[data.test_mask] == data.y[data.test_mask] # Count correct predictions
  6. test_acc = int(test_correct.sum()) / int(data.test_mask.sum()) # Get proportion of correct predictions
  7. return test_acc

GCN模型能对测试集中80%的节点进行正确分类!让我们把它画出来:

可以看到显示了很好的颜色/类别分离,特别是在图表的中心到右边。这表明带有特征和边缘数据的GCN模型能够较好地对节点进行分类。

总结

在本文中,我们将一个CSV文件转换为数据对象,然后使用PyTorch为节点分类任务构建基于图的神经网络。并且训练了两种不同类型的神经网络——多层感知器(MLP)和图卷积网络(GCN)。结果表明,GCN模型在该数据集上的表现明显优于MLP模型。

本文介绍的主要流程是我们训练图神经网络的基本流程,尤其是前期的数据处理和加载,通过扩展本文的基本流程可以应对几乎所有图神经网络问题。

作者:Claudia Ng

“图神经网络入门示例:使用PyTorch Geometric 进行节点分类”的评论: