run.py 18.4 KB
Newer Older
1
2
3
4
"""Brain Mapper Run File

Description:

5
6
7
8
9
    This file contains all the relevant functions for running BrainMapper.
    The network can be ran in one of these modes:
        - train
        - evaluate path
        - evaluate whole
10

11
    TODO: Might be worth adding some information on uncertaintiy estimation, later down the line
12

13
14
15
16
17
18
19
20
21
22
23
24
25
Usage:

    In order to run the network, in the terminal, the user needs to pass it relevant arguments:

        $ ./setup.sh
        $ source env/bin/activate
        $ python run.py --mode ...

    The arguments for mode are the following:

        mode=train # For training the model
        mode=evaluate-score # For evaluating the model score
        mode=evaluate-mapping # For evaluating the model mapping
26
27
        # For clearning the experiments and logs directories of the last experiment
        mode=clear-experiment
28
        mode=clear-all # For clearing all the files from the experiments and logs directories/
29
30
31

"""

32
import os
33
import shutil
34
35
import argparse
import logging
36
37
38
39
from settings import Settings

import torch
import torch.utils.data as data
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
40
import numpy as np
41
42

from solver import Solver
43
from BrainMapperUNet import BrainMapperUNet3D, BrainMapperResUNet3D, BrainMapperResUNet3Dshallow, BrainMapperCompResUNet3D
44
from utils.data_utils import get_datasets, data_test_train_validation_split, update_shuffling_flag, create_folder
45
46
import utils.data_evaluation_utils as evaluations
from utils.data_logging_utils import LogWriter
47
48
49
50
51

# Set the default floating point tensor type to FloatTensor

torch.set_default_tensor_type(torch.FloatTensor)

52

53
54
55
def load_data(data_parameters):
    """Dataset Loader

56
    This function loads the training and validation datasets.
57
58
59
60
61
62

    Args:
        data_parameters (dict): Dictionary containing relevant information for the datafiles.

    Returns:
        train_data (dataset object): Pytorch map-style dataset object, mapping indices to training data samples.
63
        validation_data (dataset object): Pytorch map-style dataset object, mapping indices to testing data samples.
64
65
66

    """
    print("Data is loading...")
67
    train_data, validation_data = get_datasets(data_parameters)
68
69
    print("Data has loaded!")
    print("Training dataset size is {}".format(len(train_data)))
70
    print("Validation dataset size is {}".format(len(validation_data)))
71

72
    return train_data, validation_data
73

74

