Skip to content

Commit 13ffaad

Browse files
author
zihao.chen_tp
committed
init
1 parent 66715e9 commit 13ffaad

File tree

9 files changed

+1313
-0
lines changed

9 files changed

+1313
-0
lines changed

BMSELoss.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/evn python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2017 - zihao.chen <[email protected]>
4+
'''
5+
Author: zihao.chen
6+
Create Date: 2018-04-12
7+
Modify Date: 2018-04-12
8+
descirption: ""
9+
'''
10+
import torch
11+
12+
13+
class BMSELoss(torch.nn.Module):
14+
15+
def __init__(self):
16+
super(BMSELoss, self).__init__()
17+
self.w_l = [1, 2, 5, 10, 30]
18+
self.y_l = [0.283, 0.353, 0.424, 0.565, 1]
19+
20+
def forward(self, x, y):
21+
w = y.clone()
22+
for i in range(len(self.w_l)):
23+
w[w < self.y_l[i]] = self.w_l[i]
24+
return torch.mean(w * ((y - x)** 2) )

ConvGRUCell.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#!/usr/bin/evn python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2017 - zihao.chen <[email protected]>
4+
'''
5+
Author: zihao.chen
6+
Create Date: 2018-03-29
7+
Modify Date: 2018-03-29
8+
descirption: ""
9+
'''
10+
import torch
11+
from torch import nn
12+
import torch.nn.functional as f
13+
from torch.autograd import Variable
14+
15+
16+
class ConvGRUCell(nn.Module):
17+
18+
def __init__(self, input_size, hidden_size, kernel_size):
19+
super(ConvGRUCell, self).__init__()
20+
self.input_size = input_size
21+
self.hidden_size = hidden_size
22+
self.kernel_size = kernel_size
23+
self.kernel_size = kernel_size
24+
self.dropout = nn.Dropout(p=0.5)
25+
self.ConvGates = nn.Conv2d(self.input_size + self.hidden_size, 2 * self.hidden_size, self.kernel_size,
26+
padding=self.kernel_size // 2)
27+
self.Conv_ct = nn.Conv2d(self.input_size + self.hidden_size, self.hidden_size, self.kernel_size,
28+
padding=self.kernel_size // 2)
29+
dtype = torch.FloatTensor
30+
31+
def forward(self, input, hidden):
32+
if hidden is None:
33+
# print (input.data.size()[0])
34+
# print (self.hidden_size)
35+
# print (list(input.data.size()[2:]))
36+
size_h = [input.data.size()[0], self.hidden_size] + list(input.data.size()[2:])
37+
# print size_h
38+
hidden = Variable(torch.zeros(size_h).cuda())
39+
if input is None:
40+
# print (input.data.size()[0])
41+
# print (self.hidden_size)
42+
# print (list(input.data.size()[2:]))
43+
size_h = [hidden.data.size()[0], self.input_size] + list(hidden.data.size()[2:])
44+
# print size_h
45+
input = Variable(torch.zeros(size_h).cuda())
46+
# print input.size()
47+
# print hidden.size()
48+
c1 = self.ConvGates(torch.cat((input, hidden), 1))
49+
(rt, ut) = c1.chunk(2, 1)
50+
reset_gate = self.dropout(f.sigmoid(rt))
51+
update_gate = self.dropout(f.sigmoid(ut))
52+
gated_hidden = torch.mul(reset_gate, hidden)
53+
p1 = self.Conv_ct(torch.cat((input, gated_hidden), 1))
54+
ct = f.tanh(p1)
55+
next_h = torch.mul(update_gate, hidden) + (1 - update_gate) * ct
56+
return next_h
57+
58+

HKO_EF.py

Lines changed: 283 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,283 @@
1+
#!/usr/bin/evn python
2+
# -*- coding: utf-8 -*-
3+
# Copyright (c) 2017 - zihao.chen <[email protected]>
4+
'''
5+
Author: zihao.chen
6+
Create Date: 2018-04-08
7+
Modify Date: 2018-04-08
8+
descirption: ""
9+
'''
10+
import torch
11+
from torch import nn
12+
from torch import optim
13+
from torch.autograd import Variable
14+
import numpy as np
15+
import sys
16+
import cv2
17+
import os
18+
import pickle
19+
from forecaster import Forecaster
20+
from encoder import Encoder
21+
# sys.path.append('/home/meteo/zihao.chen/model_service/utils')
22+
from data_transfrom import decode_radar_code, imgmap_tonumpy, encode_squs_code, imgmaps_tonumpy
23+
24+
input_num_seqs = 10
25+
output_num_seqs = 10
26+
hidden_size = 3
27+
input_channels_img = 1
28+
output_channels_img = 1
29+
size_image = 240
30+
max_epoch = 12
31+
cuda_flag = False
32+
kernel_size = 3
33+
batch_size = 16
34+
35+
36+
def train_by_stype(model_e, model_f, loss_e, loss_f, optimizer_e, optimizer_f, x_val, y_val):
37+
model_e.init_h0()
38+
for time in xrange(model_e.num_seqs):
39+
h_next_e = model_e(x_val[time])
40+
41+
all_pre_data = []
42+
# print type(model_e)
43+
# print type(model_f)
44+
model_f.set_h0(model_e)
45+
46+
for time in xrange(model_e.num_seqs):
47+
pre_data, h_next = model_f(None)
48+
# print h_next.size()
49+
all_pre_data.append(pre_data)
50+
51+
# fx = model_f.forward(x_val)
52+
output_f = 0
53+
# print all_pre_data[0].requires_grad
54+
# print y_val[0].requires_grad
55+
optimizer_f.zero_grad()
56+
for pre_id in range(len(all_pre_data)):
57+
# print all_pre_data[pre_id].dtype()
58+
output_f += loss_f.forward(all_pre_data[pre_id], y_val[pre_id])
59+
60+
output_f.backward(retain_graph=True)
61+
optimizer_f.step()
62+
all_e_rnn_h = [model_e.rnn3_3_h, model_e.rnn3_2_h, model_e.rnn3_1_h, model_e.rnn2_3_h, model_e.rnn2_2_h,
63+
model_e.rnn2_1_h, model_e.rnn1_2_h, model_e.rnn1_1_h]
64+
65+
all_f_rnn_h = [model_f.rnn1_1_h, model_f.rnn1_2_h, model_f.rnn1_3_h, model_f.rnn2_1_h, model_f.rnn2_2_h,
66+
model_f.rnn2_3_h, model_f.rnn3_1_h, model_f.rnn3_2_h]
67+
output_e = 0
68+
optimizer_e.zero_grad()
69+
for i in range(len(all_e_rnn_h)):
70+
71+
# all_f_rnn_h[0].requires_grad = False
72+
output_e += loss_e.forward(all_e_rnn_h[i],all_f_rnn_h[i].detach())
73+
output_e.backward()
74+
optimizer_e.step()
75+
76+
# if pre_id == 1:
77+
# print 'loss 1:',output
78+
return output_f.cuda().data[0], all_pre_data
79+
80+
81+
# def train(model_e,model_f, loss, optimizer, x_val, y_val):
82+
# # x = Variable(x_val.cuda(), requires_grad=False)
83+
# # y = Variable(y_val.cuda(), requires_grad=False)
84+
# optimizer.zero_grad()
85+
# fx = model.forward(x_val)
86+
# output = 0
87+
# # t_y = fx.cpu().data.numpy().argmax(axis=1)
88+
# # acc = 1. * np.mean(t_y == y_val.numpy())
89+
# for pre_id in range(len(fx)):
90+
# output += loss.forward(fx[pre_id], y_val[pre_id]).data.cpu()
91+
# # if pre_id == 1:
92+
# # print 'loss 1:',output
93+
# output.backward()
94+
# optimizer.step()
95+
#
96+
# return output.cuda().data[0], fx
97+
98+
99+
def verify(model_e, model_f, loss, x_val, y_val):
100+
model_e.init_h0()
101+
for time in xrange(model_e.num_seqs):
102+
h_next = model_e(x_val[time])
103+
104+
fx = []
105+
106+
model_f.set_h0(model_e)
107+
108+
for time in xrange(model_e.num_seqs):
109+
pre_data, h_next = model_f(None)
110+
# print h_next.size()
111+
fx.append(pre_data)
112+
113+
output = 0
114+
for pre_id in range(len(fx)):
115+
output += loss.forward(fx[pre_id], y_val[pre_id])
116+
return output.cuda().data[0]
117+
118+
119+
def load_data(code_list):
120+
test_arr = None
121+
train_arr = None
122+
train_imgs_maps = {}
123+
test_imgs_maps = {}
124+
for code in code_list:
125+
file_f = open('data_%s.pkl' % code, 'rb')
126+
map_l = pickle.load(file_f)
127+
file_f.close()
128+
if test_arr is None:
129+
test_arr = map_l['test_arr']
130+
train_arr = map_l['train_arr']
131+
else:
132+
test_arr = np.concatenate((test_arr, map_l['test_arr']), axis=0)
133+
train_arr = np.concatenate((train_arr, map_l['train_arr']), axis=0)
134+
train_imgs_maps[code] = map_l['train_imgs_map']
135+
test_imgs_maps[code] = map_l['test_imgs_map']
136+
137+
return train_arr, test_arr, train_imgs_maps, test_imgs_maps
138+
139+
140+
def adjust_learning_rate(optimizer, epoch):
141+
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
142+
lr = 0.001
143+
lr = lr * (0.3 ** (epoch // 4))
144+
for param_group in optimizer.param_groups:
145+
param_group['lr'] = lr
146+
147+
148+
def touch_dir(path):
149+
result = False
150+
try:
151+
path = path.strip().rstrip("\\")
152+
if not os.path.exists(path):
153+
os.makedirs(path)
154+
result = True
155+
else:
156+
result = True
157+
except:
158+
result = False
159+
return result
160+
161+
162+
def test(input_channels_img, output_channels_img, size_image, max_epoch, model_e, model_f, cuda_test):
163+
# input_image = np.ones((input_num_seqs,batch_size,input_channels_img,size_image,size_image))
164+
#
165+
# for i in range(input_num_seqs):
166+
# input_image[i,...] = i*1+1
167+
# # input_image = input_image *10
168+
# input_image = torch.from_numpy(input_image).float()
169+
# input_gru = Variable(input_image.cuda())
170+
#
171+
# target_image = np.ones((output_num_seqs,batch_size,output_channels_img,size_image,size_image))
172+
# for i in range(output_num_seqs):
173+
# target_image[i,...] = i*1+1*(input_num_seqs)+1
174+
# print target_image[i,0,0,0:3,0:3]
175+
# # target_image = target_image *10
176+
# target_image = torch.from_numpy(target_image).float()
177+
# target_gru = Variable(target_image.cuda())
178+
params = model_e.state_dict()
179+
print params.keys()
180+
print params['conv1_act.0.weight']
181+
criterion_e = nn.MSELoss()
182+
criterion_e = criterion_e.cuda()
183+
optimizer_e = optim.SGD(model_e.parameters(), lr=(0.001), momentum=0.9, weight_decay=0.005)
184+
185+
criterion_f = nn.MSELoss()
186+
criterion_f = criterion_f.cuda()
187+
optimizer_f = optim.SGD(model_f.parameters(), lr=(0.001), momentum=0.9, weight_decay=0.005)
188+
189+
for i in range(max_epoch):
190+
adjust_learning_rate(optimizer_e, i)
191+
adjust_learning_rate(optimizer_f, i)
192+
print 'epoch :', i
193+
print train_arr.shape
194+
nnn = range(train_arr.shape[0])
195+
np.random.shuffle(nnn)
196+
train_arr_b = train_arr[nnn]
197+
batch_num = train_arr_b.shape[0] // batch_size
198+
print batch_num
199+
for j in range(batch_num):
200+
batch_img = imgmaps_tonumpy(train_arr_b[j * batch_size:(j + 1) * batch_size, ...], train_imgs_maps)
201+
input_image = batch_img[:10, ...] / 255.
202+
target_image = batch_img[10:, ...] / 255.
203+
input_image = torch.from_numpy(input_image).float()
204+
input_gru = Variable(input_image.cuda())
205+
target_image = torch.from_numpy(target_image).float()
206+
target_gru = Variable(target_image.cuda())
207+
208+
error, pre_list = train_by_stype(model_e, model_f, criterion_e, criterion_f, optimizer_e, optimizer_f,
209+
input_gru, target_gru)
210+
print j, ' : ', error
211+
# print model.encoder.conv1_act
212+
params = model_e.state_dict()
213+
print params.keys()
214+
print params['conv1_act.0.weight']
215+
batch_num = test_arr.shape[0] // batch_size
216+
for j in range(batch_num):
217+
batch_img = imgmaps_tonumpy(test_arr[j * batch_size:(j + 1) * batch_size, ...], test_imgs_maps)
218+
input_image = batch_img[:10, ...] / 255.
219+
target_image = batch_img[10:, ...] / 255.
220+
input_image = torch.from_numpy(input_image).float()
221+
input_gru = Variable(input_image.cuda())
222+
target_image = torch.from_numpy(target_image).float()
223+
target_gru = Variable(target_image.cuda())
224+
225+
error = verify(model_e,model_f, criterion_f, input_gru, target_gru)
226+
print j, ' : ', error
227+
228+
for i in range(test_arr.shape[0]):
229+
temp_path = test_arr[i, 0, 0]
230+
start_i = temp_path.find('201')
231+
time_str = temp_path[start_i:start_i + 12]
232+
print time_str
233+
start_i = temp_path.find('AZ')
234+
radar_code = temp_path[start_i:start_i + 6]
235+
save_path = '/home/meteo/zihao.chen/model_service/imgs/%s/%s/' % (radar_code, time_str)
236+
touch_dir(save_path)
237+
temp_arr = test_arr[i]
238+
temp_arr = temp_arr[np.newaxis, ...]
239+
batch_img = imgmaps_tonumpy(temp_arr, test_imgs_maps)
240+
input_image = batch_img[:10, ...]
241+
target_image = batch_img[10:, ...]
242+
input_image_t = torch.from_numpy(input_image / 255.).float()
243+
input_gru = Variable(input_image_t.cuda())
244+
# fx = model.forward(input_gru)
245+
model_e.init_h0()
246+
for time in xrange(model_e.num_seqs):
247+
h_next = model_e(input_gru[time])
248+
249+
fx = []
250+
251+
model_f.set_h0(model_e)
252+
253+
for time in xrange(model_e.num_seqs):
254+
pre_data, h_next = model_f(None)
255+
# print h_next.size()
256+
fx.append(pre_data)
257+
258+
for pre_id in range(len(fx)):
259+
temp_xx = fx[pre_id].cpu().data.numpy()
260+
tmp_img = temp_xx[0, 0, ...]
261+
tmp_img = tmp_img * 255.
262+
true_img = target_image[pre_id, 0, 0, ...]
263+
encode_img = input_image[pre_id, 0, 0, ...]
264+
cv2.imwrite(os.path.join(save_path, 'a_%s.png' % pre_id), encode_img)
265+
cv2.imwrite(os.path.join(save_path, 'c_%s.png' % pre_id), tmp_img)
266+
cv2.imwrite(os.path.join(save_path, 'b_%s.png' % pre_id), true_img)
267+
268+
# for pre_data in pre_list:
269+
# temp = pre_data.cpu().data.numpy()
270+
# print temp.mean()
271+
272+
273+
train_arr, test_arr, train_imgs_maps, test_imgs_maps = load_data(['AZ9010','AZ9200'])
274+
275+
if __name__ == '__main__':
276+
# m = HKOModel(inplanes=1, input_num_seqs=input_num_seqs, output_num_seqs=output_num_seqs)
277+
m_e = Encoder(inplanes=input_channels_img, num_seqs=input_num_seqs)
278+
m_e = m_e.cuda()
279+
280+
m_f = Forecaster(num_seqs=output_num_seqs)
281+
m_f = m_f.cuda()
282+
283+
test(input_channels_img, output_channels_img, size_image, max_epoch, model_e=m_e, model_f=m_f, cuda_test=cuda_flag)

0 commit comments

Comments
 (0)