根据报错信息,可以看出是在 GCNConv 的 forward 函数中出现了错误。具体的错误是索引 4 超出了维度 0 的大小 3。

可能的原因是在计算 GCNConv 时,输入的特征 x 的维度与边的索引 edge_index 不匹配。请检查输入数据的维度是否正确,并确保特征和边的索引的维度匹配。

另外,还需要注意的是,GCNConv 的输入特征 x 的维度应该为 [num_nodes, num_node_features],而不是 [num_nodes, num_node_features, width, height],因此在 CNN 模型的 forward 函数中,可以考虑添加一个平均池化层,将特征的维度从 [batch_size, num_node_features, width, height] 转换为 [batch_size, num_node_features]。

以下是修改后的代码示例:

class CNN(torch.nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Conv2d(4, 16, kernel_size=3, stride=2, padding=1)
        self.conv2 = nn.Conv2d(16, 4, kernel_size=3, stride=2, padding=1)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))  # 添加平均池化层

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = self.avgpool(x)  # 添加平均池化层
        return x.squeeze()


class GCN(torch.nn.Module):
    def __init__(self, num_node_features, num_classes):
        super(GCN, self).__init__()
        self.conv1 = GCNConv(num_node_features, 8)
        self.conv2 = GCNConv(8, 16)
        self.conv3 = GCNConv(16, num_classes)
        self.cnn = CNN()

    def forward(self, data):
        x, edge_index = data.x, data.edge_index
        x = self.cnn(x)  # 使用CNN模型提取图像特征
        x = self.conv1(x, 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 和标签 y 的维度是正确的。可以通过打印相关的维度来进行检查。

PyG 数据集加载及 GCN 模型训练报错:索引超出范围解决方法

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

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