-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_multiview.py
176 lines (157 loc) · 10.6 KB
/
train_multiview.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
import yaml
import argparse
import os
import sys
import time
import gc
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.utils import class_weight
from src.training.utils import preprocess_views
from src.training.learn_pipeline import MultiFusion_train, assign_multifusion_name
from src.datasets.views_structure import DataViews, load_structure
from src.datasets.utils import _to_loader
OVERWRITE=True
def main_run(config_file):
start_time = time.time()
input_dir_folder = config_file["input_dir_folder"]
output_dir_folder = config_file["output_dir_folder"]
data_name = config_file["data_name"]
view_names = config_file["view_names"]
runs = config_file["experiment"]["runs"]
preprocess_args = config_file["experiment"]["preprocess"]
val_size = config_file["experiment"]["val_size"]
if config_file["experiment"].get("save_individually"):
save_ind = config_file["experiment"]["save_individually"]
else:
save_ind=False
mlflow_runs_exp = config_file["experiment"]["mlflow_runs_exp"]
try:
data_views_tr = load_structure(f"{input_dir_folder}/{data_name}_train")
except:
data_views_tr = load_structure(f"{input_dir_folder}/{data_name}")
raw_dims = {}
for view_name in data_views_tr.get_view_names():
aux_data = data_views_tr.get_view_data(view_name)["views"]
raw_dims[view_name] = {"raw": list(aux_data.shape[1:]), "flatten": int(np.prod(aux_data.shape[1:]))}
#preprocessing
funcs = preprocess_views(data_views_tr, **preprocess_args)
views_tr = data_views_tr.generate_full_view_data(views_first=True, view_names=view_names)
if config_file.get("aux_test"):
aux_test = config_file["aux_test"]
data_views_te = load_structure(f"{input_dir_folder}/{aux_test}")
else:
data_views_te = load_structure(f"{input_dir_folder}/{data_name}_test")
#preprocessing
preprocess_views(data_views_te, train=False, funcs=funcs, **preprocess_args)
views_te = data_views_te.generate_full_view_data(views_first=True, view_names=view_names)
if "loss_args" not in config_file["training"]:
config_file["training"]["loss_args"] = {}
config_file["training"]["loss_args"]["name"] = "ce" if "name" not in config_file["training"]["loss_args"] else config_file["training"]["loss_args"]["name"]
train_data_target = views_tr["target"].astype(int).flatten()
config_file["training"]["loss_args"]["weight"]=class_weight.compute_class_weight(class_weight='balanced',classes= np.unique(train_data_target), y=train_data_target)
method_name = assign_multifusion_name(config_file["training"],config_file["method"])
if config_file.get("additional_method_name"):
method_name += config_file.get("additional_method_name")
run_id_mlflow = None
metadata_r = {"epoch_runs":[], "prediction_time":[], "training_time":[], "best_score":[]}
for r in range(runs):
if os.path.isfile(f"{output_dir_folder}/pred/{data_name}/test/{method_name}/out_run-{r:02d}.csv") and not OVERWRITE:
print(f"run {r} already created.. so skipping")
continue
if mlflow_runs_exp:
run_id_mlflow = "ind"
print(f"Executing model on run {r}")
if val_size!= 0:
mask_train = np.random.rand(len(data_views_tr.get_all_identifiers())) <= (1-val_size)
indx_train = np.arange(len(mask_train))[~mask_train]
data_views_tr.set_test_mask(indx_train, reset=True)
train_data = data_views_tr.generate_full_view_data(train = True, views_first=True, view_names=view_names)
val_data = data_views_tr.generate_full_view_data(train = False, views_first=True, view_names=view_names)
else:
train_data = views_tr
val_data = None
start_aux = time.time()
method, trainer = MultiFusion_train(train_data, val_data=val_data,run_id=r,method_name=method_name,
run_id_mlflow = run_id_mlflow, **config_file)
mlf_logger, run_id_mlflow = trainer.loggers[0], trainer.loggers[0].run_id
mlf_logger.experiment.log_dict(run_id_mlflow, raw_dims, "original_data_dim.yaml")
mlf_logger.experiment.log_dict(run_id_mlflow, config_file, "config_file.yaml")
metadata_r["training_time"].append(time.time()-start_aux)
metadata_r["epoch_runs"].append(trainer.callbacks[0].stopped_epoch)
metadata_r["best_score"].append(trainer.callbacks[0].best_score.cpu())
print("Training done")
pred_time_Start = time.time()
BS = config_file["training"]["batch_size"]
outputs_tr = method.transform(_to_loader(views_tr, batch_size=BS, train=False), output=True, out_norm=True, **config_file) #.get("forward_testing"))
outputs_te = method.transform(_to_loader(views_te, batch_size=BS, train=False), output=True, out_norm=True, **config_file) #.get("forward_testing"))
metadata_r["prediction_time"].append(time.time()-pred_time_Start)
## EXTRA -- PREDICTIONS ##
data_save_tr = DataViews([outputs_tr["prediction"]], identifiers=views_tr["identifiers"], view_names=[f"out_run-{r:02d}"])
data_save_tr.save(f"{output_dir_folder}/pred/{data_name}/train/{method_name}", ind_views=True, xarray=False)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/pred/{data_name}/train/{method_name}/out_run-{r:02d}.csv",
artifact_path="preds/train")
data_save_te = DataViews([outputs_te["prediction"]], identifiers=views_te["identifiers"], view_names=[f"out_run-{r:02d}"])
data_save_te.save(f"{output_dir_folder}/pred/{data_name}/test/{method_name}", ind_views=True, xarray=False)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/pred/{data_name}/test/{method_name}/out_run-{r:02d}.csv",
artifact_path="preds/test")
for v in outputs_tr:
if ":prediction" in v:
print(f"Saving auxiliar predictions from {v}")
for key, value in outputs_tr[v].items():
data_save_tr = DataViews([value], identifiers=views_tr["identifiers"], view_names=[f"out_run-{r:02d}"])
data_save_tr.save(f"{output_dir_folder}/pred/{data_name}/train/{method_name}/{key}", ind_views=True, xarray=False)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/pred/{data_name}/train/{method_name}/{key}/out_run-{r:02d}.csv",
artifact_path=f"preds/train/{method_name}/{key}")
for key, value in outputs_te[v].items():
data_save_te = DataViews([value], identifiers=views_te["identifiers"], view_names=[f"out_run-{r:02d}"])
data_save_te.save(f"{output_dir_folder}/pred/{data_name}/test/{method_name}/{key}", ind_views=True, xarray=False)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/pred/{data_name}/test/{method_name}/{key}/out_run-{r:02d}.csv",
artifact_path=f"preds/test/{method_name}/{key}")
if config_file["method"]["feature"]:
data_save_tr = DataViews(outputs_tr["views:rep"], identifiers=views_tr["identifiers"], view_names=view_names)
data_save_tr.save(f"{output_dir_folder}/repre/{data_name}/train/{method_name}_{r:02d}", ind_views=save_ind)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/repre/{data_name}/train/{method_name}_{r:02d}.nc",
artifact_path="repre/train")
data_save_te = DataViews(outputs_te["views:rep"], identifiers=views_te["identifiers"], view_names=view_names)
data_save_te.save(f"{output_dir_folder}/repre/{data_name}/test/{method_name}_{r:02d}", ind_views=save_ind)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/repre/{data_name}/test/{method_name}_{r:02d}.nc",
artifact_path="repre/test")
if "att_views" in outputs_tr:
data_save_tr = DataViews([outputs_tr["att_views"]], identifiers=views_tr["identifiers"], view_names=[f"attention"])
data_save_tr.target_names = method.view_names #to save order of attention
data_save_tr.save(f"{output_dir_folder}/att/{data_name}/train/{method_name}/att_run-{r:02d}", xarray=True)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/att/{data_name}/train/{method_name}/att_run-{r:02d}.nc",
artifact_path="att/train")
data_save_te = DataViews([outputs_te["att_views"]], identifiers=views_te["identifiers"], view_names=[f"attention"])
data_save_te.target_names = method.view_names #to save order of attention
data_save_te.save(f"{output_dir_folder}/att/{data_name}/test/{method_name}/att_run-{r:02d}", xarray=True)
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/att/{data_name}/test/{method_name}/att_run-{r:02d}.nc",
artifact_path="att/test")
print(f"Run {r:02d} of {method_name} finished...")
if type(run_id_mlflow) != type(None):
mlf_logger.experiment.log_metric(run_id_mlflow, "mean_tr_time", np.mean(metadata_r["training_time"]))
mlf_logger.experiment.log_metric(run_id_mlflow, "mean_pred_time", np.mean(metadata_r["prediction_time"]))
mlf_logger.experiment.log_metric(run_id_mlflow, "mean_epoch_runs", np.mean(metadata_r["epoch_runs"]))
mlf_logger.experiment.log_metric(run_id_mlflow, "mean_best_score", np.mean(metadata_r["best_score"]))
pd.DataFrame(metadata_r).to_csv(f"{output_dir_folder}/metadata_runs.csv")
mlf_logger.experiment.log_artifact(run_id_mlflow, f"{output_dir_folder}/metadata_runs.csv",)
os.remove(f"{output_dir_folder}/metadata_runs.csv")
print("Epochs for %s runs on average for %.2f epochs +- %.3f"%(method_name,np.mean(metadata_r["epoch_runs"]),np.std(metadata_r["epoch_runs"])))
print(f"Finished whole execution of {runs} runs in {time.time()-start_time:.2f} secs")
if __name__ == "__main__":
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
"--settings_file",
"-s",
action="store",
dest="settings_file",
required=True,
type=str,
help="path of the settings file",
)
args = arg_parser.parse_args()
with open(args.settings_file) as fd:
config_file = yaml.load(fd, Loader=yaml.SafeLoader)
main_run(config_file)