NNConv
- class dgl.nn.pytorch.conv.NNConv(in_feats, out_feats, edge_func, aggregator_type='mean', residual=False, bias=True)[source]
Bases:
Module
图卷积层来自量子化学的神经消息传递
\[h_{i}^{l+1} = h_{i}^{l} + \mathrm{aggregate}\left(\left\{ f_\Theta (e_{ij}) \cdot h_j^{l}, j\in \mathcal{N}(i) \right\}\right)\]其中 \(e_{ij}\) 是边的特征,\(f_\Theta\) 是一个具有可学习参数的函数。
- Parameters:
in_feats (int) – 输入特征大小;即\(h_j^{(l)}\)的维度数。 NNConv可以应用于同构图和单向的 二分图。 如果该层要应用于单向二分图,
in_feats
指定源节点和目标节点的输入特征大小。如果 给定一个标量,源节点和目标节点的特征大小将取相同的值。out_feats (int) – Output feature size; i.e., the number of dimensions of \(h_i^{(l+1)}\).
edge_func (可调用的激活函数/层) – 将每个边的特征映射为形状为
(in_feats * out_feats)
的向量作为权重来计算 消息。 同时也是公式中的 \(f_\Theta\)。aggregator_type (str) – 使用的聚合器类型 (
sum
,mean
或max
)。残差 (bool, 可选) – 如果为True,使用残差连接。默认值:
False
。bias (bool, optional) – If True, adds a learnable bias to the output. Default:
True
.
示例
>>> import dgl >>> import numpy as np >>> import torch as th >>> from dgl.nn import NNConv
>>> # Case 1: Homogeneous graph >>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3])) >>> g = dgl.add_self_loop(g) >>> feat = th.ones(6, 10) >>> lin = th.nn.Linear(5, 20) >>> def edge_func(efeat): ... return lin(efeat) >>> efeat = th.ones(6+6, 5) >>> conv = NNConv(10, 2, edge_func, 'mean') >>> res = conv(g, feat, efeat) >>> res tensor([[-1.5243, -0.2719], [-1.5243, -0.2719], [-1.5243, -0.2719], [-1.5243, -0.2719], [-1.5243, -0.2719], [-1.5243, -0.2719]], grad_fn=<AddBackward0>)
>>> # Case 2: Unidirectional bipartite graph >>> u = [0, 1, 0, 0, 1] >>> v = [0, 1, 2, 3, 2] >>> g = dgl.heterograph({('_N', '_E', '_N'):(u, v)}) >>> u_feat = th.tensor(np.random.rand(2, 10).astype(np.float32)) >>> v_feat = th.tensor(np.random.rand(4, 10).astype(np.float32)) >>> conv = NNConv(10, 2, edge_func, 'mean') >>> efeat = th.ones(5, 5) >>> res = conv(g, (u_feat, v_feat), efeat) >>> res tensor([[-0.6568, 0.5042], [ 0.9089, -0.5352], [ 0.1261, -0.0155], [-0.6568, 0.5042]], grad_fn=<AddBackward0>)
- forward(graph, feat, efeat)[source]
计算MPNN图卷积层。
- Parameters:
graph (DGLGraph) – The graph.
feat (torch.Tensor 或 pair 的 torch.Tensor) – 输入特征的形状为 \((N, D_{in})\),其中 \(N\) 是图中节点的数量,\(D_{in}\) 是 输入特征的大小。
efeat (torch.Tensor) – 形状为 \((E, *)\) 的边特征,应符合
edge_func
的输入形状要求。\(E\) 是图的边数。
- Returns:
The output feature of shape \((N, D_{out})\) where \(D_{out}\) is the output feature size.
- Return type:
torch.Tensor