WeightAndSum

class dgl.nn.pytorch.glob.WeightAndSum(in_feats)[源码]

基类: Module

计算原子的重要性权重并执行加权求和。

参数:

in_feats (int) – 输入原子特征大小

示例

以下示例使用 PyTorch 后端。

>>> import dgl
>>> import torch as th
>>> from dgl.nn import WeightAndSum
>>>
>>> g1 = dgl.rand_graph(3, 4)  # g1 is a random graph with 3 nodes and 4 edges
>>> g1_node_feats = th.rand(3, 5)  # feature size is 5
>>> g1_node_feats
tensor([[0.8948, 0.0699, 0.9137, 0.7567, 0.3637],
        [0.8137, 0.8938, 0.8377, 0.4249, 0.6118],
        [0.5197, 0.9030, 0.6825, 0.5725, 0.4755]])
>>>
>>> g2 = dgl.rand_graph(4, 6)  # g2 is a random graph with 4 nodes and 6 edges
>>> g2_node_feats = th.rand(4, 5)  # feature size is 5
>>> g2_node_feats
tensor([[0.2053, 0.2426, 0.4111, 0.9028, 0.5658],
        [0.5278, 0.6365, 0.9990, 0.2351, 0.8945],
        [0.3134, 0.0580, 0.4349, 0.7949, 0.3891],
        [0.0142, 0.2709, 0.3330, 0.8521, 0.6925]])
>>>
>>> weight_and_sum = WeightAndSum(5)  # create a weight and sum layer(in_feats=16)

案例 1:输入单个图

>>> weight_and_sum(g1, g1_node_feats)
tensor([[1.2194, 0.9490, 1.3235, 0.9609, 0.7710]],
       grad_fn=<SegmentReduceBackward>)

案例 2:输入一批图

构建一批 DGL 图,并将所有图的节点特征连接成一个张量。

>>> batch_g = dgl.batch([g1, g2])
>>> batch_f = th.cat([g1_node_feats, g2_node_feats])
>>>
>>> weight_and_sum(batch_g, batch_f)
tensor([[1.2194, 0.9490, 1.3235, 0.9609, 0.7710],
        [0.5322, 0.5840, 1.0729, 1.3665, 1.2360]],
       grad_fn=<SegmentReduceBackward>)

注意事项

WeightAndSum 模块常用于分子性质预测网络中,请参见 dgl-lifesci 中的 GCN 预测器,以了解如何使用 WeightAndSum 层获取图的读出输出。

forward(g, feats)[源码]

从原子表示中计算分子表示

参数:
  • g (DGLGraph) – 批大小为 B 的 DGLGraph,用于并行处理多个分子

  • feats (形状为 (N, self.in_feats) 的 FloatTensor) – 所有分子中所有原子的表示 * N 是所有分子中原子的总数

返回:

B 个分子的表示

返回类型:

形状为 (B, self.in_feats) 的 FloatTensor