forked from y-kawagu/dcase2020_task2_baseline
-
Notifications
You must be signed in to change notification settings - Fork 1
/
00_train.py
213 lines (175 loc) · 7.82 KB
/
00_train.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
"""
@file 00_train.py
@brief Script for training
@author Toshiki Nakamura, Yuki Nikaido, and Yohei Kawaguchi (Hitachi Ltd.)
Copyright (C) 2020 Hitachi, Ltd. All right reserved.
"""
########################################################################
# import default python-library
########################################################################
import os
import glob
import sys
########################################################################
########################################################################
# import additional python-library
########################################################################
import numpy
# from import
from tqdm import tqdm
# original lib
import common as com
import keras_model
########################################################################
########################################################################
# load parameter.yaml
########################################################################
param = com.yaml_load()
########################################################################
########################################################################
# visualizer
########################################################################
class visualizer(object):
def __init__(self):
import matplotlib.pyplot as plt
self.plt = plt
self.fig = self.plt.figure(figsize=(30, 10))
self.plt.subplots_adjust(wspace=0.3, hspace=0.3)
def loss_plot(self, loss, val_loss):
"""
Plot loss curve.
loss : list [ float ]
training loss time series.
val_loss : list [ float ]
validation loss time series.
return : None
"""
ax = self.fig.add_subplot(1, 1, 1)
ax.cla()
ax.plot(loss)
ax.plot(val_loss)
ax.set_title("Model loss")
ax.set_xlabel("Epoch")
ax.set_ylabel("Loss")
ax.legend(["Train", "Validation"], loc="upper right")
def save_figure(self, name):
"""
Save figure.
name : str
save png file path.
return : None
"""
self.plt.savefig(name)
########################################################################
def list_to_vector_array(file_list,
msg="calc...",
n_mels=64,
frames=5,
n_fft=1024,
hop_length=512,
power=2.0):
"""
convert the file_list to a vector array.
file_to_vector_array() is iterated, and the output vector array is concatenated.
file_list : list [ str ]
.wav filename list of dataset
msg : str ( default = "calc..." )
description for tqdm.
this parameter will be input into "desc" param at tqdm.
return : numpy.array( numpy.array( float ) )
vector array for training (this function is not used for test.)
* dataset.shape = (number of feature vectors, dimensions of feature vectors)
"""
# calculate the number of dimensions
dims = n_mels * frames
# iterate file_to_vector_array()
for idx in tqdm(range(len(file_list)), desc=msg):
vector_array = com.file_to_vector_array(file_list[idx],
n_mels=n_mels,
frames=frames,
n_fft=n_fft,
hop_length=hop_length,
power=power)
if idx == 0:
dataset = numpy.zeros((vector_array.shape[0] * len(file_list), dims), float)
dataset[vector_array.shape[0] * idx: vector_array.shape[0] * (idx + 1), :] = vector_array
return dataset
def file_list_generator(target_dir,
dir_name="train",
ext="wav"):
"""
target_dir : str
base directory path of the dev_data or eval_data
dir_name : str (default="train")
directory name containing training data
ext : str (default="wav")
file extension of audio files
return :
train_files : list [ str ]
file list for training
"""
com.logger.info("target_dir : {}".format(target_dir))
# generate training list
training_list_path = os.path.abspath("{dir}/{dir_name}/*.{ext}".format(dir=target_dir, dir_name=dir_name, ext=ext))
files = sorted(glob.glob(training_list_path))
if len(files) == 0:
com.logger.exception("no_wav_file!!")
com.logger.info("train_file num : {num}".format(num=len(files)))
return files
########################################################################
########################################################################
# main 00_train.py
########################################################################
if __name__ == "__main__":
# check mode
# "development": mode == True
# "evaluation": mode == False
mode = com.command_line_chk()
if mode is None:
sys.exit(-1)
# make output directory
os.makedirs(param["model_directory"], exist_ok=True)
# initialize the visualizer
visualizer = visualizer()
# load base_directory list
dirs = com.select_dirs(param=param, mode=mode)
# loop of the base directory
for idx, target_dir in enumerate(dirs):
print("\n===========================")
print("[{idx}/{total}] {dirname}".format(dirname=target_dir, idx=idx+1, total=len(dirs)))
# set path
machine_type = os.path.split(target_dir)[1]
model_file_path = "{model}/model_{machine_type}.hdf5".format(model=param["model_directory"],
machine_type=machine_type)
history_img = "{model}/history_{machine_type}.png".format(model=param["model_directory"],
machine_type=machine_type)
if os.path.exists(model_file_path):
com.logger.info("model exists")
continue
# generate dataset
print("============== DATASET_GENERATOR ==============")
files = file_list_generator(target_dir)
train_data = list_to_vector_array(files,
msg="generate train_dataset",
n_mels=param["feature"]["n_mels"],
frames=param["feature"]["frames"],
n_fft=param["feature"]["n_fft"],
hop_length=param["feature"]["hop_length"],
power=param["feature"]["power"])
# train model
print("============== MODEL TRAINING ==============")
model = keras_model.get_model(param["feature"]["n_mels"] * param["feature"]["frames"])
model.summary()
model.compile(**param["fit"]["compile"])
history = model.fit(train_data,
train_data,
epochs=param["fit"]["epochs"],
batch_size=param["fit"]["batch_size"],
shuffle=param["fit"]["shuffle"],
validation_split=param["fit"]["validation_split"],
verbose=param["fit"]["verbose"])
visualizer.loss_plot(history.history["loss"], history.history["val_loss"])
visualizer.save_figure(history_img)
model.save(model_file_path)
com.logger.info("save_model -> {}".format(model_file_path))
print("============== END TRAINING ==============")