-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
274 lines (233 loc) · 10.8 KB
/
main.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import numpy as np
import pandas as pd
import torch
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from torch.utils.data import DataLoader
from utils import (
DynamicDataset,
DynamicMultitasker,
load_embeddings_and_labels,
embedding_dimensions,
results_to_dict,
)
from sklearn.model_selection import KFold, train_test_split
from sklearn.metrics import r2_score, f1_score
from scipy.stats import pearsonr
import yaml, json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=str, default="config.yaml")
args = parser.parse_args()
with open(args.config, "r") as f:
config = yaml.safe_load(f)
# TODO:
# - The routing branch is a good idea (different embeddings for different targets).
# It must not be done by modality, but by voice or no-voice.
# - a way to include critical analysis in the loss function is to employ a gain on
# the signal coming from the class gender exaggeration, as well as the scales anger,
# beauty, etc, together with the overall target.
torch.manual_seed(42)
#####################
# Load ground truth #
#####################
groundtruth_df = pd.read_csv("groundtruth_merged.csv")
groundtruth_df.set_index("stimulus_id", inplace=True)
emotions_and_mid_level_df = pd.read_csv("emotions_and_mid_level.csv")
emotions_and_mid_level_df.set_index("stimulus_id", inplace=True)
# drop columns that would introduce noise
n_emotions = 7
if config["drop_non_significant"]:
to_drop = [
"Amusing", # Extremely low correlations with all the mid-level features
"Wide/Narrow pitch variation", # non significant differences between targets (ANOVA)
"Repetitive/Non-repetitive", # non significant differences between targets (ANOVA)
"Fast tempo/Slow tempo", # non significant differences between targets (ANOVA)
]
emotions_and_mid_level_df = emotions_and_mid_level_df.drop(columns=to_drop)
n_emotions -= 1 # we dropped Amusing
###################
# Repeated k-fold #
###################
# iterate over the various configurations
for filmed in config["filmed_list"]:
for targets_list in config["targets_list"]:
for which in config["which_embeddings"]:
for voice in config["voice_list"]:
# add current status to config
config["cls_dict"]["target"] = targets_list
# load data
X, y_mid, y_emo, y_cls = load_embeddings_and_labels(
groundtruth_df,
emotions_and_mid_level_df,
which,
config["modality"],
voice,
config["cls_dict"],
n_emotions,
)
# set the parameters for the model
params = {
"input_dim": X.shape[1],
"n_emo": y_emo.shape[1],
"n_mid": y_mid.shape[1],
"cls_dict": config["cls_dict"],
"filmed": filmed,
}
# prepare the results
all_cls_f1s = {k: [] for k in config["cls_dict"]}
all_r2s_mid = []
all_r2s_emo = []
all_pear_mid = []
all_pear_emo = []
all_ps_mid = []
all_ps_emo = []
for _ in range(config["repetitions"]):
kf = KFold(
n_splits=config["folds"], shuffle=True
) # NO RANDOM SEED, get a new split each time
cls_f1s = {k: [] for k in config["cls_dict"]}
r2s_mid = []
r2s_emo = []
pears_mid = []
pears_emo = []
ps_mid = []
ps_emo = []
for train_index, test_index in kf.split(X):
test_index, val_index = train_test_split(test_index, test_size=0.5)
# get the split
X_train, X_test, X_val = X[train_index], X[test_index], X[val_index]
y_mid_train, y_mid_test, y_mid_val = (
y_mid[train_index],
y_mid[test_index],
y_mid[val_index],
)
y_emo_train, y_emo_test, y_emo_val = (
y_emo[train_index],
y_emo[test_index],
y_emo[val_index],
)
y_cls_train, y_cls_test, y_cls_val = (
{k: y_cls[k][train_index] for k in y_cls},
{k: y_cls[k][test_index] for k in y_cls},
{k: y_cls[k][val_index] for k in y_cls},
)
train_dataset = DynamicDataset(
X_train, y_mid_train, y_emo_train, y_cls_train
)
val_dataset = DynamicDataset(X_val, y_mid_val, y_emo_val, y_cls_val)
train_loader = DataLoader(
train_dataset, batch_size=8, shuffle=True, num_workers=1
)
val_loader = DataLoader(
val_dataset, batch_size=8, shuffle=False, num_workers=1
)
# train
model = DynamicMultitasker(**params)
checkpoint_callback = ModelCheckpoint(monitor="val_loss")
trainer = pl.Trainer(
max_epochs=config["max_epochs"],
callbacks=[
checkpoint_callback,
EarlyStopping(monitor="val_loss", patience=30),
],
enable_progress_bar=False,
accelerator="gpu",
devices=1,
)
trainer.fit(model, train_loader, val_loader)
# load best model
model = model.load_from_checkpoint(
checkpoint_callback.best_model_path, **params
)
# evaluate on test set
model.eval()
with torch.no_grad():
y_mid_pred, y_emo_pred, y_cls_pred = model(
torch.from_numpy(X_test).float()
)
for k in config["cls_dict"]:
y_pred_temp = y_cls_pred[k]
y_test_temp = y_cls_test[k]
skip_unlabelled = y_test_temp != -1
y_pred_temp = torch.argmax(y_pred_temp, dim=1).numpy()[
skip_unlabelled # <<<<<<<<<<<<<<<<<<<<<
]
y_test_temp = y_test_temp[skip_unlabelled]
cls_f1s[k].append(
f1_score(y_test_temp, y_pred_temp, average="weighted")
)
y_mid_pred = y_mid_pred.numpy()
y_emo_pred = y_emo_pred.numpy()
r2_mid = r2_score(y_mid_test, y_mid_pred, multioutput="raw_values")
r2s_mid.append(r2_mid)
r2_emo = r2_score(y_emo_test, y_emo_pred, multioutput="raw_values")
r2s_emo.append(r2_emo)
r_mid = [
pearsonr(y_mid_test[:, i], y_mid_pred[:, i])[0]
for i in range(y_mid_test.shape[1])
]
r_emo = [
pearsonr(y_emo_test[:, i], y_emo_pred[:, i])[0]
for i in range(y_emo_test.shape[1])
]
p_mid = [
pearsonr(y_mid_test[:, i], y_mid_pred[:, i])[1]
for i in range(y_mid_test.shape[1])
]
p_emo = [
pearsonr(y_emo_test[:, i], y_emo_pred[:, i])[1]
for i in range(y_emo_test.shape[1])
]
pears_emo.append(r_emo)
pears_mid.append(r_mid)
ps_emo.append(p_emo)
ps_mid.append(p_mid)
for k in config["cls_dict"]:
all_cls_f1s[k].append(cls_f1s[k])
all_r2s_emo.append(r2s_emo)
all_r2s_mid.append(r2s_mid)
all_pear_emo.append(pears_emo)
all_pear_mid.append(pears_mid)
all_ps_emo.append(ps_emo)
all_ps_mid.append(ps_mid)
# convert to numpy arrays
for k in config["cls_dict"]:
all_cls_f1s[k] = np.array(all_cls_f1s[k])
all_r2s_mid = np.array(all_r2s_mid)
all_r2s_emo = np.array(all_r2s_emo)
all_pear_mid = np.array(all_pear_mid)
all_pear_emo = np.array(all_pear_emo)
all_ps_mid = np.array(all_ps_mid)
all_ps_emo = np.array(all_ps_emo)
## save results
current_config_dict = {
"modality": config["modality"],
"voice": voice,
"classifications": config["cls_dict"],
"which_embeddings": which,
"drop_non_significant": config["drop_non_significant"],
}
# results
results_dict = results_to_dict(
all_cls_f1s,
all_r2s_mid,
all_r2s_emo,
all_pear_mid,
all_pear_emo,
all_ps_mid,
all_ps_emo,
list(emotions_and_mid_level_df.columns[n_emotions:]),
list(emotions_and_mid_level_df.columns[:n_emotions]),
)
results_dict["config"] = current_config_dict
# save results to file
# horridly long filename
foo = "_filmed" if filmed else ""
filename = (
f"results{foo}/targCls_{len(targets_list)}_{config['modality']}_{which}"
f"_voice_{voice}_TotCls_{len(config['cls_dict'].keys())}_dropNs_{config['drop_non_significant']}"
f"_rep_{config['repetitions']}_fold_{config['folds']}.json"
)
with open(filename, "w") as f:
json.dump(results_dict, f)