75
76
def train(data_parameters, training_parameters, network_parameters, misc_parameters):
    """Training Function
77

78
    This function trains a given model using the provided training data.
79
    Currently, the data loaded is set to have multiple sub-processes.
80
81
    A high enough number of workers assures that CPU computations are efficiently managed, i.e. that the bottleneck is indeed the neural network's forward and backward operations on the GPU (and not data generation)
    Loader memory is also pinned, to speed up data transfer from CPU to GPU  by using the page-locked memory.
82
    Train data is also re-shuffled at each training epoch.
83
84

    Args:
85
86
87
88
89
        data_parameters (dict): Dictionary containing relevant information for the datafiles.

        training_parameters(dict): Dictionary containing relevant hyperparameters for training the network.
        training_parameters = {
            'training_batch_size': 5
90
            'validation_batch_size: 5
91
92
93
94
95
96
97
98
99
100
101
102
103
            'use_pre_trained': False
            'pre_trained_path': 'pre_trained/path'
            'experiment_name': 'experiment_name'
            'learning_rate': 1e-4
            'optimizer_beta': (0.9, 0.999)
            'optimizer_epsilon': 1e-8
            'optimizer_weigth_decay': 1e-5
            'number_of_epochs': 10
            'loss_log_period': 50
            'learning_rate_scheduler_step_size': 3
            'learning_rate_scheduler_gamma': 1e-1
            'use_last_checkpoint': True
            'final_model_output_file': 'path/to/model'
104
        }
105

106
        network_parameters (dict): Contains information relevant parameters
107

108
109
110
111
112
113
114
115
        misc_parameters (dict): Dictionary of aditional hyperparameters
        misc_parameters = {
            'save_model_directory': 'directory_name'
            'model_name': 'BrainMapper'
            'logs_directory': 'log-directory'
            'device': 1
            'experiments_directory': 'experiments-directory'
        }
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
    def _train_runner(data_parameters, training_parameters, network_parameters, misc_parameters):
        """Wrapper for the training operation

        This function wraps the training operation for the network

        Args:
            data_parameters (dict): Dictionary containing relevant information for the datafiles.
            training_parameters(dict): Dictionary containing relevant hyperparameters for training the network.
            network_parameters (dict): Contains information relevant parameters
            misc_parameters (dict): Dictionary of aditional hyperparameters

        """
        train_data, validation_data = load_data(data_parameters)

        train_loader = data.DataLoader(
            dataset=train_data,
            batch_size=training_parameters['training_batch_size'],
            shuffle=True,
            num_workers=4,
            pin_memory=True
        )

        validation_loader = data.DataLoader(
            dataset=validation_data,
            batch_size=training_parameters['validation_batch_size'],
            shuffle=False,
            num_workers=4,
            pin_memory=True
        )

        if training_parameters['use_pre_trained']:
            BrainMapperModel = torch.load(
                training_parameters['pre_trained_path'])
        else:
152
            BrainMapperModel = BrainMapperUNet3D(network_parameters)
153
154
            # BrainMapperModel = BrainMapperResUNet3D(network_parameters)
            # BrainMapperModel = BrainMapperResUNet3Dshallow(network_parameters)
155
            # BrainMapperModel = BrainMapperCompResUNet3D(network_parameters)
156

157
158
        BrainMapperModel.reset_parameters()

159
160
        optimizer = torch.optim.Adam

161
162
163
164
        solver = Solver(model=BrainMapperModel,
                        device=misc_parameters['device'],
                        number_of_classes=network_parameters['number_of_classes'],
                        experiment_name=training_parameters['experiment_name'],
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
165
                        optimizer=optimizer,
166
                        optimizer_arguments={'lr': training_parameters['learning_rate'],
167
168
169
170
                                             'betas': training_parameters['optimizer_beta'],
                                             'eps': training_parameters['optimizer_epsilon'],
                                             'weight_decay': training_parameters['optimizer_weigth_decay']
                                             },
171
172
173
174
175
176
177
178
179
                        model_name=misc_parameters['model_name'],
                        number_epochs=training_parameters['number_of_epochs'],
                        loss_log_period=training_parameters['loss_log_period'],
                        learning_rate_scheduler_step_size=training_parameters[
                            'learning_rate_scheduler_step_size'],
                        learning_rate_scheduler_gamma=training_parameters['learning_rate_scheduler_gamma'],
                        use_last_checkpoint=training_parameters['use_last_checkpoint'],
                        experiment_directory=misc_parameters['experiments_directory'],
                        logs_directory=misc_parameters['logs_directory'],
180
181
182
                        checkpoint_directory=misc_parameters['checkpoint_directory'],
                        save_model_directory=misc_parameters['save_model_directory'],
                        final_model_output_file=training_parameters['final_model_output_file']
183
184
185
186
                        )

        validation_loss = solver.train(train_loader, validation_loader)

187
        del train_data, validation_data, train_loader, validation_loader, BrainMapperModel, solver, optimizer
188
189
190
191
192
193
194
195
        torch.cuda.empty_cache()

        return validation_loss

    if data_parameters['k_fold'] is None:

        _ = _train_runner(data_parameters, training_parameters,
                          network_parameters, misc_parameters)
196

197
    else:
198
        print("Training initiated using K-fold Cross Validation!")
199
        k_fold_losses = []
200

201
        for k in range(data_parameters['k_fold']):
202

Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
203
            print("K-fold Number: {}".format(k+1))
204

205
            data_parameters['train_list'] = os.path.join(
206
                data_parameters['data_folder_name'], 'train' + str(k+1)+'.txt')
207
            data_parameters['validation_list'] = os.path.join(
208
209
210
                data_parameters['data_folder_name'], 'validation' + str(k+1)+'.txt')
            training_parameters['final_model_output_file'] = training_parameters['final_model_output_file'].replace(
                ".pth.tar", str(k+1)+".pth.tar")
211

212
            validation_loss = _train_runner(
213
                data_parameters, training_parameters, network_parameters, misc_parameters)
214

215
            k_fold_losses.append(validation_loss)
216

217
218
219
        for k in range(data_parameters['k_fold']):
            print("K-fold Number: {} Loss: {}".format(k+1, k_fold_losses[k]))
        print("K-fold Cross Validation Avearge Loss: {}".format(np.mean(k_fold_losses)))
220

Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
221

222
def evaluate_score(training_parameters, network_parameters, misc_parameters, evaluation_parameters):
223
224
225
226
227
228
229
230
231
232
233
    """Mapping Score Evaluator

    This function evaluates a given trained model by calculating the it's dice score prediction.

    Args:

        training_parameters(dict): Dictionary containing relevant hyperparameters for training the network.
        training_parameters = {
            'experiment_name': 'experiment_name'
        }

