-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathkeras_model.py
226 lines (194 loc) · 8.88 KB
/
keras_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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.lite.experimental.microfrontend.python.ops import audio_microfrontend_op as frontend_op
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Activation, Flatten, BatchNormalization, Dropout, Reshape
from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, AveragePooling2D, GlobalAveragePooling2D
from tensorflow.keras.regularizers import l2
def prepare_model_settings(label_count, args):
"""Calculates common settings needed for all models.
Args:
label_count: How many classes are to be recognized.
sample_rate: Number of audio samples per second.
clip_duration_ms: Length of each audio clip to be analyzed.
window_size_ms: Duration of frequency analysis window.
window_stride_ms: How far to move in time between frequency windows.
dct_coefficient_count: Number of frequency bins to use for analysis.
Returns:
Dictionary containing common settings.
"""
desired_samples = int(args.sample_rate * args.clip_duration_ms / 1000)
if args.feature_type == 'td_samples':
window_size_samples = 1
spectrogram_length = desired_samples
dct_coefficient_count = 1
window_stride_samples = 1
fingerprint_size = desired_samples
else:
dct_coefficient_count = args.dct_coefficient_count
window_size_samples = int(args.sample_rate * args.window_size_ms / 1000)
window_stride_samples = int(args.sample_rate * args.window_stride_ms / 1000)
length_minus_window = (desired_samples - window_size_samples)
if length_minus_window < 0:
spectrogram_length = 0
else:
spectrogram_length = 1 + int(length_minus_window / window_stride_samples)
fingerprint_size = args.dct_coefficient_count * spectrogram_length
return {
'desired_samples': desired_samples,
'window_size_samples': window_size_samples,
'window_stride_samples': window_stride_samples,
'feature_type': args.feature_type,
'spectrogram_length': spectrogram_length,
'dct_coefficient_count': dct_coefficient_count,
'fingerprint_size': fingerprint_size,
'label_count': label_count,
'sample_rate': args.sample_rate,
'background_frequency': 0.8, # args.background_frequency
'background_volume_range_': 0.1
}
def get_model(args):
model_name = args.model_architecture
label_count=12
model_settings = prepare_model_settings(label_count, args)
if model_name=="fc4":
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(model_settings['spectrogram_length'],
model_settings['dct_coefficient_count'])),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(model_settings['label_count'], activation="softmax")
])
elif model_name == 'ds_cnn':
print("DS CNN model invoked")
input_shape = [model_settings['spectrogram_length'], model_settings['dct_coefficient_count'],1]
filters = 64
weight_decay = 1e-4
regularizer = l2(weight_decay)
final_pool_size = (int(input_shape[0]/2), int(input_shape[1]/2))
# Model layers
# Input pure conv2d
inputs = Input(shape=input_shape)
x = Conv2D(filters, (10,4), strides=(2,2), padding='same', kernel_regularizer=regularizer)(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Dropout(rate=0.2)(x)
# First layer of separable depthwise conv2d
# Separable consists of depthwise conv2d followed by conv2d with 1x1 kernels
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Second layer of separable depthwise conv2d
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Third layer of separable depthwise conv2d
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Fourth layer of separable depthwise conv2d
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Reduce size and apply final softmax
x = Dropout(rate=0.4)(x)
x = AveragePooling2D(pool_size=final_pool_size)(x)
x = Flatten()(x)
outputs = Dense(model_settings['label_count'], activation='softmax')(x)
# Instantiate model.
model = Model(inputs=inputs, outputs=outputs)
elif model_name == 'td_cnn':
print("TD CNN model invoked")
input_shape = [model_settings['spectrogram_length'], model_settings['dct_coefficient_count'],1]
print(f"Input shape = {input_shape}")
filters = 64
weight_decay = 1e-4
regularizer = l2(weight_decay)
# Model layers
# Input time-domain conv
inputs = Input(shape=input_shape)
x = Conv2D(filters, (512,1), strides=(384, 1),
padding='valid', kernel_regularizer=regularizer)(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Dropout(rate=0.2)(x)
x = Reshape((41,64,1))(x)
# True conv
x = Conv2D(filters, (10,4), strides=(2,2), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Dropout(rate=0.2)(x)
# First layer of separable depthwise conv2d
# Separable consists of depthwise conv2d followed by conv2d with 1x1 kernels
# First layer of separable depthwise conv2d
# Separable consists of depthwise conv2d followed by conv2d with 1x1 kernels
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Second layer of separable depthwise conv2d
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Third layer of separable depthwise conv2d
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Fourth layer of separable depthwise conv2d
x = DepthwiseConv2D(depth_multiplier=1, kernel_size=(3,3), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, (1,1), padding='same', kernel_regularizer=regularizer)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Reduce size and apply final softmax
x = Dropout(rate=0.4)(x)
# x = AveragePooling2D(pool_size=(25,5))(x)
x = GlobalAveragePooling2D()(x)
x = Flatten()(x)
outputs = Dense(model_settings['label_count'], activation='softmax')(x)
# Instantiate model.
model = Model(inputs=inputs, outputs=outputs)
else:
raise ValueError("Model name {:} not supported".format(model_name))
model.compile(
#optimizer=keras.optimizers.RMSprop(learning_rate=args.learning_rate), # Optimizer
optimizer=keras.optimizers.Adam(learning_rate=args.learning_rate), # Optimizer
# Loss function to minimize
loss=keras.losses.SparseCategoricalCrossentropy(),
# List of metrics to monitor
metrics=[keras.metrics.SparseCategoricalAccuracy()],
)
return model