-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathConvGRUCell3.py
251 lines (222 loc) · 10.3 KB
/
ConvGRUCell3.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - zihao.chen <zihao.chen@moji.com>
'''
Author: zihao.chen
Create Date: 2018-03-29
Modify Date: 2018-03-29
descirption: ""
'''
import torch
from torch import nn
import torch.nn.functional as f
import numpy as np
from torch.autograd import Variable
class ConvGRUCell2(nn.Module):
#input_size=(128, 256), hidden_size=128, kernel_size=(3,3)
def __init__(self, input_size, hidden_size, kernel_size):
super(ConvGRUCell2, self).__init__()
#num_layer=2, so print 2 time2
# print('self.input--00000-', input_size, hidden_size)
self.input_size = input_size
self.hidden_size = hidden_size
self.kernel_size = kernel_size
self.height, self.width = 64, 128
self.dropout = nn.Dropout(p=0.5)
# print('kernal-----', kernel_size[0], kernel_size[1])
self.padding = kernel_size[0] // 2, kernel_size[1] // 2
self.ConvGates = nn.Conv2d(self.input_size + self.hidden_size,
2 * self.hidden_size,
self.kernel_size,
padding=self.padding
)
self.Conv_ct = nn.Conv2d(self.input_size + self.hidden_size, self.hidden_size, self.kernel_size,
padding=self.padding)
# dtype = torch.FloatTensor
#input = [5, 3, 64, 128, 256], hidden=
def forward(self, input, hidden):
if hidden is None:
# print('input----', input.shape)
size_h = [input.data.size()[0], self.hidden_size] + list(input.data.size()[2:])
# print size_h
hidden = Variable(torch.zeros(size_h).cuda())
if input is None:
# print (input.data.size()[0])
# print (self.hidden_size)
# print (list(input.data.size()[2:]))
size_h = [hidden.data.size()[0], self.input_size] + list(hidden.data.size()[2:])
# print size_h
input = Variable(torch.zeros(size_h).cuda())
# print input.size()
# print hidden.size()
# print('input--hidden----', input.shape, hidden.shape)
tmp = torch.cat((input, hidden), 1)
# print('tmp----', tmp.shape)
c1 = self.ConvGates(tmp)
# print('c1-----', c1.shape)
(rt, ut) = c1.chunk(2, 1)
# print('rt-----', rt.shape)
# print('ut-----', ut.shape)
# reset_gate = self.dropout(f.sigmoid(rt))
# update_gate = self.dropout(f.sigmoid(ut))
reset_gate = self.dropout(torch.sigmoid(rt))
update_gate = self.dropout(torch.sigmoid(ut))
# print('reset_gate-----', reset_gate.shape)
# print('update_gate-----', update_gate.shape)
# print('hidden----', hidden.shape)
gated_hidden = torch.mul(reset_gate, hidden)
p1 = self.Conv_ct(torch.cat((input, gated_hidden), 1))
# ct = f.tanh(p1)
ct = torch.tanh(p1)
next_h = torch.mul(update_gate, hidden) + (1 - update_gate) * ct
# print('next_h----', next_h.shape)
return next_h, 0
def init_hidden(self, batch_size):
# print('init_hidden---', self.hidden_size, self.height)
return (torch.zeros(batch_size, self.hidden_size, self.height, self.width).cuda(),
torch.zeros(batch_size, self.hidden_size, self.height, self.width).cuda())
class ConvGRU3(nn.Module):
# input_size=(128,256), input_dim=128, hidden_dim=[128, 128], kernel_size=(3,3), num_layers=2
def __init__(self, input_size, input_dim, hidden_dim, kernel_size, num_layers,
batch_first=False, bias=True, return_all_layers=False):
super(ConvGRU3, self).__init__()
self._check_kernel_size_consistency(kernel_size)
# Make sure that both `kernel_size` and `hidden_dim` are lists having len == num_layers
kernel_size = self._extend_for_multilayer(kernel_size, num_layers)
hidden_dim = self._extend_for_multilayer(hidden_dim, num_layers)
if not len(kernel_size) == len(hidden_dim) == num_layers:
raise ValueError('Inconsistent list length.')
# input_size = (8, 16) is a tuple, notate the useful method to sign values for height, and width
self.height, self.width = input_size
# print('input_dim-----', input_dim, hidden_dim[0])
self.input_dim = input_dim #128
self.hidden_dim = hidden_dim #128,128
self.kernel_size = kernel_size
self.num_layers = num_layers
self.batch_first = batch_first
self.bias = bias
self.return_all_layers = return_all_layers
cell_list = []
for i in range(0, self.num_layers):
cur_input_dim = self.input_dim if i == 0 else self.hidden_dim[i - 1]
# to prepare all parameters for every layer, and then construct a object to be called when needed/required
cell_list.append(ConvGRUCell2(input_size=self.input_dim,
#input_dim=cur_input_dim,
hidden_size= self.hidden_dim[i],
#hidden_dim=self.hidden_dim[i],
kernel_size=self.kernel_size[i])
#bias=self.bias)
)
self.cell_list = nn.ModuleList(cell_list)
def forward(self, input_tensor, hidden_state=None):
"""
Parameters
----------
input_tensor: todo
5-D Tensor either of shape (t, b, c, h, w) or (b, t, c, h, w)
hidden_state: todo
None. todo implement stateful
Returns
-------
last_state_list, layer_output
-------
here data = [5, 1, 512, 8, 16]= input_tensor is passed into ConvLSTM
5 is number of times, each time is one batch, as 1,
and each batch_size size has 512 feature maps, each feature map size is 8x16
"""
# print('input_tensor---', input_tensor.shape)
# input_tensor = [5, 20, 512, 8, 16]
if not self.batch_first:
# (t, b, c, h, w) -> (b, t, c, h, w)
input_tensor = input_tensor.permute(1, 0, 2, 3, 4)
# print('input_tensor---', input_tensor.shape)
# input_tensor.shape = [3, 20, 512, 8, 16]
# Implement stateful ConvLSTM
if hidden_state is not None:
raise NotImplementedError()
else:
# input_tensor.size(0)=1
# print('input_tensor.size(0)--', input_tensor.size(0) = 1)
hidden_state = self._init_hidden(batch_size=input_tensor.size(0))
layer_output_list = []
last_state_list = []
# seq_len = 5, actually is 5 feature map, each size =
seq_len = input_tensor.size(1)
# print('seq_len-----', seq_len)
cur_layer_input = input_tensor
for layer_idx in range(self.num_layers):
# initilize hidden_state
h, c = hidden_state[layer_idx]
# h = c size = [3, 512, 128, 256]
# print('h, c,---', h.shape, c.shape)
output_inner = []
output_inner1 = []
final_out = []
for t in range(seq_len):
# change to run forward of ConvLSTMCell, after input_tensor=cur_layer_input[:, t, :, :, :]
# input_tensor shape is [3, 512, 8, 16]
# h, c = self.cell_list[layer_idx](input_tensor=cur_layer_input[:, t, :, :, :],
# cur_state=[h, c])
# hl = torch.cat((h, c), dim=1)
h, c = self.cell_list[layer_idx](input=cur_layer_input[:, t, :, :, :],
hidden=h)
# del c
# h = h + c/5
# h1, c1 = self.cell_list[layer_idx](input=cur_layer_input[:, t, :, :, :],
# hidden=h)
# aa = torch.sum(h1)
# h = h - h1 / abs(aa)
# print('h------', aa)
# print('h, c----', h.shape, c.shape)
output_inner.append(h)
# print('h---', type(h))
# exit(0)
# output_inner1.append(h1)
# o = output_inner + output_inner1
# print('99------', len(o))
# exit(0)
# for i in range(len(output_inner1)):
# output0 = output_inner1[i] * 0.2 +output_inner[i]*0.8
# final_out.append(output0)
# output_inner = final_out
# print('0--------', len(output_inner), len(output_inner1))
# exit(0)
layer_output = torch.stack(output_inner, dim=1)
# print('1--------', layer_output.shape)
cur_layer_input = layer_output
# print('2--------', cur_layer_input.shape)
layer_output = layer_output.permute(1, 0, 2, 3, 4)
# print('3-------', layer_output.shape)
layer_output_list.append(layer_output)
# print('4-------', layer_output_list)
last_state_list.append([h, c])
# print('5-------', last_state_list)
if not self.return_all_layers:
layer_output_list = layer_output_list[-1:]
# print('6-------', layer_output_list)
last_state_list = last_state_list[-1:]
# print('7-------', last_state_list)
return layer_output_list, last_state_list
def _init_hidden(self, batch_size):
init_states = []
for i in range(self.num_layers):
init_states.append(self.cell_list[i].init_hidden(batch_size))
return init_states
"""
check the type of kernel_size to be the same
"""
@staticmethod
def _check_kernel_size_consistency(kernel_size):
if not (isinstance(kernel_size, tuple) or
(isinstance(kernel_size, list) and all([isinstance(elem, tuple) for elem in kernel_size]))):
raise ValueError('`kernel_size` must be tuple or list of tuples')
"""
if kerner_size = (3,3), num_layers = 2, then _extend_for_multilayer() will make
kernal_size = [(3,3), (3,3)] for each layer
"""
@staticmethod
def _extend_for_multilayer(param, num_layers):
if not isinstance(param, list):
# print('exten_--', param)
param = [param] * num_layers
return param