-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.py
206 lines (185 loc) · 8.35 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
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
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from keras import backend as K
from keras.models import Sequential, Model
from keras.layers import (
Input,
Activation,
Dropout,
Reshape,
Permute,
Dense,
UpSampling1D,
Flatten,
Concatenate
)
from keras.optimizers import SGD, RMSprop
from keras.layers.convolutional import (
Convolution1D)
from keras.layers.pooling import (
MaxPooling1D,
AveragePooling1D
)
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2
from keras.models import Sequential, load_model
weight_decay = 1e-5
def _conv_bn_relu(nb_filter, kernel_size):
def f(input):
conv_a = Convolution1D(nb_filter, kernel_size, activation='relu', padding='same')(input)
norm_a = BatchNormalization()(conv_a)
act_a = Activation(activation = 'relu')(norm_a)
return act_a
return f
def _conv_bn_relu_x2(nb_filter, kernel_size):
def f(input):
conv_a = Convolution1D(nb_filter, kernel_size,
activation='relu', padding='same')(input)
norm_a = BatchNormalization()(conv_a)
act_a = Activation(activation = 'relu')(norm_a)
conv_b = Convolution1D(nb_filter, kernel_size,
activation='relu', padding='same')(act_a)
norm_b = BatchNormalization()(conv_b)
act_b = Activation(activation = 'relu')(norm_b)
return act_b
return f
def FCRN_A_base(input):
block1 = _conv_bn_relu(32,3)(input)
pool1 = MaxPooling1D(pool_size=(2))(block1)
# =========================================================================
block2 = _conv_bn_relu(64,3)(pool1)
pool2 = MaxPooling1D(pool_size=(2))(block2)
# =========================================================================
block3 = _conv_bn_relu(128,3)(pool2)
pool3 = MaxPooling1D(pool_size=(2))(block3)
# =========================================================================
block4 = _conv_bn_relu(512,3)(pool3)
# =========================================================================
up5 = UpSampling1D(size=(2))(block4)
block5 = _conv_bn_relu(128,3)(up5)
# =========================================================================
up6 = UpSampling1D(size=(2))(block5)
block6 = _conv_bn_relu(64,3)(up6)
# =========================================================================
up7 = UpSampling1D(size=(2))(block6)
block7 = _conv_bn_relu(32,3)(up7)
return block7
def FCRN_A_base_v2(input):
block1 = _conv_bn_relu_x2(32,3)(input)
pool1 = MaxPooling1D(pool_size=(2))(block1)
# =========================================================================
block2 = _conv_bn_relu_x2(64,3)(pool1)
pool2 = MaxPooling1D(pool_size=(2))(block2)
# =========================================================================
block3 = _conv_bn_relu_x2(128,3)(pool2)
pool3 = MaxPooling1D(pool_size=(2))(block3)
# =========================================================================
block4 = _conv_bn_relu(512,3)(pool3)
# =========================================================================
up5 = UpSampling1D(size=(2))(block4)
block5 = _conv_bn_relu_x2(128,3)(up5)
# =========================================================================
up6 = UpSampling1D(size=(2))(block5)
block6 = _conv_bn_relu_x2(64,3)(up6)
# =========================================================================
up7 = UpSampling1D(size=(2))(block6)
block7 = _conv_bn_relu_x2(32,3)(up7)
return block7
def U_net_base(input, nb_filter = 64):
block1 = _conv_bn_relu_x2(nb_filter,3)(input)
pool1 = MaxPooling1D(pool_size=(2))(block1)
# =========================================================================
block2 = _conv_bn_relu_x2(nb_filter,3)(pool1)
pool2 = MaxPooling1D(pool_size=(2))(block2)
# =========================================================================
block3 = _conv_bn_relu_x2(nb_filter,3)(pool2)
pool3 = MaxPooling1D(pool_size=(2))(block3)
# =========================================================================
block4 = _conv_bn_relu_x2(nb_filter,3)(pool3)
up4 = Concatenate(axis=-1)([UpSampling1D(size=(2))(block4), block3])
# =========================================================================
block5 = _conv_bn_relu_x2(nb_filter,3)(up4)
up5 = Concatenate(axis=-1)([UpSampling1D(size=(2))(block5), block2])
# =========================================================================
block6 = _conv_bn_relu_x2(nb_filter,3)(up5)
up6 = Concatenate(axis=-1)([UpSampling1D(size=(2))(block6), block1])
# =========================================================================
block7 = _conv_bn_relu(nb_filter,3)(up6)
return block7
def buildModel_FCRN_A (input_dim):
input_ = Input (shape = (input_dim))
# =========================================================================
act_ = FCRN_A_base (input_)
# =========================================================================
density_pred = Convolution1D(1, 1, activation='linear',\
name='pred')(act_)
# =========================================================================
model = Model (inputs = input_, outputs = density_pred)
opt = SGD(lr = 1e-2, momentum = 0.9, nesterov = True)
model.compile(optimizer = opt, loss = 'mse')
return model
def buildModel_FCRN_A_v2 (input_dim):
input_ = Input (shape = (input_dim))
# =========================================================================
act_ = FCRN_A_base_v2 (input_)
# =========================================================================
density_pred = Convolution1D(1, 1, activation='linear',\
name='pred')(act_)
# =========================================================================
model = Model (inputs = input_, outputs = density_pred)
opt = SGD(lr = 1e-2, momentum = 0.9, nesterov = True)
model.compile(optimizer = opt, loss = 'mse')
return model
def buildModel_U_net (input_dim):
input_ = Input (shape = (input_dim))
# =========================================================================
act_ = U_net_base (input_, nb_filter = 64 )
# =========================================================================
density_pred = Convolution1D(1, 1, activation='linear',\
name='pred')(act_)
# =========================================================================
model = Model (inputs = input_, outputs = density_pred)
opt = RMSprop(1e-3)
model.compile(optimizer = opt, loss = 'mse')
return model
def train(x, y, length, channels, batch_size=64, lr=3e-4, epochs=500, filepath="model.h5", model_type="FRCN_A_v2"):
import tensorflow as tf
from tensorflow.keras import layers, regularizers
from keras.constraints import max_norm, unit_norm
import keras.callbacks
from keras.callbacks import TensorBoard
from keras.callbacks import ModelCheckpoint
import os
# define the checkpoint
# define the checkpoint
if(os.path.exists(filepath)):
print(f"{filepath} Checkpoint Loaded")
model = load_model(filepath)
else:
print("No model checkpoint, starting from scratch...")
if (model_type == "FRCN_A"):
print("Loading Model FRCN-A")
model = buildModel_FCRN_A((length, channels))
else:
print("Loading Model FRCN-A-v2")
model = buildModel_FCRN_A_v2((length, channels))
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
opt = tf.keras.optimizers.Adam(lr=lr)
model.compile(loss='mse',optimizer=opt,metrics='accuracy')
print(model.summary())
history = model.fit(x, y, batch_size=batch_size,epochs=epochs,validation_split=0.1,verbose=True, callbacks=callbacks_list)
#model.save("my_model")
import matplotlib.pyplot as plt
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.xlabel('iteration')
plt.ylabel('loss')
plt.title('Loss over time')
plt.legend(['train','val'])
plt.savefig('loss.png', bbox_inches='tight')
return model
def evaluate(model_path, x):
model = load_model(model_path)
return model.predict(x)