Source code for torch_geometric.nn.conv.gated_graph_conv

import torch
from torch import Tensor
from torch.nn import Parameter as Param
from torch_geometric.nn.conv import MessagePassing

from ..inits import uniform

[docs]class GatedGraphConv(MessagePassing): r"""The gated graph convolution operator from the `"Gated Graph Sequence Neural Networks" <>`_ paper .. math:: \mathbf{h}_i^{(0)} &= \mathbf{x}_i \, \Vert \, \mathbf{0} \mathbf{m}_i^{(l+1)} &= \sum_{j \in \mathcal{N}(i)} \mathbf{\Theta} \cdot \mathbf{h}_j^{(l)} \mathbf{h}_i^{(l+1)} &= \textrm{GRU} (\mathbf{m}_i^{(l+1)}, \mathbf{h}_i^{(l)}) up to representation :math:`\mathbf{h}_i^{(L)}`. The number of input channels of :math:`\mathbf{x}_i` needs to be less or equal than :obj:`out_channels`. Args: out_channels (int): Size of each input sample. num_layers (int): The sequence length :math:`L`. aggr (string, optional): The aggregation scheme to use (:obj:`"add"`, :obj:`"mean"`, :obj:`"max"`). (default: :obj:`"add"`) bias (bool, optional): If set to :obj:`False`, the layer will not learn an additive bias. (default: :obj:`True`) **kwargs (optional): Additional arguments of :class:`torch_geometric.nn.conv.MessagePassing`. """ def __init__(self, out_channels, num_layers, aggr='add', bias=True, **kwargs): super(GatedGraphConv, self).__init__(aggr=aggr, **kwargs) self.out_channels = out_channels self.num_layers = num_layers self.weight = Param(Tensor(num_layers, out_channels, out_channels)) self.rnn = torch.nn.GRUCell(out_channels, out_channels, bias=bias) self.reset_parameters()
[docs] def reset_parameters(self): uniform(self.out_channels, self.weight) self.rnn.reset_parameters()
[docs] def forward(self, x, edge_index, edge_weight=None): """""" h = x if x.dim() == 2 else x.unsqueeze(-1) if h.size(1) > self.out_channels: raise ValueError('The number of input channels is not allowed to ' 'be larger than the number of output channels') if h.size(1) < self.out_channels: zero = h.new_zeros(h.size(0), self.out_channels - h.size(1)) h =[h, zero], dim=1) for i in range(self.num_layers): m = torch.matmul(h, self.weight[i]) m = self.propagate(edge_index, x=m, edge_weight=edge_weight) h = self.rnn(m, h) return h
def message(self, x_j, edge_weight): if edge_weight is not None: return edge_weight.view(-1, 1) * x_j return x_j def __repr__(self): return '{}({}, num_layers={})'.format( self.__class__.__name__, self.out_channels, self.num_layers)