-
Notifications
You must be signed in to change notification settings - Fork 0
/
model_build_and_training.py
199 lines (163 loc) · 6.13 KB
/
model_build_and_training.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
import argparse
import logging
import logging.config
import os
import tensorflow as tf
from keras import backend as K
from keras import optimizers, regularizers
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from keras.layers import Activation, Conv2D, Dense, Dropout, Flatten
from keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator
# Disable PIL.PngImagePlugin DEBUG logs
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": True,
})
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SRKWs:
@staticmethod
def build(img_width, img_height):
"""Build Convolution Neural Network model
Create a Convolution-Neural-Network model for detection of calls
and no calls of the Southern Resident Killer Whales.
Args:
img_width: The width of the image
img_height: The height of the image
Returns:
model
"""
if K.image_data_format() == "channels_first":
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model = Sequential()
model.add(Conv2D(64, (5, 5),
kernel_regularizer=regularizers.l2(0.001),
padding="same",
strides=3,
input_shape=input_shape))
model.add(Activation("relu"))
model.add(Dropout(0.5))
model.add(Conv2D(64, (5, 5),
kernel_regularizer=regularizers.l2(0.001),
strides=3,
padding="same"))
model.add(Activation("relu"))
model.add(Conv2D(128, (5, 5),
kernel_regularizer=regularizers.l2(0.001),
strides=3,
padding="same"))
model.add(Activation("relu"))
model.add(Dropout(0.6))
model.add(Conv2D(128, (5, 5),
kernel_regularizer=regularizers.l2(0.001),
strides=3,
padding="same"))
model.add(Activation("relu"))
model.add(Dropout(0.6))
model.add(Flatten())
model.add(Dense(256))
model.add(Activation("relu"))
model.add(Dense(1))
model.add(Activation("sigmoid"))
model.compile(
loss="binary_crossentropy",
optimizer=optimizers.Adam(lr=3e-5),
metrics=["accuracy"])
model.summary()
return model
def train(
model, img_width, img_height, train_data_path,
validation_data_path, no_of_epochs):
"""Train the Convolution Neural Network model
Trains the model on the training dataset which consists of calls and
no calls.The trained model is also saved with the name srkw_cnn.h5
Args:
model: The CNN model that we created
img_width: The width of the image
img_height: The height of the image
train_data_path: The path to the training folder
validation_data_path: The path to the validation folder
no_of_epochs: The number of epochs for which we want to train
our model
Returns:
None
"""
nb_train_samples = sum(len(files)
for _, _, files in os.walk(train_data_path))
nb_validation_samples = sum(len(files)
for _, _, files in os.walk(
validation_data_path))
epochs = no_of_epochs
batch_size = 32
checkpoint = ModelCheckpoint(
filepath="checkpoint_srkw-{epoch:02d}-{val_loss:.2f}.h5",
monitor="val_loss", verbose=0, save_best_only=True)
reduce_lr = ReduceLROnPlateau(monitor="val_loss", factor=0.1,
patience=100, min_lr=1e-8)
train_datagen = ImageDataGenerator(rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2)
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_batchsize = 32
val_batchsize = 22
train_generator = train_datagen.flow_from_directory(
train_data_path,
target_size=(img_width, img_height),
batch_size=train_batchsize,
class_mode="binary",
shuffle=True)
validation_generator = test_datagen.flow_from_directory(
validation_data_path,
target_size=(img_width, img_height),
batch_size=val_batchsize,
class_mode="binary",
shuffle=False)
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size,
callbacks=[checkpoint, reduce_lr])
model.save("srkw_cnn.h5")
logger.info("Detection Model saved")
def main(args):
dataset_path = args.classpath
no_of_epochs = args.noofepochs
train_data_path = os.path.join(dataset_path, "train_srkw/")
validation_data_path = os.path.join(dataset_path, "val_srkw/")
img_width, img_height = 288, 432
logger.info("Starting compiling of SRKWs ... ")
model = SRKWs.build(img_width=img_width, img_height=img_height)
model.compile(loss="binary_crossentropy",
optimizer=optimizers.Adam(lr=3e-5),
metrics=["accuracy"])
logger.info("Starting Training ... ")
train(model=model,
img_width=img_width,
img_height=img_height,
train_data_path=train_data_path,
validation_data_path=validation_data_path,
no_of_epochs=no_of_epochs)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Train CNN model for detection of srkws calls in spectrograms")
parser.add_argument(
"-c",
"--classpath",
type=str,
help="directory with pos and neg samples in two respective folders",
required=True)
parser.add_argument(
"-epochs",
"--noofepochs",
type=int,
help="Enter the number of epochs for which you want to train",
default=256
)
args = parser.parse_args()
main(args)