spline_conv.py 1.77 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
import torch
rusty1s's avatar
rusty1s committed
2
from torch.autograd import Variable as Var
rusty1s's avatar
rusty1s committed
3
4

from .degree import node_degree
5
from .spline_weighting import spline_weighting
rusty1s's avatar
rusty1s committed
6
7
8
9
10
11
12
13
14
15
16
17


def spline_conv(x,
                edge_index,
                pseudo,
                weight,
                kernel_size,
                is_open_spline,
                root_weight=None,
                degree=1,
                bias=None):

rusty1s's avatar
typos  
rusty1s committed
18
    # Convolve over each node.
19
20
    output = basic_spline_conv(x, edge_index, pseudo, weight, kernel_size,
                               is_open_spline, degree)
rusty1s's avatar
rusty1s committed
21
22

    # Normalize output by node degree.
rusty1s's avatar
rusty1s committed
23
    degree = x.new() if torch.is_tensor(x) else x.data.new()
24
25
    degree = node_degree(edge_index, x.size(0), out=degree)
    degree = degree.unsqueeze(-1).clamp_(min=1)
rusty1s's avatar
rusty1s committed
26
    output /= degree if torch.is_tensor(x) else Var(degree)
rusty1s's avatar
rusty1s committed
27
28
29
30
31
32
33
34
35
36

    # Weight root node separately (if wished).
    if root_weight is not None:
        output += torch.mm(x, root_weight)

    # Add bias (if wished).
    if bias is not None:
        output += bias

    return output
rusty1s's avatar
rusty1s committed
37
38


39
40
def basic_spline_conv(x, edge_index, pseudo, weight, kernel_size,
                      is_open_spline, degree):
rusty1s's avatar
rusty1s committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

    n, e, m_out = x.size(0), edge_index.size(1), weight.size(2)

    x = x.unsqueeze(-1) if x.dim() == 1 else x

    # Weight gathered features based on B-spline bases and trainable weights.
    output = spline_weighting(x[edge_index[1]], pseudo, weight, kernel_size,
                              is_open_spline, degree)

    # Perform the real convolution => Convert e x m_out to n x m_out features.
    row = edge_index[0].unsqueeze(-1).expand(e, m_out)
    row = row if torch.is_tensor(x) else Var(row)
    zero = x.new(n, m_out) if torch.is_tensor(x) else Var(x.data.new(n, m_out))
    output = zero.fill_(0).scatter_add_(0, row, output)

    return output