DGL-GrapgConv源码注释

  • Post author:
  • Post category:其他


DGL中GraphConv源码解读,带原理论文Semi-Supervised Classification with Graph Convolutional Networks笔记



论文笔记(建议先看,便于后续源码理解)

Semi-Supervised Classification with Graph Convolutional Networks论文介绍了一种基于频谱的图卷积方法。在此展示论文笔记,结合论文应该可以看懂(大概吧。。。)

论文链接:

https://arxiv.org/abs/1609.02907


论文笔记1

论文笔记2



源码解释(关键点都写在注释里)

下方是DGL中GraphConv层定义的全部代码,对其中关键部分进行了注释,结合原论文应该可以看懂。

"""Torch modules for graph convolutions(GCN)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init

from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair

# pylint: disable=W0235
class GraphConv(nn.Module):
    r"""

    Description
    -----------
    下述链接是DGL中图卷积的原理来源论文
    Graph convolution was introduced in `GCN <https://arxiv.org/abs/1609.02907>`__
    and mathematically is defined as follows:
    
    这个公式格式写的不太好理解,可以直接看论文
    .. math::
      h_i^{(l+1)} = \sigma(b^{(l)} + \sum_{j\in\mathcal{N}(i)}\frac{1}{c_{ij}}h_j^{(l)}W^{(l)})

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

    Parameters
    ----------
    一些参数的定义
    in_feats : int 输入值图卷积层的特征的维度
        Input feature size; i.e, the number of dimensions of :math:`h_j^{(l)}`.
    out_feats : int 图卷积层输出特征的维度
        Output feature size; i.e., the number of dimensions of :math:`h_i^{(l+1)}`.
    norm : str, optional 是否进行标准化
        How to apply the normalizer. If is `'right'`, divide the aggregated messages
        by each node's in-degrees, which is equivalent to averaging the received messages.
        If is `'none'`, no normalization is applied. Default is `'both'`,
        where the :math:`c_{ij}` in the paper is applied.
    weight : bool, optional # 是否使用线性层进行权重相乘来实现数据聚合,如果False,则直接对数据进行聚合
        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 # 是否允许graph中存在输入degree为0的节点,因为这样的节点会对信息传输造成不好的影响
        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``.

    Attributes
    ----------
    weight : torch.Tensor
        The learnable weight tensor.
    bias : torch.Tensor
        The learnable bias 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
    >>> g = dgl.add_self_loop(g)

    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 zere-in-degree nodes manually.
    A common practise to handle this is to filter out the nodes with zere-in-degree when use
    after conv.
    """
    # 初始化众多参数
    def __init__(self,
                 in_feats,
                 out_feats,
                 norm='both',
                 weight=True,
                 bias=True,
                 activation=None,
                 allow_zero_in_degree=False):
        super(GraphConv, self).__init__()
        if norm not in ('none', 'both', 'right'):
            raise DGLError('Invalid norm value. Must be either "none", "both" or "right".'
                           ' But got "{}".'.format(norm))
        self._in_feats = in_feats
        self._out_feats = out_feats
        self._norm = norm
        self._allow_zero_in_degree = allow_zero_in_degree

        if weight:
            self.weight = nn.Parameter(th.Tensor(in_feats, out_feats)) # 当使用weight时,将其定义为tensor,用于后续计算
        else:
            self.register_parameter('weight', None)

        if bias:
            self.bias = nn.Parameter(th.Tensor(out_feats)) # 定义tensor类型的bias
        else:
            self.register_parameter('bias', None)

        self.reset_parameters()

        self._activation = activation

    def reset_parameters(self): # 初始化可学习的参数
        r"""

        Description
        -----------
        Reinitialize learnable parameters.

        Note
        ----
        The model parameters are initialized as in the
        `original implementation <https://github.com/tkipf/gcn/blob/master/gcn/layers.py>`__
        where the weight :math:`W^{(l)}` is initialized using Glorot uniform initialization
        and the bias is initialized to be zero.

        """
        if self.weight is not None: # 当存在weight时,对weight初始化,便于训练
            init.xavier_uniform_(self.weight)
        if self.bias is not None: # 当存在bias时,对bias初始化,便于训练
            init.zeros_(self.bias)

    def set_allow_zero_in_degree(self, set_value): # 允许graph存在输入degree为0的节点
        r"""

        Description
        -----------
        Set allow_zero_in_degree flag.

        Parameters
        ----------
        set_value : bool
            The value to be set to the flag.
        """
        self._allow_zero_in_degree = set_value

    def forward(self, graph, feat, weight=None): # 定义图卷积层的传输规则
        r"""

        Description
        -----------
        Compute graph convolution.

        Parameters
        ----------
        graph : DGLGraph # 输入的graph
            The graph.
        feat : torch.Tensor or pair of torch.Tensor 输入至网络层的特征
            If a torch.Tensor is given, it represents the input feature of shape
            :math:`(N, D_{in})`
            where :math:`D_{in}` is size of input feature, :math:`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 :math:`(N_{in}, D_{in_{src}})` and
            :math:`(N_{out}, D_{in_{dst}})`.
        weight : torch.Tensor, optional # 权重矩阵
            Optional external weight tensor.

        Returns
        -------
        torch.Tensor
            The output feature

        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: :math:`(N, *, \text{in_feats})` where * means any number of additional
          dimensions, :math:`N` is the number of nodes.
        * Output shape: :math:`(N, *, \text{out_feats})` where all but the last dimension are
          the same shape as the input.
        * Weight shape: :math:`(\text{in_feats}, \text{out_feats})`.
        """
        with graph.local_scope(): # 在graph的作用域中进行计算,便于结束计算时清楚记录
            if not self._allow_zero_in_degree: # 如果不允许输入degree为0,但输入的graph的输入degree还有0,则报错
                if (graph.in_degrees() == 0).any():
                    raise DGLError('There are 0-in-degree nodes in the graph, '
                                   'output for those nodes will be invalid. '
                                   'This is harmful for some applications, '
                                   'causing silent performance regression. '
                                   'Adding self-loop on the input graph by '
                                   'calling `g = dgl.add_self_loop(g)` will resolve '
                                   'the issue. Setting ``allow_zero_in_degree`` '
                                   'to be `True` when constructing this module will '
                                   'suppress the check and let the code run.')

            # (BarclayII) For RGCN on heterogeneous graphs we need to support GCN on bipartite.
            feat_src, feat_dst = expand_as_pair(feat, graph) # 将单向图转为双向图
            if self._norm == 'both':
                degs = graph.out_degrees().float().clamp(min=1) # 根据邻接矩阵计算度矩阵
                norm = th.pow(degs, -0.5) # norm = D^-1/2
                shp = norm.shape + (1,) * (feat_src.dim() - 1)
                norm = th.reshape(norm, shp) # 将norm转换为可与feat_src做矩阵乘法的形式
                feat_src = feat_src * norm # feat_src = D^-1/2 * feat_src

            if weight is not None: # 当定义中要求有weight,但实例中无weight时,报错
                if self.weight is not None:
                    raise DGLError('External weight is provided while at the same time the'
                                   ' module has defined its own weight parameter. Please'
                                   ' create the module with flag weight=False.')
            else:
                weight = self.weight

            if self._in_feats > self._out_feats: # 当输入特征维度大于输出特征维度时,先进行与W的矩阵乘法,再进行聚类
                # mult W first to reduce the feature size for aggregation.
                if weight is not None: # 有weight时
                    feat_src = th.matmul(feat_src, weight) # 进行输入特征与权重的矩阵乘法
                graph.srcdata['h'] = feat_src # 把上一步得到的结果赋予graph中srcdata(即源节点)的‘h’属性
                graph.update_all(fn.copy_src(src='h', out='m'), # 在graph中进行数据传输,实现功能:将上述矩阵乘法的结果传输至相邻节点;然后每个节点对接收到的数据进行求和
                                 fn.sum(msg='m', out='h'))
                rst = graph.dstdata['h'] # graph.dstdata['h']即为上一步经历数据传输,聚合后,节点的新特征,将其提取出赋给rst
            else:# 当输入特征维度小于输出特征维度时,先进行聚类,再进行与W的矩阵乘法
                # aggregate first then mult W
                graph.srcdata['h'] = feat_src # 把输入的feat_src赋值给graph中srcdata(即原节点)的‘h’属性
                graph.update_all(fn.copy_src(src='h', out='m'), # 在graph中进行数据传输,实现功能:将上述矩阵乘法的结果传输至相邻节点;然后每个节点对接收到的数据进行求和
                                 fn.sum(msg='m', out='h'))
                rst = graph.dstdata['h'] # graph.dstdata['h']即为上一步经历数据传输,聚合后,节点的新特征,将其提取出赋给rst
                if weight is not None:
                    rst = th.matmul(rst, weight) # 对上一步的rst进行与weight的矩阵乘法运算

            if self._norm != 'none': # 当允许标准化时,对特征进行标准化
                degs = graph.in_degrees().float().clamp(min=1)
                if self._norm == 'both':
                    norm = th.pow(degs, -0.5) # 当norm的方法选择‘both’时,norm = D^-1/2
                else:
                    norm = 1.0 / degs # 否则,norm = D^-1
                shp = norm.shape + (1,) * (feat_dst.dim() - 1)
                norm = th.reshape(norm, shp) # 将norm转换为可与feat_src做矩阵乘法的形式
                rst = rst * norm # 对rst进行标准化处理

            if self.bias is not None: # 当允许加入bias时,直接对rst加上bias
                rst = rst + self.bias

            if self._activation is not None: # 允许激活时,对rst进行激活函数处理
                rst = self._activation(rst)

            return rst 
            # 图卷积层的输出,若norm=both,weight=True,bias = True,此时rst = activation(D^-1/2*A*D^-1/2*H*W)
            # 其中A为加了自环的邻接矩阵,D为度矩阵,H为输入特征,W为权重,这与论文介绍的公式相同,至此实现最基础的基于频域的图卷积计算
    def extra_repr(self): # 用于打印网络层信息的函数
        """Set the extra representation of the module,
        which will come into effect when printing the model.
        """
        summary = 'in={_in_feats}, out={_out_feats}'
        summary += ', normalization={_norm}'
        if '_activation' in self.__dict__:
            summary += ', activation={_activation}'
        return summary.format(**self.__dict__)



版权声明:本文为qq_42599237原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。