-
Notifications
You must be signed in to change notification settings - Fork 98
/
model.py
156 lines (137 loc) · 6.55 KB
/
model.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import torch.nn as nn
import torch.nn.functional as F
import torch
from torch.autograd import Variable
class BatchTreeEncoder(nn.Module):
def __init__(self, vocab_size, embedding_dim, encode_dim, batch_size, use_gpu, pretrained_weight=None):
super(BatchTreeEncoder, self).__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.encode_dim = encode_dim
self.W_c = nn.Linear(embedding_dim, encode_dim)
self.W_l = nn.Linear(encode_dim, encode_dim)
self.W_r = nn.Linear(encode_dim, encode_dim)
self.activation = F.relu
self.stop = -1
self.batch_size = batch_size
self.use_gpu = use_gpu
self.node_list = []
self.th = torch.cuda if use_gpu else torch
self.batch_node = None
# pretrained embedding
if pretrained_weight is not None:
self.embedding.weight.data.copy_(torch.from_numpy(pretrained_weight))
# self.embedding.weight.requires_grad = False
def create_tensor(self, tensor):
if self.use_gpu:
return tensor.cuda()
return tensor
def traverse_mul(self, node, batch_index):
size = len(node)
if not size:
return None
batch_current = self.create_tensor(Variable(torch.zeros(size, self.encode_dim)))
index, children_index = [], []
current_node, children = [], []
for i in range(size):
if node[i][0] is not -1:
index.append(i)
current_node.append(node[i][0])
temp = node[i][1:]
c_num = len(temp)
for j in range(c_num):
if temp[j][0] is not -1:
if len(children_index) <= j:
children_index.append([i])
children.append([temp[j]])
else:
children_index[j].append(i)
children[j].append(temp[j])
else:
batch_index[i] = -1
batch_current = self.W_c(batch_current.index_copy(0, Variable(self.th.LongTensor(index)),
self.embedding(Variable(self.th.LongTensor(current_node)))))
for c in range(len(children)):
zeros = self.create_tensor(Variable(torch.zeros(size, self.encode_dim)))
batch_children_index = [batch_index[i] for i in children_index[c]]
tree = self.traverse_mul(children[c], batch_children_index)
if tree is not None:
batch_current += zeros.index_copy(0, Variable(self.th.LongTensor(children_index[c])), tree)
# batch_current = F.tanh(batch_current)
batch_index = [i for i in batch_index if i is not -1]
b_in = Variable(self.th.LongTensor(batch_index))
self.node_list.append(self.batch_node.index_copy(0, b_in, batch_current))
return batch_current
def forward(self, x, bs):
self.batch_size = bs
self.batch_node = self.create_tensor(Variable(torch.zeros(self.batch_size, self.encode_dim)))
self.node_list = []
self.traverse_mul(x, list(range(self.batch_size)))
self.node_list = torch.stack(self.node_list)
return torch.max(self.node_list, 0)[0]
class BatchProgramClassifier(nn.Module):
# def __init__(self, embedding_dim, hidden_dim, vocab_size, encode_dim, label_size, batch_size, use_gpu=True, pretrained_weight=None):
def __init__(self, embedding_dim, hidden_dim, vocab_size, encode_dim, label_size, batch_size, use_gpu=True, pretrained_weight=None):
super(BatchProgramClassifier, self).__init__()
self.stop = [vocab_size-1]
self.hidden_dim = hidden_dim
self.num_layers = 1
self.gpu = use_gpu
self.batch_size = batch_size
self.vocab_size = vocab_size
self.embedding_dim = embedding_dim
self.encode_dim = encode_dim
self.label_size = label_size
#class "BatchTreeEncoder"
self.encoder = BatchTreeEncoder(self.vocab_size, self.embedding_dim, self.encode_dim,
self.batch_size, self.gpu, pretrained_weight)
self.root2label = nn.Linear(self.encode_dim, self.label_size)
# gru
self.bigru = nn.GRU(self.encode_dim, self.hidden_dim, num_layers=self.num_layers, bidirectional=True,
batch_first=True)
# linear
self.hidden2label = nn.Linear(self.hidden_dim * 2, self.label_size)
# hidden
self.hidden = self.init_hidden()
self.dropout = nn.Dropout(0.2)
def init_hidden(self):
if self.gpu is True:
if isinstance(self.bigru, nn.LSTM):
h0 = Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim).cuda())
c0 = Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim).cuda())
return h0, c0
return Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim)).cuda()
else:
return Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim))
def get_zeros(self, num):
zeros = Variable(torch.zeros(num, self.encode_dim))
if self.gpu:
return zeros.cuda()
return zeros
def forward(self, x):
lens = [len(item) for item in x]
max_len = max(lens)
encodes = []
for i in range(self.batch_size):
for j in range(lens[i]):
encodes.append(x[i][j])
encodes = self.encoder(encodes, sum(lens))
seq, start, end = [], 0, 0
for i in range(self.batch_size):
end += lens[i]
seq.append(encodes[start:end])
if max_len-lens[i]:
seq.append(self.get_zeros(max_len-lens[i]))
start = end
encodes = torch.cat(seq)
encodes = encodes.view(self.batch_size, max_len, -1)
encodes = nn.utils.rnn.pack_padded_sequence(encodes, torch.LongTensor(lens), True, False)
# gru
gru_out, _ = self.bigru(encodes, self.hidden)
gru_out, _ = nn.utils.rnn.pad_packed_sequence(gru_out, batch_first=True, padding_value=-1e9)
gru_out = torch.transpose(gru_out, 1, 2)
# pooling
gru_out = F.max_pool1d(gru_out, gru_out.size(2)).squeeze(2)
# gru_out = gru_out[:,-1]
# linear
y = self.hidden2label(gru_out)
return y