-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
212 lines (185 loc) · 8.04 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
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
from core.base_classes import BaseModel
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Flatten, Input, InputLayer, Conv2D, AveragePooling2D, \
Reshape, \
Dot, Add, Dropout, MaxPool2D, BatchNormalization
from argparse import ArgumentParser
from keras import regularizers
from keras import initializers
from kapre.utils import Normalization2D
from keras.applications import VGG16 as keras_vgg
def add_regularization(layers, params):
if params and "regularizer" in params and params['regularizer'] is not None:
obj = getattr(regularizers, params["regularizer"])
if "regularizer.l" in params and params["regularizer.l"] is not None:
reg = obj(l=params["regularizer.l"])
else:
reg = obj()
for l in layers:
if isinstance(l, Dense) or isinstance(l, Conv2D):
l.kernel_regularizer = reg
class MLP(BaseModel):
def build(self, input_shape) -> Model:
print('###########', self.params)
m = self.create_model(**{'input_shape': input_shape, **vars(self.params)})
return m
def create_model(self, input_shape, nb_classes, n_neurons, act='sigmoid',
use_softmax=None, **kwargs):
n_neurons = list(map(int, n_neurons.split(";")))
model = Sequential()
layers = []
is_first = True
if len(input_shape) > 1:
layers = layers + [Flatten(input_shape=input_shape)]
is_first = False
# add fully connected layers
if is_first:
layers += [Dense(n_neurons[0], activation=act, input_shape=input_shape)]
else:
layers += [Dense(n_neurons[0], activation=act)]
for i in n_neurons[1:]:
layers += [
Dense(i, activation=act)
]
# add output layer
if nb_classes == 2 and not use_softmax:
layers += [
Dense(1, activation='sigmoid')
]
else:
layers += [
Dense(nb_classes, activation='softmax' if use_softmax else 'sigmoid')
]
add_regularization(layers, kwargs)
for l in layers:
model.add(l)
return model
def get_parser(self) -> ArgumentParser:
parser = ArgumentParser()
parser.add_argument('--nb_classes', required=True, type=int)
parser.add_argument('--n_neurons', type=str, default="100")
parser.add_argument('--regularizer', type=str)
parser.add_argument('--regularizer.l', type=float)
parser.add_argument('--use_softmax', action='store_true')
return parser
class LeNet(BaseModel):
def build(self, input_shape) -> Model:
print('###########', self.params)
m = self.create_model(**{'input_shape': input_shape, **vars(self.params)})
return m
def create_block(self, nb_filters, padding, pool=None, act='relu', input_shape=None):
layers = [AveragePooling2D(pool_size=(2, 2))]
if input_shape is not None:
return [Conv2D(filters=nb_filters, kernel_size=(5, 5), activation=act,
input_shape=input_shape, padding=padding)] + layers
else:
return [Conv2D(filters=nb_filters, kernel_size=(5, 5), activation=act, padding=padding)] + layers
def create_model(self, input_shape, nb_classes, n_filters, padding, n_neurons, act='relu',
use_softmax=None, **kwargs):
n_filters = list(map(int, n_filters.split(";")))
n_neurons = list(map(int, n_neurons.split(";")))
model = Sequential()
layers = []
# build blocks
for i, n_filter in enumerate(n_filters):
in_sh = input_shape if i == 0 else None
layers += self.create_block(nb_filters=n_filter,
act=act,
input_shape=in_sh, padding=padding)
if len(n_neurons) > 1:
layers = layers + [Conv2D(filters=n_neurons[0], kernel_size=(5, 5), activation='relu', padding=padding)]
n_neurons = n_neurons[1:]
layers = layers + [Flatten()]
# add fully connected layers
for i in n_neurons:
layers += [
Dense(i, activation=act)
]
# add output layer
if nb_classes == 2 and not use_softmax:
layers += [
Dense(1, activation='sigmoid')
]
else:
layers += [
Dense(nb_classes, activation='softmax' if use_softmax else 'sigmoid')
]
add_regularization(layers, kwargs)
for l in layers:
model.add(l)
return model
def get_parser(self) -> ArgumentParser:
parser = ArgumentParser()
parser.add_argument('--nb_classes', required=True, type=int)
parser.add_argument('--regularizer', type=str)
parser.add_argument('--regularizer.l', type=float)
parser.add_argument('--padding', type=str, default='valid')
parser.add_argument('--n_filters', type=str, default="6;16")
parser.add_argument('--n_neurons', type=str, default="120;84")
parser.add_argument('--use_softmax', action='store_true')
return parser
class ESCConvNet(BaseModel):
def build(self, input_shape) -> Model:
print('###########', self.params)
m = self.create_model(**{'input_shape': input_shape, **vars(self.params)})
return m
def create_model(self, input_shape, nb_classes, n_filters, dropout, **kwargs):
model = Sequential()
dropout = list(map(float, dropout.split(",")))
if len(dropout) == 1:
dropout = dropout * 4
if len(dropout) != 4:
raise Exception("Unexpected length of dropouts:{0}".format(len(dropout)))
layers = [
Normalization2D(str_axis='batch', input_shape=input_shape),
Conv2D(filters=n_filters, kernel_size=(9, 9), activation='relu'),
MaxPool2D((2, 2), strides=(2, 2)),
Dropout(dropout[0]),
Conv2D(filters=n_filters, kernel_size=(6, 6), activation='relu'),
Dropout(dropout[1]),
Conv2D(filters=n_filters, kernel_size=(3, 3), activation='relu'),
MaxPool2D((1, 2), strides=(1, 2)),
Dropout(dropout[1]),
Conv2D(filters=n_filters, kernel_size=(3, 3), activation='relu'),
Dropout(dropout[1]),
Flatten(),
Dense(1000, activation='relu'),
Dropout(dropout[2]),
Dense(1000, activation='relu'),
Dropout(dropout[3]),
Dense(nb_classes, activation='sigmoid')
]
add_regularization(layers, kwargs)
for l in layers:
model.add(l)
return model
def get_parser(self) -> ArgumentParser:
parser = ArgumentParser()
parser.add_argument('--nb_classes', required=True, type=int)
parser.add_argument('--regularizer', type=str)
parser.add_argument('--regularizer.l', type=float)
parser.add_argument('--n_filters', type=int, default=100)
parser.add_argument('--dropout', type=str)
return parser
class VGG16(BaseModel):
def build(self, input_shape) -> Model:
print('###########', self.params)
m = self.create_model(**{'input_shape': input_shape, **vars(self.params)})
return m
def create_model(self, input_shape, nb_classes, **kwargs):
model = Sequential()
layers = [keras_vgg(include_top=False, weights=None, input_shape=input_shape),
Flatten(),
Dense(4096, activation='relu'),
Dense(4096, activation='relu'),
Dense(nb_classes, activation='sigmoid')]
add_regularization(layers, kwargs)
for l in layers:
model.add(l)
return model
def get_parser(self) -> ArgumentParser:
parser = ArgumentParser()
parser.add_argument('--nb_classes', required=True, type=int)
parser.add_argument('--regularizer', type=str)
parser.add_argument('--regularizer.l', type=float)
return parser