-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.py
More file actions
216 lines (196 loc) · 6.6 KB
/
main.py
File metadata and controls
216 lines (196 loc) · 6.6 KB
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
import os
import yaml
import argparse
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold
from utils.data_loading import import_data
from utils.explainability import get_heatmap
from utils.helpers import create_logger, save_experiment
from models.mtex_cnn import mtex_cnn
from models.xcm import xcm
from models.xcm_seq import xcm_seq
if __name__ == "__main__":
# Load configuration
parser = argparse.ArgumentParser(description="XCM")
parser.add_argument(
"-c", "--config", default="configuration/config.yml", help="Configuration File"
)
args = parser.parse_args()
with open(args.config, "r") as config_file:
configuration = yaml.safe_load(config_file)
if configuration["model_name"] in ["XCM", "XCM-Seq"]:
window_size = configuration["window_size"]
else:
window_size = 0
model_dict = {"XCM": xcm, "XCM-Seq": xcm_seq, "MTEX-CNN": mtex_cnn}
# Create experiment folder
xp_dir = (
"./results/"
+ str(configuration["dataset"])
+ "/"
+ str(configuration["model_name"])
+ "/XP_"
+ str(configuration["experiment_run"])
+ "/"
)
save_experiment(xp_dir, args.config)
log, logclose = create_logger(log_filename=os.path.join(xp_dir, "experiment.log"))
log("Model: " + configuration["model_name"])
# Load dataset
(
X_train,
y_train,
X_test,
y_test,
y_train_nonencoded,
y_test_nonencoded,
) = import_data(configuration["dataset"], log)
print("X_train.shape: ", X_train.shape)
print("X_test.shape: ", X_test.shape)
# Instantiate the cross validator
skf = StratifiedKFold(
n_splits=configuration["cv_folds"],
random_state=configuration["random_state"],
shuffle=True,
)
# Instantiate the result dataframes
train_val_epochs_accuracies = pd.DataFrame(
columns=["Fold", "Epoch", "Accuracy_Train", "Accuracy_Validation"]
)
results = pd.DataFrame(
columns=[
"Dataset",
"Model_Name",
"Batch_Size",
"Window_Size",
"Fold",
"Accuracy_Train",
"Accuracy_Validation",
"Accuracy_Test",
]
)
# Loop through the indices the split() method returns
for index, (train_indices, val_indices) in enumerate(
skf.split(X_train, y_train_nonencoded)
):
log("\nTraining on fold " + str(index + 1))
# Generate batches from indices
xtrain, xval = X_train[train_indices], X_train[val_indices]
ytrain, yval, ytrain_nonencoded, yval_nonencoded = (
y_train[train_indices],
y_train[val_indices],
y_train_nonencoded[train_indices],
y_train_nonencoded[val_indices],
)
# Train the model
if configuration["model_name"] in ["XCM", "XCM-Seq"]:
model = model_dict[configuration["model_name"]](
input_shape=X_train.shape[1:],
n_class=y_train.shape[1],
window_size=configuration["window_size"],
)
else:
model = model_dict[configuration["model_name"]](
input_shape=X_train.shape[1:], n_class=y_train.shape[1]
)
model.compile(
optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]
)
h = model.fit(
xtrain,
ytrain,
epochs=configuration["epochs"],
batch_size=configuration["batch_size"],
verbose=1,
validation_data=(xval, yval),
)
# Calculate accuracies
fold_epochs_accuracies = np.concatenate(
(
pd.DataFrame(np.repeat(index + 1, configuration["epochs"])),
pd.DataFrame(range(1, configuration["epochs"] + 1)),
pd.DataFrame(h.history["accuracy"]),
pd.DataFrame(h.history["val_accuracy"]),
),
axis=1,
)
acc_train = accuracy_score(
ytrain_nonencoded, np.argmax(model.predict(xtrain), axis=1)
)
acc_val = accuracy_score(
yval_nonencoded, np.argmax(model.predict(xval), axis=1)
)
acc_test = accuracy_score(
y_test_nonencoded, np.argmax(model.predict(X_test), axis=1)
)
# Add fold results to the dedicated dataframe
train_val_epochs_accuracies = pd.concat(
[
train_val_epochs_accuracies,
pd.DataFrame(
fold_epochs_accuracies,
columns=["Fold", "Epoch", "Accuracy_Train", "Accuracy_Validation"],
),
],
axis=0,
)
results.loc[index] = [
configuration["dataset"],
configuration["model_name"],
configuration["batch_size"],
int(configuration["window_size"] * 100),
index + 1,
acc_train,
acc_val,
acc_test,
]
log("Accuracy Test: {0}".format(acc_test))
# Train the model on the full train set
log("\nTraining on the full train set")
if configuration["model_name"] in ["XCM", "XCM-Seq"]:
model = model_dict[configuration["model_name"]](
input_shape=X_train.shape[1:],
n_class=y_train.shape[1],
window_size=configuration["window_size"],
)
else:
model = model_dict[configuration["model_name"]](
input_shape=X_train.shape[1:], n_class=y_train.shape[1]
)
print(model.summary())
model.compile(
optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]
)
model.fit(
X_train,
y_train,
epochs=configuration["epochs"],
batch_size=configuration["batch_size"],
verbose=1,
)
# Add result to the results dataframe
acc_test = accuracy_score(
y_test_nonencoded, np.argmax(model.predict(X_test), axis=1)
)
results["Accuracy_Test_Full_Train"] = acc_test
log("Accuracy Test: {0}".format(acc_test))
# Export model and results
model.save(xp_dir + "/model.h5")
train_val_epochs_accuracies.to_csv(
xp_dir + "/train_val_accuracies.csv", index=False
)
results.to_csv(xp_dir + "/results.csv", index=False)
print(results)
# Example of a heatmap from Grad-CAM for the first MTS of the test set
get_heatmap(
configuration,
xp_dir,
model,
X_train,
X_test,
y_train_nonencoded,
y_test_nonencoded,
)
logclose()