PyG GCN 模型中 RuntimeError: index out of bounds 错误的解决方法
这个错误是由于在 GCN 模型的 forward 函数中,调用了 GCNConv 的 forward 函数时,传入的 'edge_index' 超出了范围。具体来说,'edge_index' 中的索引值超过了节点特征 'x' 的大小。
解决这个问题的方法是检查数据集中的节点特征 'x' 的大小是否与 'edge_index' 的索引值匹配。在这里,特征 'x' 的大小应该是 [batch_size, num_node_features, width, height],而 'edge_index' 的索引值应该小于等于 'num_node_features'。
你可以在 GCN 模型的 forward 函数中添加以下代码来检查这个问题:
def forward(self, data):
x, edge_index = data.x, data.edge_index
assert edge_index.max() < x.size(0), 'Edge index exceeds node feature size'
# 执行卷积神经网络前向传播
features = self.cnn(x) # 提取节点特征
features = features.view(features.size(0), -1) # 调整特征维度
# 替换 PyG 数据集的节点特征 x
data.x = features
x = self.conv1(features, edge_index)
x = F.relu(x)
x = self.conv2(x, edge_index)
x = F.relu(x)
x = F.dropout(x, training=self.training)
x = self.conv3(x, edge_index)
return x
添加了这个断言后,如果有节点特征的索引超过了 'edge_index' 的大小,就会抛出一个错误,从而帮助你找到问题所在。
另外,还需要确保数据集中的节点特征 'x' 的大小与你在 GCN 模型中定义的 'num_node_features' 相匹配。
原文地址: https://www.cveoy.top/t/topic/peqs 著作权归作者所有。请勿转载和采集!