This repository has been archived by the owner on Nov 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
06-train-model-only-mel.py
185 lines (148 loc) · 5.81 KB
/
06-train-model-only-mel.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
"""Train only the part of the model, that depends on the Log Mel-Spec features"""
import pickle
import sys
import os
import numpy as np
import pandas as pd
import keras as kr
from keras import backend as ktf
from tqdm import tqdm
from utils import mel_0_1, get_random_eraser, CyclicLR, pushbullet_callback
from mel_model_funcs import TrainGenerator, ValGenerator, create_mel_model
# Load data
train_metadata = pd.read_csv('./data/train.csv')
fnames_train_all = train_metadata.fname.values
mel_train_all_data = {
fname: mel_0_1(np.load('./data/mel_spec_train/' + fname + '.npy'))
for fname in tqdm(train_metadata.fname.values)
}
# this fold
with open('./data/folds.pkl', 'rb') as f:
folds = pickle.load(f)
this_fold = int(sys.argv[1])
print('this fold:', this_fold)
# label text -> label id
y_train_all = train_metadata.label.tolist()
labels = list(sorted(list(set(y_train_all))))
num_classes = len(labels)
label2int = {l: i for i, l in enumerate(labels)}
int2label = {i: l for i, l in enumerate(labels)}
y_train_all_idx = [label2int[l] for l in y_train_all]
train_metadata['label_idx'] = pd.Series(y_train_all_idx,
index=train_metadata.index)
# train and valid sets
train_metadata.set_index('fname', inplace=True)
fnames_train, fnames_valid = folds[this_fold]
y_train = kr.utils.to_categorical(
train_metadata.label_idx.loc[fnames_train].values,
num_classes)
y_valid = kr.utils.to_categorical(
train_metadata.label_idx.loc[fnames_valid].values,
num_classes)
print(fnames_train.shape)
print(fnames_valid.shape)
print(y_train.shape)
print(y_valid.shape)
# Instantiate train and val generators
batch_size = 64
datagen = kr.preprocessing.image.ImageDataGenerator(
rotation_range=0,
width_shift_range=0.6,
height_shift_range=0,
horizontal_flip=True,
preprocessing_function=get_random_eraser(v_l=0, v_h=1)
)
train_generator = TrainGenerator(
fnames_train,
y_one_hot=y_train,
batch_size=batch_size,
alpha=1,
datagen=datagen,
mel_data=mel_train_all_data)
val_generator = ValGenerator(
fnames_valid,
y_one_hot=y_valid,
batch_size=batch_size,
mel_data=mel_train_all_data)
# Define model
model = create_mel_model()
model.summary()
this_fold_dir = 'model_outs/mel_model/fold' + str(this_fold)
os.makedirs(this_fold_dir, exist_ok=True)
print('Train with CyclicLR...')
callbacks = [
kr.callbacks.ModelCheckpoint(this_fold_dir + '/best_model_1.h5',
verbose=1,
monitor='val_loss',
save_best_only=True,
save_weights_only=True),
CyclicLR(base_lr=0.0001,
max_lr=0.001,
step_size=len(train_generator),
mode='triangular'),
kr.callbacks.CSVLogger(this_fold_dir + '/train.log', append=True)
]
if 'PB_API_KEY' in os.environ:
callbacks.append(pushbullet_callback(this_fold))
model.fit_generator(train_generator,
steps_per_epoch=len(train_generator),
epochs=100,
verbose=2,
validation_data=val_generator,
validation_steps=len(val_generator),
max_queue_size=1,
workers=1,
use_multiprocessing=False,
callbacks=callbacks)
print('Fine tuning 1 with ReduceLROnPlateau...')
model.load_weights(this_fold_dir + '/best_model_1.h5')
ktf.set_value(model.optimizer.lr, 0.00001)
callbacks = [
kr.callbacks.ModelCheckpoint(this_fold_dir + '/best_model_2.h5',
verbose=1,
monitor='val_loss',
save_best_only=True,
save_weights_only=True),
kr.callbacks.EarlyStopping(monitor="val_loss", mode="min", verbose=1, patience=10),
kr.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3,
verbose=1, min_delta=0.0001, mode='min'),
kr.callbacks.CSVLogger(this_fold_dir + '/train.log', append=True),
]
if 'PB_API_KEY' in os.environ:
callbacks.append(pushbullet_callback(this_fold))
model.fit_generator(train_generator,
steps_per_epoch=len(train_generator),
epochs=100,
verbose=2,
validation_data=val_generator,
validation_steps=len(val_generator),
max_queue_size=1,
workers=1,
use_multiprocessing=False,
callbacks=callbacks)
print('Fine tuning 2 with ReduceLROnPlateau...')
model.load_weights(this_fold_dir + '/best_model_2.h5')
ktf.set_value(model.optimizer.lr, 0.0001)
callbacks = [
kr.callbacks.ModelCheckpoint(this_fold_dir + '/best_model_3.h5',
verbose=1,
monitor='val_loss',
save_best_only=True,
save_weights_only=True),
kr.callbacks.EarlyStopping(monitor="val_loss", mode="min", verbose=1, patience=10),
kr.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3,
verbose=1, min_delta=0.0001, mode='min'),
kr.callbacks.CSVLogger(this_fold_dir + '/train.log', append=True),
]
if 'PB_API_KEY' in os.environ:
callbacks.append(pushbullet_callback(this_fold))
model.fit_generator(train_generator,
steps_per_epoch=len(train_generator),
epochs=100,
verbose=2,
validation_data=val_generator,
validation_steps=len(val_generator),
max_queue_size=1,
workers=1,
use_multiprocessing=False,
callbacks=callbacks)