run.py 16.2 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
26
27
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
        mode=clear-experiment # For clearning the experiments and logs directories of the last experiment
        mode=clear-all # For clearing all the files from the experiments and logs directories/
28
29
30

"""

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

import torch
import torch.utils.data as data

from solver import Solver
41
from BrainMapperUNet import BrainMapperUNet3D
42
from utils.data_utils import get_datasets, data_test_train_validation_split, update_shuffling_flag, create_folder
43
44
import utils.data_evaluation_utils as evaluations
from utils.data_logging_utils import LogWriter
45
46
47
48
49

# Set the default floating point tensor type to FloatTensor

torch.set_default_tensor_type(torch.FloatTensor)

50

51
52
53
def load_data(data_parameters):
    """Dataset Loader

54
    This function loads the training and validation datasets.
55
56
57
58
59
60

    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.
61
        validation_data (dataset object): Pytorch map-style dataset object, mapping indices to testing data samples.
62
63
64

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

70
    return train_data, validation_data
71

72

73
74
def train(data_parameters, training_parameters, network_parameters, misc_parameters):
    """Training Function
75

76
    This function trains a given model using the provided training data.
77
78
79
80
81
82
    Currently, the data loaded is set to have multiple sub-processes. 
    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.
    Train data is also re-shuffled at each training epoch. 

    Args:
83
84
85
86
87
        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
88
            'validation_batch_size: 5
89
90
91
92
93
94
95
96
97
98
99
100
101
            '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'
102
        }
103
104

        network_parameters (dict): Contains information relevant parameters 
105

106
107
108
109
110
111
112
113
        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'
        }
114
115
    """

116
    train_data, validation_data = load_data(data_parameters)
117
118

    train_loader = data.DataLoader(
119
120
121
122
123
        dataset=train_data,
        batch_size=training_parameters['training_batch_size'],
        shuffle=True,
        num_workers=4,
        pin_memory=True
124
125
    )

126
127
128
    validation_loader = data.DataLoader(
        dataset=validation_data,
        batch_size=training_parameters['validation_batch_size'],
129
130
131
        shuffle=False,
        num_workers=4,
        pin_memory=True
132
133
134
    )

    if training_parameters['use_pre_trained']:
135
        BrainMapperModel = torch.load(training_parameters['pre_trained_path'])
136
    else:
137
138
        BrainMapperModel = BrainMapperUNet3D(network_parameters)

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
    solver = Solver(model=BrainMapperModel,
                    device=misc_parameters['device'],
                    number_of_classes=network_parameters['number_of_classes'],
                    experiment_name=training_parameters['experiment_name'],
                    optimizer_arguments={'lr': training_parameters['learning_rate'],
                                         'betas': training_parameters['optimizer_beta'],
                                         'eps': training_parameters['optimizer_epsilon'],
                                         'weight_decay': training_parameters['optimizer_weigth_decay']
                                         },
                    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']
                    )

    solver.train(train_loader, validation_loader)

    model_output_path = os.path.join(
        misc_parameters['save_model_directory'], training_parameters['final_model_output_file'])

    create_folder(misc_parameters['save_model_directory'])

    BrainMapperModel.save(model_output_path)

    print("Final Model Saved in: {}".format(model_output_path))
169

170
171

def evaluate_score(training_parameters, network_parameters, misc_parameters, evaluation_parameters):
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    """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'
        }

        network_parameters (dict): Contains information relevant parameters 
        network_parameters= {
            'number_of_classes': 1
        }
187

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
        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'
        }
    """

206
    # TODO - NEED TO UPDATE THE DATA FUNCTIONS!
207

208
209
210
211
    logWriter = LogWriter(number_of_classes=network_parameters['number_of_classes'],
                          logs_directory=misc_parameters['logs_directory'],
                          experiment_name=training_parameters['experiment_name']
                          )
212
213

    prediction_output_path = os.path.join(misc_parameters['experiments_directory'],
214
215
216
217
                                          training_parameters['experiment_name'],
                                          evaluation_parameters['saved_predictions_directory']
                                          )

218
219
220
221
222
223
224
225
226
227
228
    _ = evaluations.evaluate_dice_score(trained_model_path=evaluation_parameters['trained_model_path'],
                                        number_of_classes=network_parameters['number_of_classes'],
                                        data_directory=evaluation_parameters['data_directory'],
                                        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
    )
229
230
231

    logWriter.close()

232

