Download train.py from FelixOtt/5g-dil: direct link, hf CLI and curl.
- Browser
- Download file 26.2 kB
-
https://huggingface.co/datasets/FelixOtt/5g-dil/resolve/main/train.py
- Command line
-
hf download hf://datasets/FelixOtt/5g-dil/train.py
-
curl -L -o train.py https://huggingface.co/datasets/FelixOtt/5g-dil/resolve/main/train.py
26.2 kB
| import torch | |
| from torch.utils.data import DataLoader, Subset, ConcatDataset | |
| from model import TimeCNN, ProgressiveTimeCNN | |
| from dataset import TSDataset, ErrDataset | |
| from sklearn.metrics import median_absolute_error as mae | |
| import os | |
| import torch.nn.functional as F | |
| import sys | |
| from scipy import spatial | |
| from numpy import dot | |
| from numpy.linalg import norm | |
| import datetime | |
| import numpy as np | |
| import random | |
| from distances import * | |
| import logging | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| def _set_random(seed): | |
| torch.manual_seed(seed) | |
| random.seed(seed) | |
| np.random.seed(seed) | |
| torch.cuda.manual_seed(1) | |
| torch.cuda.manual_seed_all(1) | |
| torch.backends.cudnn.deterministic = True | |
| torch.backends.cudnn.benchmark = False | |
| class Localization: | |
| def __init__(self, model, config, device): | |
| self.config = config | |
| self._device = device | |
| self.model = model.to(self._device) | |
| self.X_min = 5 | |
| self.X_max = 35 | |
| self.Y_min = 5 | |
| self.Y_max = 25 | |
| self.task_idx = 0 | |
| _set_random(self.config['seed']) | |
| def return_distances(self, prev_dname, curr_dname, method='euclidean'): | |
| prev_dataset = TSDataset(data_path=f"{prev_dname}/training_data") | |
| curr_dataset = TSDataset(data_path=f"{curr_dname}/cleaned_training_data") | |
| tree = spatial.KDTree(prev_dataset.targets) | |
| _, indices = tree.query(curr_dataset.targets) | |
| data2_flat = curr_dataset.data.reshape(len(curr_dataset.data), -1) | |
| data1_flat = prev_dataset.data[indices].reshape(len(indices), -1) | |
| if method == 'manhattan': | |
| distances = manhattan(data1_flat, data2_flat) | |
| elif method == 'euclidean': | |
| distances = euclidean(data1_flat, data2_flat) | |
| elif method == 'minkowski': | |
| distances = minkowski(data1_flat, data2_flat) | |
| elif method == 'mahalanobis': | |
| distances = mahalanobis(data1_flat, data2_flat) | |
| elif method == 'chebyshev': | |
| distances = chebyshev(data1_flat, data2_flat) | |
| elif method == 'canberra': | |
| distances = canberra(data1_flat, data2_flat) | |
| elif method == 'bray_curtis': | |
| distances = bray_curtis(data1_flat, data2_flat) | |
| elif method == 'correlation': | |
| distances = correlation(data1_flat, data2_flat) | |
| else: | |
| sys.exit(f"Distance metric {method} not implemented!!") | |
| return distances | |
| def cosine_similarity(self, prev_dname, curr_dname): | |
| prev_dataset = TSDataset(data_path=f"{prev_dname}/training_data") | |
| curr_dataset = TSDataset(data_path=f"{curr_dname}/cleaned_training_data") | |
| tree = spatial.KDTree(prev_dataset.targets) | |
| _, indices = tree.query(curr_dataset.targets) | |
| data2_flat = curr_dataset.data.reshape(len(curr_dataset.data), -1) | |
| data1_flat = prev_dataset.data[indices].reshape(len(indices), -1) | |
| dot_products = np.sum(data2_flat * data1_flat, axis=1) | |
| norms_1 = norm(data2_flat, axis=1) | |
| norms_2 = norm(data1_flat, axis=1) | |
| cosine_similarities = dot_products / (norms_1 * norms_2) | |
| return cosine_similarities | |
| def random_subset(self, dataset, count=200): | |
| indices = torch.randint(0, len(dataset), (count,)) | |
| return Subset(dataset, indices) | |
| def distances_based_equal_distribution(self, prev_dname, curr_dname, subset_count=200): | |
| dataset = TSDataset(data_path=f"{curr_dname}/cleaned_training_data") | |
| data = dataset.data | |
| targets = dataset.targets | |
| distances = self.return_distances(prev_dname, curr_dname, method=self.config['subset_name']) | |
| mask = np.ones(len(distances)) | |
| step = 5 | |
| grids = ((self.X_max - self.X_min)/step) * ((self.Y_max - self.Y_min)/step) | |
| samples_per_grid = int((subset_count//grids)+1) | |
| for x in range(self.X_min, self.X_max, step): | |
| for y in range(self.Y_min, self.Y_max, step): | |
| indices = np.where((targets[:, 0] > x) & (targets[:, 0] < x+step) & (targets[:, 1] > y) & (targets[:, 1] < y+step))[0] | |
| count = 0 | |
| min_dist = 0 | |
| if len(indices) > 0 and len(indices) >= samples_per_grid: | |
| while count <= samples_per_grid: | |
| count = np.sum(distances[indices] <= min_dist) | |
| min_dist = min_dist + 0.01 | |
| logging.info(f'Max similarity for {samples_per_grid} data points is {min_dist} in the region x: ({x} - {x+5}) and y: ({y} - {y+5})') | |
| for indice, dist in zip(indices, distances[indices]): | |
| if dist > min_dist: | |
| mask[indice] = 0 | |
| if np.sum(mask[indices]) > samples_per_grid: | |
| diff = np.sum(mask[indices]) - samples_per_grid | |
| one_indices = np.where(mask[indices] == 1)[0] | |
| zero_indices = np.random.choice(one_indices, size=int(diff), replace=False) | |
| mask[indices[zero_indices]] = 0 | |
| logging.info(f"No of data points in this grid x:{x}-{x+5} y:{y}-{y+5} : {np.sum(mask[indices])})") | |
| mask = mask.astype(bool) | |
| error_based_data = data[mask,:] | |
| error_based_targets = targets[mask, :] | |
| logging.info('Error-based data len', len(error_based_data)) | |
| return ErrDataset(error_based_data, error_based_targets) | |
| def similarity_based_equal_distribution(self, prev_dname, curr_dname, subset_count=200): | |
| dataset = TSDataset(data_path=f"{curr_dname}/cleaned_training_data") | |
| data = dataset.data | |
| targets = dataset.targets | |
| similarity = self.cosine_similarity(prev_dname, curr_dname) | |
| mask = np.ones(len(similarity)) | |
| step = 5 | |
| grids = ((self.X_max - self.X_min)/step) * ((self.Y_max - self.Y_min)/step) | |
| samples_per_grid = int((subset_count//grids)+1) | |
| for x in range(self.X_min, self.X_max, step): | |
| for y in range(self.Y_min, self.Y_max, step): | |
| indices = np.where((targets[:, 0] > x) & (targets[:, 0] < x+step) & (targets[:, 1] > y) & (targets[:, 1] < y+step))[0] | |
| count = 0 | |
| max_sim = 1.0 | |
| if len(indices) > 0 and len(indices) >= samples_per_grid: | |
| while count <= samples_per_grid: | |
| count = np.sum(similarity[indices] > max_sim) | |
| max_sim = max_sim - 0.01 | |
| logging.info(f'Max similarity for {samples_per_grid} data points is {max_sim} in the region x: ({x} - {x+5}) and y: ({y} - {y+5})') | |
| for indice, sim in zip(indices, similarity[indices]): | |
| if sim < max_sim: | |
| mask[indice] = 0 | |
| if np.sum(mask[indices]) > samples_per_grid: | |
| diff = np.sum(mask[indices]) - samples_per_grid | |
| one_indices = np.where(mask[indices] == 1)[0] | |
| zero_indices = np.random.choice(one_indices, size=int(diff), replace=False) | |
| mask[indices[zero_indices]] = 0 | |
| logging.info(f"No of data points in this grid x:{x}-{x+5} y:{y}-{y+5} : {np.sum(mask[indices])})") | |
| mask = mask.astype(bool) | |
| error_based_data = data[mask,:] | |
| error_based_targets = targets[mask, :] | |
| logging.info('Error-based data len', len(error_based_data)) | |
| return ErrDataset(error_based_data, error_based_targets) | |
| def equal_distribution(self, dname, subset_count=200): | |
| dataset = TSDataset(data_path=f"{dname}/cleaned_training_data") | |
| data = dataset.data | |
| targets = dataset.targets | |
| mask = np.zeros(len(dataset)) | |
| step = 5 | |
| grids = ((self.X_max - self.X_min)/step) * ((self.Y_max - self.Y_min)/step) | |
| samples_per_grid = int((subset_count//grids)+1) | |
| for x in range(self.X_min, self.X_max, step): | |
| for y in range(self.Y_min, self.Y_max, step): | |
| indices = np.where((targets[:, 0] > x) & (targets[:, 0] < x+step) & (targets[:, 1] > y) & (targets[:, 1] < y+step))[0] | |
| if len(indices) > 0 and len(indices) >= samples_per_grid: | |
| one_indices = np.random.choice(indices, size=int(samples_per_grid), replace=False) | |
| mask[one_indices] = 1 | |
| logging.info(f"No of data points in this grid x:{x}-{x+5} y:{y}-{y+5} : {np.sum(mask[indices])})") | |
| mask = mask.astype(bool) | |
| error_based_data = data[mask,:] | |
| error_based_targets = targets[mask, :] | |
| logging.info('Error-based data len', len(error_based_data)) | |
| return ErrDataset(error_based_data, error_based_targets) | |
| def error_dependent_random_min(self, dname, subset_count=200): | |
| absolute_dis, dataset = self.get_mae_and_data(dname=dname) | |
| data = dataset.data | |
| targets = dataset.targets | |
| mask = np.ones(len(dataset)) | |
| count = 0 | |
| min_err = 0.0 | |
| while count <= subset_count: | |
| count = np.sum(absolute_dis < min_err) | |
| min_err = min_err + 0.01 | |
| logging.info(f'Count of data points for min_error {min_err}m is {count}') | |
| for idx, dis in enumerate(absolute_dis): | |
| if dis > min_err: | |
| mask[idx] = 0 | |
| if np.sum(mask) > subset_count: | |
| diff = np.sum(mask) - subset_count | |
| one_indices = np.where(mask == 1)[0] | |
| zero_indices = np.random.choice(one_indices, size=int(diff), replace=False) | |
| mask[zero_indices] = 0 | |
| mask = mask.astype(bool) | |
| logging.info(f"No of data points : {np.sum(mask)})") | |
| error_based_data = data[mask,:] | |
| error_based_targets = targets[mask, :] | |
| logging.info('Error-based data len', len(error_based_data)) | |
| return ErrDataset(error_based_data, error_based_targets) | |
| def error_dependent_random_max(self, dname, subset_count=200): | |
| absolute_dis, dataset = self.get_mae_and_data(dname=dname) | |
| data = dataset.data | |
| targets = dataset.targets | |
| mask = np.ones(len(dataset)) | |
| count = 0 | |
| max_err = 10.0 | |
| while count <= subset_count: | |
| count = np.sum(absolute_dis > max_err) | |
| max_err = max_err - 0.01 | |
| logging.info(f'Count of data points for max_error {max_err}m is {count}') | |
| logging.info(f'Min error for {subset_count} data points are {max_err}') | |
| for idx, dis in enumerate(absolute_dis): | |
| if dis < max_err: | |
| mask[idx] = 0 | |
| if np.sum(mask) > subset_count: | |
| diff = np.sum(mask) - subset_count | |
| one_indices = np.where(mask == 1)[0] | |
| zero_indices = np.random.choice(one_indices, size=int(diff), replace=False) | |
| mask[zero_indices] = 0 | |
| mask = mask.astype(bool) | |
| logging.info(f"No of data points : {np.sum(mask)})") | |
| error_based_data = data[mask,:] | |
| error_based_targets = targets[mask, :] | |
| logging.info('Error-based data len', len(error_based_data)) | |
| return ErrDataset(error_based_data, error_based_targets) | |
| def error_dependent_equal_distribution_min(self, dname, subset_count=200): | |
| absolute_dis, dataset = self.get_mae_and_data(dname=dname) | |
| data = dataset.data | |
| targets = dataset.targets | |
| mask = np.ones(len(dataset)) | |
| step = 5 | |
| grids = ((self.X_max - self.X_min)/step) * ((self.Y_max - self.Y_min)/step) | |
| samples_per_grid = int((subset_count//grids)+1) | |
| for x in range(self.X_min, self.X_max, step): | |
| for y in range(self.Y_min, self.Y_max, step): | |
| indices = np.where((targets[:, 0] > x) & (targets[:, 0] < x+step) & (targets[:, 1] > y) & (targets[:, 1] < y+step))[0] | |
| count = 0 | |
| min_err = 0.0 | |
| if len(indices) > 0 and len(indices) >= samples_per_grid: | |
| while count <= samples_per_grid: | |
| count = np.sum(absolute_dis[indices] < min_err) | |
| min_err = min_err + 0.01 | |
| logging.info(f'Min error for ((subset_count//24)+1) data points is {min_err} in the region x: ({x} - {x+5}) and y: ({y} - {y+5})') | |
| for indice, dis in zip(indices, absolute_dis[indices]): | |
| if dis > min_err: | |
| mask[indice] = 0 | |
| if np.sum(mask[indices]) > ((subset_count//24)+1): | |
| diff = np.sum(mask[indices]) - ((subset_count//24)+1) | |
| one_indices = np.where(mask[indices] == 1)[0] | |
| zero_indices = np.random.choice(one_indices, size=int(diff), replace=False) | |
| mask[indices[zero_indices]] = 0 | |
| logging.info(f"No of data points in this grid x:{x}-{x+5} y:{y}-{y+5} : {np.sum(mask[indices])})") | |
| mask = mask.astype(bool) | |
| error_based_data = data[mask,:] | |
| error_based_targets = targets[mask, :] | |
| logging.info('Error-based data len', len(error_based_data)) | |
| return ErrDataset(error_based_data, error_based_targets) | |
| def error_dependent_equal_distribution_max(self, dname, subset_count=200): | |
| absolute_dis, dataset = self.get_mae_and_data(dname=dname) | |
| data = dataset.data | |
| targets = dataset.targets | |
| mask = np.ones(len(dataset)) | |
| step = 5 | |
| grids = ((self.X_max - self.X_min)/step) * ((self.Y_max - self.Y_min)/step) | |
| samples_per_grid = int((subset_count//grids)+1) | |
| for x in range(self.X_min, self.X_max, step): | |
| for y in range(self.Y_min, self.Y_max, step): | |
| indices = np.where((targets[:, 0] > x) & (targets[:, 0] < x+step) & (targets[:, 1] > y) & (targets[:, 1] < y+step))[0] | |
| count = 0 | |
| max_err = 10.0 | |
| if len(indices) > 0 and len(indices) >= samples_per_grid: | |
| while count <= samples_per_grid: | |
| count = np.sum(absolute_dis[indices] > max_err) | |
| max_err = max_err - 0.01 | |
| logging.info(f'Max error for ((subset_count//24)+1) data points is {max_err} in the region x: ({x} - {x+5}) and y: ({y} - {y+5})') | |
| for indice, dis in zip(indices, absolute_dis[indices]): | |
| if dis < max_err: | |
| mask[indice] = 0 | |
| if np.sum(mask[indices]) > ((subset_count//24)+1): | |
| diff = np.sum(mask[indices]) - ((subset_count//24)+1) | |
| one_indices = np.where(mask[indices] == 1)[0] | |
| zero_indices = np.random.choice(one_indices, size=int(diff), replace=False) | |
| mask[indices[zero_indices]] = 0 | |
| logging.info(f"No of data points in this grid x:{x}-{x+5} y:{y}-{y+5} : {np.sum(mask[indices])})") | |
| mask = mask.astype(bool) | |
| error_based_data = data[mask,:] | |
| error_based_targets = targets[mask, :] | |
| logging.info('Error-based data len', len(error_based_data)) | |
| return ErrDataset(error_based_data, error_based_targets) | |
| def get_mae_and_data(self, dname): | |
| dataset = TSDataset(data_path=f"{dname}/cleaned_training_data") | |
| loader = DataLoader(dataset, batch_size=16, shuffle=False) | |
| self.model.eval() | |
| true_values = [] | |
| predicted_values = [] | |
| self.model.to(self._device) | |
| with torch.no_grad(): | |
| for inputs, targets in loader: | |
| inputs, targets = inputs.to(self._device), targets.to(self._device) | |
| outputs = self.model(inputs) | |
| true_values.extend(targets.detach().cpu().numpy()) | |
| predicted_values.extend(outputs.detach().cpu().numpy()) | |
| median_error = mae(y_true=np.array(true_values), y_pred=np.array(predicted_values)) | |
| logging.info(f'Median Error on {dname}: {median_error}') | |
| absolute_dis = np.linalg.norm(np.array(true_values)-np.array(predicted_values), axis=1) | |
| return absolute_dis, dataset | |
| def get_dataset(self, dataset_name, subset_count=0, subset_name='normal'): | |
| """ | |
| Loads the training, validation, and test datasets for a given dataset name, along with exemplars from the previous scenario | |
| for a selected subset_name | |
| Parameters: | |
| ---------- | |
| dataset_name : str | |
| The name of the dataset to load. | |
| subset_count : int, optional (default=0) | |
| Number of exemplars to add to the training dataset from a previous scenario. | |
| subset_name : str, optional (default='normal') | |
| Strategy for selecting additional exemplars. Options include: | |
| - 'ED': Equal distribution. | |
| - 'ED-Min', 'ED-Max': Error-dependent equal distribution (min/max). | |
| - 'RD': Random distribution. | |
| - 'RD-Min', 'RD-Max': Error-dependent random distribution (min/max). | |
| - 'ED-CosineSimilarity': Cosine similarity-based selection from previous dataset. | |
| - Distance-based methods: 'manhattan', 'euclidean', 'minkowski', 'mahalanobis', 'chebyshev', 'canberra', 'bray_curtis', 'correlation'. | |
| Returns: | |
| ------- | |
| tuple of torch.utils.data.DataLoader | |
| Returns a tuple: (train_loader, val_loader, test_loader). | |
| """ | |
| if ("change" in dataset_name) or ('Absorber' in dataset_name): | |
| train_dataset = TSDataset(data_path=f"{dataset_name}/repair_training_data") | |
| val_dataset = TSDataset(data_path=f"{dataset_name}/repair_validation_data") | |
| test_dataset = TSDataset(data_path=f"{dataset_name}/test_data") | |
| if self.config["get_subset"]: | |
| logging.info(f'Fetching the exemplars {subset_name}') | |
| if subset_name == 'ED': | |
| additional_dataset = self.equal_distribution(dname=dataset_name, subset_count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| if subset_name == 'ED-Min': | |
| additional_dataset = self.error_dependent_equal_distribution_min(dname=dataset_name, subset_count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| if subset_name == 'ED-Max': | |
| additional_dataset = self.error_dependent_equal_distribution_max(dname=dataset_name, subset_count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| if subset_name == 'RD-Max': | |
| additional_dataset = self.error_dependent_random_max(dname=dataset_name, subset_count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| if subset_name == 'RD-Min': | |
| additional_dataset = self.error_dependent_random_min(dname=dataset_name, subset_count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| if subset_name == 'RD': | |
| additional_dataset = TSDataset(data_path=f"{dataset_name}/cleaned_training_data") | |
| additional_dataset = self.random_subset(additional_dataset, count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| if subset_name == 'ED-CosineSimilarity': | |
| additional_dataset = self.similarity_based_equal_distribution(prev_dname=self.datasets[self.curr_dataset_idx-1], curr_dname=dataset_name, subset_count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| if subset_name in ('manhattan', 'euclidean', "minkowski", "mahalanobis", "chebyshev", "canberra", "bray_curtis", "correlation") : | |
| additional_dataset = self.distances_based_equal_distribution(prev_dname=self.datasets[self.curr_dataset_idx-1], curr_dname=dataset_name, subset_count=subset_count) | |
| train_dataset = ConcatDataset([train_dataset, additional_dataset]) | |
| else: | |
| train_dataset = TSDataset(data_path=f"{dataset_name}/training_data") | |
| val_dataset = TSDataset(data_path=f"{dataset_name}/validation_data") | |
| test_dataset = TSDataset(data_path=f"{dataset_name}/test_data") | |
| train_loader = DataLoader(train_dataset, batch_size=self.config['batch_size'], shuffle=True) | |
| val_loader = DataLoader(val_dataset, batch_size=self.config['batch_size'], shuffle=False) | |
| test_loader = DataLoader(test_dataset, batch_size=self.config['batch_size'], shuffle=False) | |
| assert len(train_loader) > 0, "Train loader is empty" | |
| assert len(val_loader) > 0, "Validation loader is empty" | |
| assert len(test_loader) > 0, "Test loader is empty" | |
| return train_loader, val_loader, test_loader | |
| def test_on_all_datasets(self, base_path, curr_dname): | |
| """ | |
| Evaluates the trained model on all datasets and logs performance metrics. | |
| This function: | |
| - Loads the best model checkpoint (based on validation performance). | |
| - Tests the model on each dataset in `self.datasets`. | |
| - Computes the mean squared error loss. | |
| - Logs and writes the results to a text file. | |
| Parameters: | |
| ---------- | |
| base_path : str | |
| The directory path where the model checkpoints and logs are stored. | |
| curr_dname : str | |
| The name of the dataset that the model was most recently trained on. | |
| ''' | |
| error_on_all = open(base_path + '/test_error.txt', "w") | |
| outputWeightspath = base_path + "/weights/" | |
| val_accs = np.loadtxt(base_path + "/log.txt", dtype=float) | |
| min_error_epoch = np.argmin(val_accs[:, -1]) | |
| best_epoch = int(val_accs[min_error_epoch, 0]) | |
| logging.info(f'Loading the model with best minimum medium error at epoch {best_epoch}') | |
| for dname in self.datasets: | |
| _, _, test_loader = self.get_dataset(dname) | |
| if self.config['method'] == 'pnn': | |
| base_model = TimeCNN() | |
| test_model = ProgressiveTimeCNN(base_model=base_model) | |
| test_model.task = self.task_idx | |
| else: | |
| test_model = TimeCNN() | |
| test_model.load_state_dict(torch.load(outputWeightspath + str(best_epoch) + '.h5', map_location=self._device)) | |
| test_model.eval() | |
| true_values = [] | |
| predicted_values = [] | |
| test_loss = 0.0 | |
| with torch.no_grad(): | |
| for i, (inputs, targets) in enumerate(test_loader): | |
| inputs, targets = inputs.to(self._device), targets.to(self._device) | |
| outputs = test_model(inputs) | |
| loss = F.mse_loss(outputs, targets) | |
| true_values.extend(targets.detach().cpu().numpy()) | |
| predicted_values.extend(outputs.detach().cpu().numpy()) | |
| test_loss += loss.item() | |
| if i == 10: | |
| break | |
| median_error = mae(y_true=np.array(true_values), y_pred=np.array(predicted_values)) | |
| logging.info(f'Test Loss: {test_loss/len(test_loader):.4f}, Median Error: {median_error}') | |
| error_on_all.write(f'tr_{curr_dname}_te_{dname}'+ '\t' + "%.5f\t%.5f\n" % (test_loss/len(test_loader), median_error)) | |
| error_on_all.flush() | |
| def get_file_name(self): | |
| return f"epochs{self.config['epochs']}_lambda{self.config['lambda']}_subset{self.config['subset_name']}({self.config['subset_N']})" | |
| def sequential_training(self, trainer, datasets, training_code, config): | |
| ''' | |
| Conducts sequential training on a list of datasets using the selected trainer. | |
| Parameters: | |
| trainer : object | |
| An instance of a continual learning training class. | |
| datasets : list of str | |
| A list of dataset names to be used sequentially in training. | |
| training_code : str | |
| A unique identifier to distinguish this training run from others. | |
| config : dict | |
| Configuration for an experiment | |
| ''' | |
| self.datasets = datasets | |
| base_folder = f"./{config['method']}/" | |
| if not os.path.exists(base_folder): | |
| os.mkdir(base_folder) | |
| sequence_folder = "results_" + training_code | |
| if not os.path.exists(base_folder + sequence_folder): | |
| os.mkdir(base_folder + sequence_folder) | |
| experiment_name = "/" + str(self.config['seed']) + '_' + self.get_file_name() | |
| base_path = base_folder + sequence_folder + experiment_name | |
| if os.path.exists(base_path): | |
| logging.info(base_path) | |
| sys.exit('The experiment is already done!!!!!!!!') | |
| os.mkdir(base_path) | |
| for idx, dataset in enumerate(datasets): | |
| self.curr_dataset_idx = idx | |
| curr_base_path = base_path + '/' + '_'.join(datasets[:idx+1]) | |
| os.mkdir(curr_base_path) | |
| tr_loader, val_loader, te_loader = self.get_dataset(dataset, subset_count=self.config['subset_N'], subset_name=self.config['subset_name']) | |
| trainer.initialize_loader(tr_loader, val_loader, te_loader) | |
| trainer.save_path = curr_base_path | |
| trainer.train(epochs=self.config['epochs'] if idx > 0 else 2) | |
| self.task_idx += 1 | |
| self.test_on_all_datasets(base_path=curr_base_path, curr_dname=dataset) | |