-
Notifications
You must be signed in to change notification settings - Fork 147
/
models.py
72 lines (60 loc) · 1.99 KB
/
models.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
import torch
import torch.nn as nn
from torch.nn import Module
import torch.nn.functional as F
import math
class SGC(nn.Module):
"""
A Simple PyTorch Implementation of Logistic Regression.
Assuming the features have been preprocessed with k-step graph propagation.
"""
def __init__(self, nfeat, nclass):
super(SGC, self).__init__()
self.W = nn.Linear(nfeat, nclass)
def forward(self, x):
return self.W(x)
class GraphConvolution(Module):
"""
A Graph Convolution Layer (GCN)
"""
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.W = nn.Linear(in_features, out_features, bias=bias)
self.init()
def init(self):
stdv = 1. / math.sqrt(self.W.weight.size(1))
self.W.weight.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = self.W(input)
output = torch.spmm(adj, support)
class GCN(nn.Module):
"""
A Two-layer GCN.
"""
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.dropout = dropout
def forward(self, x, adj, use_relu=True):
x = self.gc1(x, adj)
if use_relu:
x = F.relu(x)
x = F.dropout(x, self.dropout, training=self.training)
x = self.gc2(x, adj)
return x
def get_model(model_opt, nfeat, nclass, nhid=0, dropout=0, cuda=True):
if model_opt == "GCN":
model = GCN(nfeat=nfeat,
nhid=nhid,
nclass=nclass,
dropout=dropout)
elif model_opt == "SGC":
model = SGC(nfeat=nfeat,
nclass=nclass)
else:
raise NotImplementedError('model:{} is not implemented!'.format(model_opt))
if cuda: model.cuda()
return model