234
        network_parameters (dict): Contains information relevant parameters
235
236
237
        network_parameters= {
            'number_of_classes': 1
        }
238

239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
        misc_parameters (dict): Dictionary of aditional hyperparameters
        misc_parameters = {
            'logs_directory': 'log-directory'
            'device': 1
            'experiments_directory': 'experiments-directory'
        }

        evaluation_parameters (dict): Dictionary of parameters useful during evaluation.
        evaluation_parameters = {
            'trained_model_path': 'path/to/model'
            'data_directory': 'path/to/data'
            'targets_directory': 'path/to/targets'
            'data_list': 'path/to/datalist.txt/
            'orientation': 'coronal'
            'saved_predictions_directory': 'directory-of-saved-predictions'
        }
    """

257
    # TODO - NEED TO UPDATE THE DATA FUNCTIONS!
258

259
260
261
    logWriter = LogWriter(number_of_classes=network_parameters['number_of_classes'],
                          logs_directory=misc_parameters['logs_directory'],
                          experiment_name=training_parameters['experiment_name']
262
                          )
263

264
    prediction_output_path = os.path.join(misc_parameters['experiments_directory'],
265
266
267
268
                                          training_parameters['experiment_name'],
                                          evaluation_parameters['saved_predictions_directory']
                                          )

269
    _ = evaluations.evaluate_dice_score(trained_model_path=evaluation_parameters['trained_model_path'],
270
271
                                        number_of_classes=network_parameters['number_of_classes'],
                                        data_directory=evaluation_parameters['data_directory'],
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
272
273
274
275
276
277
                                        targets_directory=evaluation_parameters['targets_directory'],
                                        data_list=evaluation_parameters['data_list'],
                                        orientation=evaluation_parameters['orientation'],
                                        prediction_output_path=prediction_output_path,
                                        device=misc_parameters['device'],
                                        LogWriter=logWriter
278
                                        )
279
280
281

    logWriter.close()

282

283
284
def evaluate_mapping(mapping_evaluation_parameters):
    """Mapping Evaluator
285

286
287
288
289
290
    This function passes through the network an input and generates the rsfMRI outputs.

    Args:
        mapping_evaluation_parameters (dict): Dictionary of parameters useful during mapping evaluation.
        mapping_evaluation_parameters = {
291
            'trained_model_path': 'path/to/model'
292
293
294
295
296
297
298
299
300
            'data_directory': 'path/to/data'
            'data_list': 'path/to/datalist.txt/
            'prediction_output_path': 'directory-of-saved-predictions'
            'batch_size': 2
            'device': 0
            'exit_on_error': True
        }

    """
301
    trained_model_path = mapping_evaluation_parameters['trained_model_path']
302
    data_directory = mapping_evaluation_parameters['data_directory']
303
    mapping_data_file = mapping_evaluation_parameters['mapping_data_file']
304
305
    data_list = mapping_evaluation_parameters['data_list']
    prediction_output_path = mapping_evaluation_parameters['prediction_output_path']
306
    device = mapping_evaluation_parameters['device']
307
    exit_on_error = mapping_evaluation_parameters['exit_on_error']
308
309
310
    brain_mask_path = mapping_evaluation_parameters['brain_mask_path']
    mean_mask_path = mapping_evaluation_parameters['mean_mask_path']
    mean_reduction = mapping_evaluation_parameters['mean_reduction']
311
    scaling_factors = mapping_evaluation_parameters['scaling_factors']
312

313
    evaluations.evaluate_mapping(trained_model_path,
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
314
315
316
317
                                 data_directory,
                                 mapping_data_file,
                                 data_list,
                                 prediction_output_path,
318
319
320
                                 brain_mask_path,
                                 mean_mask_path,
                                 mean_reduction,
321
                                 scaling_factors,
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
322
323
324
                                 device=device,
                                 exit_on_error=exit_on_error)

325
326

def delete_files(folder):
327
    """ Clear Folder Contents
