-
Notifications
You must be signed in to change notification settings - Fork 147
/
Rsage.py
80 lines (72 loc) · 2.57 KB
/
Rsage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import dgl
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import dgl.nn as dglnn
from . import BaseModel, register_model
@register_model('Rsage')
class Rsage(BaseModel):
@classmethod
def build_model_from_args(cls, args, hg):
return cls(in_dim=args.in_dim,
out_dim=args.out_dim,
h_dim=args.hidden_dim,
etypes=hg.etypes,
aggregator_type=args.aggregator_type,
num_hidden_layers=args.num_layers - 2,
dropout=args.dropout)
def __init__(self, in_dim,
out_dim,
h_dim,
etypes,
aggregator_type,
num_hidden_layers=1,
dropout=0):
super(Rsage, self).__init__()
self.rel_names = etypes
self.layers = nn.ModuleList()
# input 2 hidden
self.layers.append(RsageLayer(
in_dim, h_dim, aggregator_type, self.rel_names, activation=F.relu, dropout=dropout))
for i in range(num_hidden_layers):
self.layers.append(RsageLayer(
h_dim, h_dim, aggregator_type, self.rel_names, activation=F.relu, dropout=dropout
))
self.layers.append(RsageLayer(
h_dim, out_dim, aggregator_type, self.rel_names, activation=None))
return
def forward(self, hg, h_dict=None):
if hasattr(hg, 'ntypes'):
# full graph training,
for layer in self.layers:
h_dict = layer(hg, h_dict)
else:
# minibatch training, block
for layer, block in zip(self.layers, hg):
h_dict = layer(block, h_dict)
return h_dict
class RsageLayer(nn.Module):
def __init__(self,
in_feat,
out_feat,
aggregator_type,
rel_names,
activation=None,
dropout=0.0,
bias=True):
super(RsageLayer, self).__init__()
self.in_feat = in_feat
self.out_feat = out_feat
self.aggregator_type = aggregator_type
self.activation = activation
self.dropout = nn.Dropout(dropout)
self.conv = dglnn.HeteroGraphConv({
rel: dgl.nn.pytorch.SAGEConv(in_feat, out_feat, aggregator_type, bias=bias)
for rel in rel_names
})
def forward(self, g, h_dict):
h_dict = self.conv(g, h_dict)
out_put = {}
for n_type, h in h_dict.items():
out_put[n_type] = h.squeeze()
return out_put