# GraphConv¶

class dgl.nn.pytorch.conv.GraphConv(in_feats, out_feats, norm='both', weight=True, bias=True, activation=None, allow_zero_in_degree=False)[source]

Bases: torch.nn.modules.module.Module

Graph convolutional layer from Semi-Supervised Classification with Graph Convolutional Networks

Mathematically it is defined as follows:

$h_i^{(l+1)} = \sigma(b^{(l)} + \sum_{j\in\mathcal{N}(i)}\frac{1}{c_{ji}}h_j^{(l)}W^{(l)})$

where $$\mathcal{N}(i)$$ is the set of neighbors of node $$i$$, $$c_{ji}$$ is the product of the square root of node degrees (i.e., $$c_{ji} = \sqrt{|\mathcal{N}(j)|}\sqrt{|\mathcal{N}(i)|}$$), and $$\sigma$$ is an activation function.

If a weight tensor on each edge is provided, the weighted graph convolution is defined as:

$h_i^{(l+1)} = \sigma(b^{(l)} + \sum_{j\in\mathcal{N}(i)}\frac{e_{ji}}{c_{ji}}h_j^{(l)}W^{(l)})$

where $$e_{ji}$$ is the scalar weight on the edge from node $$j$$ to node $$i$$. This is NOT equivalent to the weighted graph convolutional network formulation in the paper.

To customize the normalization term $$c_{ji}$$, one can first set norm='none' for the model, and send the pre-normalized $$e_{ji}$$ to the forward computation. We provide EdgeWeightNorm to normalize scalar edge weight following the GCN paper.

Parameters
• in_feats (int) – Input feature size; i.e, the number of dimensions of $$h_j^{(l)}$$.

• out_feats (int) – Output feature size; i.e., the number of dimensions of $$h_i^{(l+1)}$$.

• norm (str, optional) –

How to apply the normalizer. Can be one of the following values:

• right, to divide the aggregated messages by each node’s in-degrees, which is equivalent to averaging the received messages.

• none, where no normalization is applied.

• both (default), where the messages are scaled with $$1/c_{ji}$$ above, equivalent to symmetric normalization.

• left, to divide the messages sent out from each node by its out-degrees, equivalent to random walk normalization.

• weight (bool, optional) – If True, apply a linear layer. Otherwise, aggregating the messages without a weight matrix.

• bias (bool, optional) – If True, adds a learnable bias to the output. Default: True.

• activation (callable activation function/layer or None, optional) – If not None, applies an activation function to the updated node features. Default: None.

• allow_zero_in_degree (bool, optional) – If there are 0-in-degree nodes in the graph, output for those nodes will be invalid since no message will be passed to those nodes. This is harmful for some applications causing silent performance regression. This module will raise a DGLError if it detects 0-in-degree nodes in input graph. By setting True, it will suppress the check and let the users handle it by themselves. Default: False.

weight

The learnable weight tensor.

Type

torch.Tensor

bias

The learnable bias tensor.

Type

torch.Tensor

Note

Zero in-degree nodes will lead to invalid output value. This is because no message will be passed to those nodes, the aggregation function will be appied on empty input. A common practice to avoid this is to add a self-loop for each node in the graph if it is homogeneous, which can be achieved by:

>>> g = ... # a DGLGraph


Calling add_self_loop will not work for some graphs, for example, heterogeneous graph since the edge type can not be decided for self_loop edges. Set allow_zero_in_degree to True for those cases to unblock the code and handle zero-in-degree nodes manually. A common practise to handle this is to filter out the nodes with zero-in-degree when use after conv.

Examples

>>> import dgl
>>> import numpy as np
>>> import torch as th
>>> from dgl.nn import GraphConv

>>> # Case 1: Homogeneous graph
>>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3]))
>>> feat = th.ones(6, 10)
>>> conv = GraphConv(10, 2, norm='both', weight=True, bias=True)
>>> res = conv(g, feat)
>>> print(res)
tensor([[ 1.3326, -0.2797],
[ 1.4673, -0.3080],
[ 1.3326, -0.2797],
[ 1.6871, -0.3541],
[ 1.7711, -0.3717],
>>> # allow_zero_in_degree example
>>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3]))
>>> conv = GraphConv(10, 2, norm='both', weight=True, bias=True, allow_zero_in_degree=True)
>>> res = conv(g, feat)
>>> print(res)
tensor([[-0.2473, -0.4631],
[-0.3497, -0.6549],
[-0.3497, -0.6549],
[-0.4221, -0.7905],
[-0.3497, -0.6549],

>>> # Case 2: Unidirectional bipartite graph
>>> u = [0, 1, 0, 0, 1]
>>> v = [0, 1, 2, 3, 2]
>>> g = dgl.heterograph({('_U', '_E', '_V') : (u, v)})
>>> u_fea = th.rand(2, 5)
>>> v_fea = th.rand(4, 5)
>>> conv = GraphConv(5, 2, norm='both', weight=True, bias=True)
>>> res = conv(g, (u_fea, v_fea))
>>> res
tensor([[-0.2994,  0.6106],
[-0.4482,  0.5540],
[-0.5287,  0.8235],

forward(graph, feat, weight=None, edge_weight=None)[source]

Compute graph convolution.

Parameters
• graph (DGLGraph) – The graph.

• feat (torch.Tensor or pair of torch.Tensor) – If a torch.Tensor is given, it represents the input feature of shape $$(N, D_{in})$$ where $$D_{in}$$ is size of input feature, $$N$$ is the number of nodes. If a pair of torch.Tensor is given, which is the case for bipartite graph, the pair must contain two tensors of shape $$(N_{in}, D_{in_{src}})$$ and $$(N_{out}, D_{in_{dst}})$$.

• weight (torch.Tensor, optional) – Optional external weight tensor.

• edge_weight (torch.Tensor, optional) – Optional tensor on the edge. If given, the convolution will weight with regard to the message.

Returns

The output feature

Return type

torch.Tensor

Raises

DGLError – Case 1: If there are 0-in-degree nodes in the input graph, it will raise DGLError since no message will be passed to those nodes. This will cause invalid output. The error can be ignored by setting allow_zero_in_degree parameter to True. Case 2: External weight is provided while at the same time the module has defined its own weight parameter.

Note

• Input shape: $$(N, *, \text{in_feats})$$ where * means any number of additional dimensions, $$N$$ is the number of nodes.

• Output shape: $$(N, *, \text{out_feats})$$ where all but the last dimension are the same shape as the input.

• Weight shape: $$(\text{in_feats}, \text{out_feats})$$.

reset_parameters()[source]

Reinitialize learnable parameters.

Note

The model parameters are initialized as in the original implementation where the weight $$W^{(l)}$$ is initialized using Glorot uniform initialization and the bias is initialized to be zero.