使用DGL库得到图数据的一个数据的形状是Data(x=[38, 10], edge_index=[2, 43], edge_attr=[43], y=0, mol_attr=[1400]),其中x, edge_index输入到卷积层,想让mol_attr和卷积完成后的特征共同输入到全连接层,该怎么做,在共同输入到全连接层的时候,两个特征因为维度问题总是出错,该怎么办?
#模型代码:
class GCN(torch.nn.Module):
def __init__(self, hidden_channels):
super(GCN, self).__init__()
torch.manual_seed(12345)
self.conv1 = GCNConv(dataset.num_node_features, hidden_channels)
self.conv2 = GCNConv(hidden_channels, hidden_channels)
self.conv3 = GCNConv(hidden_channels, hidden_channels)
self.lin = Linear(hidden_channels, dataset.num_classes)
def forward(self, x, edge_index, batch):
# 1. Obtain node embeddings
x = self.conv1(x, edge_index)
x = x.relu()
x = self.conv2(x, edge_index)
x = x.relu()
x = self.conv3(x, edge_index)
# 2. Readout layer
x = global_mean_pool(x, batch) # [batch_size, hidden_channels]
# 3. Apply a final classifier
x = F.dropout(x, p=0.5, training=self.training)
x = self.lin(x)
return x
不知道你这个问题是否已经解决, 如果还没有解决的话:解决方案:
在这里,我们可以使用torch的torch.cat
函数将mol_attr
与卷积完成后的特征x
连接起来,并将其作为输入传递给全连接层。
以下是修改后的前向传播函数:
def forward(self, x, edge_index, batch, mol_attr):
# 1. 获取节点嵌入
x = self.conv1(x, edge_index)
x = x.relu()
x = self.conv2(x, edge_index)
x = x.relu()
x = self.conv3(x, edge_index)
# 2. 连接mol_attr特征
x = global_mean_pool(x, batch) # [batch_size, hidden_channels]
x = torch.cat([x, mol_attr], dim=1) # 将mol_attr与x连接在一起
# 3. 应用最后的分类器
x = F.dropout(x, p=0.5, training=self.training)
x = self.lin(x)
return x
这样,mol_attr
和卷积完成后的特征x
会一起输入到全连接层中。
请注意,为了使mol_attr
的维度和x
的维度一致,您可能需要进行相应的维度调整和预处理。具体的处理方式取决于mol_attr
的具体形状和维度。