-
Notifications
You must be signed in to change notification settings - Fork 18
/
model_train.py
186 lines (140 loc) · 5.95 KB
/
model_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
import pickle
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.metrics import f1_score
from skopt.space import Real
from skopt.utils import use_named_args
from skopt import gp_minimize
from skopt.plots import plot_convergence
import matplotlib.pyplot as plt
from parameters import *
from utils import OC_Statistics
from models import create_model
from utils import getDataset, plot_history
from get_data import downloadData, getDataDict, getDataframe
def model_train():
"""
Trains model which is used as a feature extractor
:return:None
"""
# Download data
downloadData(data_path="/input/speech_commands/")
# Get data dictionary
dataDict = getDataDict(data_path="/input/speech_commands/")
# Obtain dataframe for each dataset
trainDF = getDataframe(dataDict["train"])
valDF = getDataframe(dataDict["val"])
devDF = getDataframe(dataDict["dev"])
testDF = getDataframe(dataDict["test"])
print("Dataset statistics")
print("Train files: {}".format(trainDF.shape[0]))
print("Validation files: {}".format(valDF.shape[0]))
print("Dev test files: {}".format(devDF.shape[0]))
print("Test files: {}".format(testDF.shape[0]))
# Use TF Data API for efficient data input
train_data, train_steps = getDataset(df=trainDF, batch_size=BATCH_SIZE, cache_file="train_cache", shuffle=True)
val_data, val_steps = getDataset(df=valDF, batch_size=BATCH_SIZE, cache_file="val_cache", shuffle=False)
model = create_model()
model.summary()
# Stop training if the validation accuracy doesn't improve
earlyStopping = EarlyStopping(monitor="val_loss", patience=PATIENCE, verbose=1)
# Reduce LR on validation loss plateau
reduceLR = ReduceLROnPlateau(monitor="val_loss", patience=PATIENCE, verbose=1)
# Compile the model
model.compile(
loss="sparse_categorical_crossentropy",
optimizer=Adam(learning_rate=LEARNING_RATE),
metrics=["sparse_categorical_accuracy"],
)
# Train the model
history = model.fit(
train_data.repeat(),
steps_per_epoch=train_steps,
validation_data=val_data.repeat(),
validation_steps=val_steps,
epochs=EPOCHS,
callbacks=[earlyStopping, reduceLR],
)
# Save model
print("Saving model")
model.save("../models/marvin_kws.h5")
# Save history data
print("Saving training history")
with open("../models/marvin_kws_history.pickle", "wb") as file:
pickle.dump(history.history, file, protocol=pickle.HIGHEST_PROTOCOL)
plot_history(history=history)
def marvin_kws_model():
"""
Trains an One Class SVM for hotword detection
:return: None
"""
# Download data
downloadData(data_path="/input/speech_commands/")
# Get dictionary with files and labels
dataDict = getDataDict(data_path="/input/speech_commands/")
# Obtain dataframe for each dataset
trainDF = getDataframe(dataDict["train"])
valDF = getDataframe(dataDict["val"])
# Obtain Marvin data from training data
marvin_data, _ = getDataset(
df=trainDF.loc[trainDF["category"] == "marvin", :],
batch_size=BATCH_SIZE,
cache_file="kws_marvin_cache",
shuffle=False,
)
# Obtain Marvin - Other separated data from validation data
valDF["class"] = valDF.apply(lambda row: 1 if row["category"] == "marvin" else -1, axis=1)
valDF.drop("category", axis=1)
val_true_labels = valDF["class"].tolist()
val_data, _ = getDataset(df=valDF, batch_size=BATCH_SIZE, cache_file="kws_val_cache", shuffle=False)
# Load model and create feature extractor
model = load_model("../models/marvin_kws.h5")
layer_name = "features256"
feature_extractor = Model(inputs=model.input, outputs=model.get_layer(layer_name).output)
# Obtain the feature embeddings
X_train = feature_extractor.predict(marvin_data, use_multiprocessing=True)
X_val = feature_extractor.predict(val_data, use_multiprocessing=True)
# Apply PCA to reduce dimensionality
pca = PCA(n_components=32)
pca.fit(X_train)
print("Variance captured = ", sum(pca.explained_variance_ratio_))
X_train_transformed = pca.transform(X_train)
X_val_transformed = pca.transform(X_val)
# SVM hyper-parameter tuning using Gaussian process
marvin_svm = svm.OneClassSVM()
svm_space = [
Real(10 ** -5, 10 ** 0, "log-uniform", name="gamma"),
Real(10 ** -5, 10 ** 0, "log-uniform", name="nu"),
]
@use_named_args(svm_space)
def svm_objective(**params):
marvin_svm.set_params(**params)
marvin_svm.fit(X_train_transformed)
val_pred_labels = marvin_svm.predict(X_val_transformed)
score = f1_score(val_pred_labels, val_true_labels)
return -1 * score
res_gp_svm = gp_minimize(
func=svm_objective, dimensions=svm_space, n_calls=100, n_jobs=-1, verbose=False, random_state=1
)
print("Best F1 score={:.4f}".format(-res_gp_svm.fun))
ax = plot_convergence(res_gp_svm)
plt.savefig("../docs/results/marvin_svm.png", dpi=300)
plt.show()
# Instantiate a SVM with the optimal hyper-parameters
best_params_svm = {k.name: x for k, x in zip(svm_space, res_gp_svm.x)}
marvin_kws = svm.OneClassSVM()
marvin_kws.set_params(**best_params_svm)
marvin_kws.fit(X_train_transformed)
# Performance on training set
val_pred_labels = marvin_kws.predict(X_val_transformed)
OC_Statistics(val_pred_labels, val_true_labels, "marvin_cm_training")
print("Saving PCA object")
with open("../models/marvin_kws_pca.pickle", "wb") as file:
pickle.dump(pca, file, protocol=pickle.HIGHEST_PROTOCOL)
print("Saving Marvin SVM")
with open("../models/marvin_kws_svm.pickle", "wb") as file:
pickle.dump(marvin_svm, file, protocol=pickle.HIGHEST_PROTOCOL)