| 14 | |
| 15 | |
| 16 | class GraphConvolution(nn.Module): |
| 17 | def __init__(self, device, hidden_dim, sparse_inputs=False, act=nn.Tanh(), bias=True, dropout=0.6): |
| 18 | super(GraphConvolution, self).__init__() |
| 19 | self.active_function = act |
| 20 | self.dropout_rate = dropout |
| 21 | if dropout>0: |
| 22 | self.dropout = nn.Dropout(p=dropout) |
| 23 | self.sparse_inputs = sparse_inputs |
| 24 | self.hidden_dim = hidden_dim |
| 25 | self.bias = bias |
| 26 | self.W = nn.Parameter(torch.zeros(size=(hidden_dim, hidden_dim))) |
| 27 | Truncated_initializer(self.W) |
| 28 | if self.bias: |
| 29 | self.b = nn.Parameter(torch.zeros(hidden_dim)) |
| 30 | else: |
| 31 | self.b = None |
| 32 | self.device = device |
| 33 | |
| 34 | def forward(self, inputs, adj): |
| 35 | x = inputs |
| 36 | x = self.dropout(x) |
| 37 | node_size = adj.size(0) |
| 38 | I = torch.eye(node_size, requires_grad=False).to(self.device) |
| 39 | adj = adj + I |
| 40 | D = torch.diag(torch.sum(adj, dim=1, keepdim=False)) |
| 41 | adj = torch.matmul(torch.inverse(D), adj) |
| 42 | pre_sup = torch.matmul(x, self.W) |
| 43 | output = torch.matmul(adj, pre_sup) |
| 44 | |
| 45 | if self.bias: |
| 46 | output += self.b |
| 47 | if self.active_function is not None: |
| 48 | return self.active_function(output) |
| 49 | else: |
| 50 | return output |
| 51 | |
| 52 | |
| 53 | |