233
234
def evaluate_mapping(mapping_evaluation_parameters):
    """Mapping Evaluator
235

236
237
    This function passes through the network an input and generates the rsfMRI outputs.
    This function allows the user to either use one or two or three paths.
238

239
240
241
242
    The convention for the different model paths is as follows:
    - model1: coronal
    - model2: axial
    - model3: saggital
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
    However, this convention can be changed either bellow or the settings file.

    Args:
        mapping_evaluation_parameters (dict): Dictionary of parameters useful during mapping evaluation.
        mapping_evaluation_parameters = {
            'trained_model1_path': 'path/to/model1'
            'trained_model2_path': 'path/to/model2'
            'trained_model3_path': 'path/to/model3'
            'data_directory': 'path/to/data'
            'data_list': 'path/to/datalist.txt/
            'orientation1': 'coronal'
            'orientation2': 'axial'
            'orientation3': 'sagittal'
            'prediction_output_path': 'directory-of-saved-predictions'
            'batch_size': 2
            'device': 0
            'exit_on_error': True
            'number_of_paths': 3
        }

    """
    trained_model1_path = mapping_evaluation_parameters['trained_model1_path']
    trained_model2_path = mapping_evaluation_parameters['trained_model2_path']
    trained_model3_path = mapping_evaluation_parameters['trained_model3_path']
    data_directory = mapping_evaluation_parameters['data_directory']
    data_list = mapping_evaluation_parameters['data_list']
    orientation1 = mapping_evaluation_parameters['orientation1']
    orientation2 = mapping_evaluation_parameters['orientation2']
272
    orientation3 = mapping_evaluation_parameters['orientation3']
273
274
    prediction_output_path = mapping_evaluation_parameters['prediction_output_path']
    batch_size = mapping_evaluation_parameters['batch_size']
275
    device = mapping_evaluation_parameters['device']
276
277
278
    exit_on_error = mapping_evaluation_parameters['exit_on_error']

    if mapping_evaluation_parameters['number_of_paths'] == 1:
279
280
281
282
283
284
285
286
        evaluations.evaluate_single_path(trained_model1_path,
                                         data_directory,
                                         data_list,
                                         orientation1,
                                         prediction_output_path,
                                         batch_size,
                                         device=device,
                                         exit_on_error=exit_on_error)
287
288
    elif mapping_evaluation_parameters['number_of_paths'] == 2:
        evaluations.evaluate_two_paths(trained_model1_path,
289
290
291
292
293
294
295
296
297
                                       trained_model2_path,
                                       data_directory,
                                       data_list,
                                       orientation1,
                                       orientation2,
                                       prediction_output_path,
                                       batch_size,
                                       device=device,
                                       exit_on_error=exit_on_error)
298
299
    elif mapping_evaluation_parameters['number_of_paths'] == 3:
        evaluations.evaluate_all_paths(trained_model1_path,
300
301
302
303
304
305
306
307
308
309
310
311
312
313
                                       trained_model2_path,
                                       trained_model3_path,
                                       data_directory,
                                       data_list,
                                       orientation1,
                                       orientation2,
                                       orientation3,
                                       prediction_output_path,
                                       batch_size,
                                       device=device,
                                       exit_on_error=exit_on_error)


def delete_files(folder):
314
    """ Clear Folder Contents
315

316
317
318
319
    Function which clears contents (like experiments or logs)

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

321
322
    Returns:
        None
323

324
325
    Raises:
        Exception: Any error
326
    """
327

328
329
330
331
332
333
334
335
336
337
    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)

338
339

if __name__ == '__main__':
340
    parser = argparse.ArgumentParser()
341
342
343
344
    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')
345
346
347
348
349
350
351
352
353
354

    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']

355
356
    data_shuffling_flag = data_parameters['data_split_flag']

357
358
    if data_shuffling_flag == True:
        # Here we shuffle the data!
359
360
        data_test_train_validation_split(
            data_parameters['data_directory'], data_parameters['train_percentage'], data_parameters['validation_percentage'])
361
362
363
        update_shuffling_flag('settings.ini')
        # TODO: This might also be a very good point to add cross-validation later
    else:
364

365
366
        if arguments.mode == 'train':
            train(data_parameters, training_parameters,
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
                  network_parameters, misc_parameters)

        # NOTE: THE EVAL FUNCTIONS HAVE NOT YET BEEN DEBUGGED (16/04/20)

        elif arguments.mode == 'evaluate-score':
            evaluate_score(training_parameters,
                           network_parameters, misc_parameters, evaluation_parameters)
        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)
            else:
                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')