在 PyTorch Geometric 中使用 GCNConv 层时,可能会遇到 RuntimeError: index 1 is out of bounds for dimension 0 with size 1 错误。该错误提示 edge_index 张量的索引 1 超出了维度 0 的范围,这表明 edge_index 张量的形状可能不正确。

edge_index 张量用于表示图中的边,其形状应为 [2, num_edges],其中第一行表示边的源节点,第二行表示边的目标节点。如果 edge_index 张量的形状不正确,则可能会导致索引超出范围错误。

为了解决这个问题,可以采取以下步骤:

  1. 检查 edge_index 张量的形状:使用 edge_index.shape 获取 edge_index 张量的形状,并确认其是否为 [2, num_edges]
  2. 重新调整 edge_index 张量的形状:如果 edge_index 张量的形状不正确,可以将其重新调整为 [2, num_edges]。例如,如果 edge_index 张量的形状为 [num_edges, 2],可以使用 edge_index.t() 将其转置为正确的形状。
  3. 确保数据加载和处理过程正确:在创建 edge_index 张量之前,确保数据加载和处理过程正确,确保 edge_index 中的索引值在节点的范围内。

例如,以下是修改后的 MyDataset 类,其中 edge_index 张量的形状已调整为 [2, num_edges]

class MyDataset(torch.utils.data.Dataset):
    def __init__(self, root, transform=None, pre_transform=None):
        # ...
        # 读取边的关系
        self.edges = torch.tensor(self.edges.values, dtype=torch.long).t().contiguous()
        # ...

通过检查和修正 edge_index 张量的形状,可以避免索引超出范围错误,并成功训练图神经网络模型。

解决 PyTorch Geometric 中 GCNConv 层的索引超出范围错误

原文地址: https://www.cveoy.top/t/topic/peUV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录