328

329
330
331
332
    Function which clears contents (like experiments or logs)

    Args:
        folder (str): Name of folders whose conents is to be deleted
333

334
    """
335

336
337
338
339
340
341
342
343
344
345
    for object_name in os.listdir(folder):
        file_path = os.path.join(folder, object_name)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as exception:
            print(exception)

346
347

if __name__ == '__main__':
348
    parser = argparse.ArgumentParser()
349
350
351
352
    parser.add_argument('--mode', '-m', required=True,
                        help='run mode, valid values are train or evaluate')
    parser.add_argument('--settings_path', '-sp', required=False,
                        help='optional argument, set path to settings_evaluation.ini')
353
354
355
356
357
358
359
360
361
362

    arguments = parser.parse_args()

    settings = Settings('settings.ini')
    data_parameters = settings['DATA']
    training_parameters = settings['TRAINING']
    network_parameters = settings['NETWORK']
    misc_parameters = settings['MISC']
    evaluation_parameters = settings['EVALUATION']

363
364
    # Here we shuffle the data!

365
366
367
368
    if data_parameters['data_split_flag'] == True:

        print('Data is shuffling... This could take a few minutes!')

369
370
    if data_parameters['data_split_flag'] == True:
        if data_parameters['use_data_file'] == True:
371
372
373
            data_test_train_validation_split(data_parameters['data_folder_name'],
                                             data_parameters['test_percentage'],
                                             data_parameters['subject_number'],
374
                                             data_directory=data_parameters['data_directory'],
375
376
377
                                             train_inputs=data_parameters['train_data_file'],
                                             train_targets=data_parameters['train_output_targets'],
                                             mean_mask_path=data_parameters['mean_mask_path'],
378
379
380
                                             data_file=data_parameters['data_file'],
                                             K_fold=data_parameters['k_fold']
                                             )
381
        else:
382
383
384
385
            data_test_train_validation_split(data_parameters['data_folder_name'],
                                             data_parameters['test_percentage'],
                                             data_parameters['subject_number'],
                                             data_directory=data_parameters['data_directory'],
386
387
388
                                             train_inputs=data_parameters['train_data_file'],
                                             train_targets=data_parameters['train_output_targets'],
                                             mean_mask_path=data_parameters['mean_mask_path'],
389
390
                                             K_fold=data_parameters['k_fold']
                                             )
391
        update_shuffling_flag('settings.ini')
392

393
394
        print('Data is shuffling... Complete!')

395
396
    if arguments.mode == 'train':
        train(data_parameters, training_parameters,
397
              network_parameters, misc_parameters)
398
399

    # NOTE: THE EVAL FUNCTIONS HAVE NOT YET BEEN DEBUGGED (16/04/20)
400
    # NOTE: THE EVAL-MAPPING FUNCTION HAS BEEN DEBUGGED (28/04/20)
401
402
403

    elif arguments.mode == 'evaluate-score':
        evaluate_score(training_parameters,
404
                       network_parameters, misc_parameters, evaluation_parameters)
405
406
407
408
    elif arguments.mode == 'evaluate-mapping':
        logging.basicConfig(filename='evaluate-mapping-error.log')
        if arguments.settings_path is not None:
            settings_evaluation = Settings(arguments.settings_path)
409
        else:
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
            settings_evaluation = Settings('settings_evaluation.ini')
        mapping_evaluation_parameters = settings_evaluation['MAPPING']
        evaluate_mapping(mapping_evaluation_parameters)
    elif arguments.mode == 'clear-experiments':
        shutil.rmtree(os.path.join(
            misc_parameters['experiments_directory'], training_parameters['experiment_name']))
        shutil.rmtree(os.path.join(
            misc_parameters['logs_directory'], training_parameters['experiment_name']))
        print('Cleared the current experiments and logs directory successfully!')
    elif arguments.mode == 'clear-everything':
        delete_files(misc_parameters['experiments_directory'])
        delete_files(misc_parameters['logs_directory'])
        print('Cleared the current experiments and logs directory successfully!')
    else:
        raise ValueError(
            'Invalid mode value! Only supports: train, evaluate-score, evaluate-mapping, clear-experiments and clear-everything')