-
Notifications
You must be signed in to change notification settings - Fork 32
/
main.py
180 lines (146 loc) · 7.61 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
import argparse
import os
import sys
from datetime import datetime
import numpy as np
import torch
from dataloader.dataloader import data_generator
from models.TC import TC
from models.model import base_Model
from trainer.trainer import Trainer, model_evaluate, gen_pseudo_labels
from utils import _calc_metrics, copy_Files
from utils import _logger, set_requires_grad
start_time = datetime.now()
parser = argparse.ArgumentParser()
######################## Model parameters ########################
home_dir = os.getcwd()
parser.add_argument('--experiment_description', default='HAR_experiments', type=str, help='Experiment Description')
parser.add_argument('--run_description', default='test1', type=str, help='Experiment Description')
parser.add_argument('--seed', default=0, type=int, help='seed value')
parser.add_argument('--training_mode', default='self_supervised', type=str,
help='Modes of choice: random_init, supervised, self_supervised, SupCon, ft_1p, gen_pseudo_labels')
parser.add_argument('--selected_dataset', default='HAR', type=str, help='Dataset of choice: EEG, HAR, Epilepsy, pFD')
parser.add_argument('--data_path', default=r'data/', type=str, help='Path containing dataset')
parser.add_argument('--logs_save_dir', default='experiments_logs', type=str, help='saving directory')
parser.add_argument('--device', default='cuda:0', type=str, help='cpu or cuda')
parser.add_argument('--home_path', default=home_dir, type=str, help='Project home directory')
args = parser.parse_args()
device = torch.device(args.device)
experiment_description = args.experiment_description
data_type = args.selected_dataset
training_mode = args.training_mode
run_description = args.run_description
logs_save_dir = args.logs_save_dir
os.makedirs(logs_save_dir, exist_ok=True)
exec(f'from config_files.{data_type}_Configs import Config as Configs')
configs = Configs()
# ##### fix random seeds for reproducibility ########
SEED = args.seed
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = False
np.random.seed(SEED)
#####################################################
experiment_log_dir = os.path.join(logs_save_dir, experiment_description, run_description,
training_mode + f"_seed_{SEED}")
os.makedirs(experiment_log_dir, exist_ok=True)
# loop through domains
counter = 0
src_counter = 0
# Logging
log_file_name = os.path.join(experiment_log_dir, f"logs_{datetime.now().strftime('%d_%m_%Y_%H_%M_%S')}.log")
logger = _logger(log_file_name)
logger.debug("=" * 45)
logger.debug(f'Dataset: {data_type}')
logger.debug(f'Mode: {training_mode}')
logger.debug("=" * 45)
# Load datasets
data_path = os.path.join(args.data_path, data_type)
train_dl, valid_dl, test_dl = data_generator(data_path, configs, training_mode)
logger.debug("Data loaded ...")
# Load Model
model = base_Model(configs).to(device)
temporal_contr_model = TC(configs, device).to(device)
if "fine_tune" in training_mode or "ft_" in training_mode:
# load saved model of this experiment
if 'SupCon' not in training_mode:
load_from = os.path.join(
os.path.join(logs_save_dir, experiment_description, run_description, f"self_supervised_seed_{SEED}",
"saved_models"))
else:
load_from = os.path.join(
os.path.join(logs_save_dir, experiment_description, run_description, f"SupCon_seed_{SEED}", "saved_models"))
chkpoint = torch.load(os.path.join(load_from, "ckp_last.pt"), map_location=device)
pretrained_dict = chkpoint["model_state_dict"]
model_dict = model.state_dict()
del_list = ['logits']
pretrained_dict_copy = pretrained_dict.copy()
for i in pretrained_dict_copy.keys():
for j in del_list:
if j in i:
del pretrained_dict[i]
model_dict.update(pretrained_dict)
model.load_state_dict(model_dict)
if training_mode == "gen_pseudo_labels":
ft_perc = "1p"
load_from = os.path.join(
os.path.join(logs_save_dir, experiment_description, run_description, f"ft_{ft_perc}_seed_{SEED}", "saved_models"))
chkpoint = torch.load(os.path.join(load_from, "ckp_last.pt"), map_location=device)
pretrained_dict = chkpoint["model_state_dict"]
model.load_state_dict(pretrained_dict)
gen_pseudo_labels(model, train_dl, device, data_path)
sys.exit(0)
if "train_linear" in training_mode or "tl" in training_mode:
if 'SupCon' not in training_mode:
load_from = os.path.join(
os.path.join(logs_save_dir, experiment_description, run_description, f"self_supervised_seed_{SEED}",
"saved_models"))
else:
load_from = os.path.join(
os.path.join(logs_save_dir, experiment_description, run_description, f"SupCon_seed_{SEED}", "saved_models"))
chkpoint = torch.load(os.path.join(load_from, "ckp_last.pt"), map_location=device)
pretrained_dict = chkpoint["model_state_dict"]
model_dict = model.state_dict()
# 1. filter out unnecessary keys
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
# delete these parameters (Ex: the linear layer at the end)
del_list = ['logits']
pretrained_dict_copy = pretrained_dict.copy()
for i in pretrained_dict_copy.keys():
for j in del_list:
if j in i:
del pretrained_dict[i]
model_dict.update(pretrained_dict)
model.load_state_dict(model_dict)
set_requires_grad(model, pretrained_dict, requires_grad=False) # Freeze everything except last layer.
if training_mode == "random_init":
model_dict = model.state_dict()
# delete all the parameters except for logits
del_list = ['logits']
pretrained_dict_copy = model_dict.copy()
for i in pretrained_dict_copy.keys():
for j in del_list:
if j in i:
del model_dict[i]
set_requires_grad(model, model_dict, requires_grad=False) # Freeze everything except last layer.
if training_mode == "SupCon":
load_from = os.path.join(
os.path.join(logs_save_dir, experiment_description, run_description, f"ft_{data_perc}p_seed_{SEED}", "saved_models"))
chkpoint = torch.load(os.path.join(load_from, "ckp_last.pt"), map_location=device)
pretrained_dict = chkpoint["model_state_dict"]
model.load_state_dict(pretrained_dict)
model_optimizer = torch.optim.Adam(model.parameters(), lr=configs.lr, betas=(configs.beta1, configs.beta2),
weight_decay=3e-4)
temporal_contr_optimizer = torch.optim.Adam(temporal_contr_model.parameters(), lr=configs.lr,
betas=(configs.beta1, configs.beta2), weight_decay=3e-4)
if training_mode == "self_supervised" or training_mode == "SupCon": # to do it only once
copy_Files(os.path.join(logs_save_dir, experiment_description, run_description), data_type)
# Trainer
Trainer(model, temporal_contr_model, model_optimizer, temporal_contr_optimizer, train_dl, valid_dl, test_dl, device,
logger, configs, experiment_log_dir, training_mode)
if training_mode != "self_supervised" and training_mode != "SupCon" and training_mode != "SupCon_pseudo":
# Testing
outs = model_evaluate(model, temporal_contr_model, test_dl, device, training_mode)
total_loss, total_acc, pred_labels, true_labels = outs
_calc_metrics(pred_labels, true_labels, experiment_log_dir, args.home_path)
logger.debug(f"Training time is : {datetime.now() - start_time}")