run.py 11.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"""Brain Mapper Run File

Description:
-------------
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


Usage
-------------
In order to run the network, in the terminal, the user needs to pass it relevant arguments:
    - (TODO: ADD ARGUMENTS)

"""

19
20
import torch
from utils.data_utils import get_datasets
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
21
from BrainMapperUNet import BrainMapperUNet
22
import torch.utils.data as data
23
24
from solver import Solver
import os
25
26
from utils.data_logging_utils import LogWriter
import utils.data_evaluation_utils as evaluations
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# Set the default floating point tensor type to FloatTensor

torch.set_default_tensor_type(torch.FloatTensor)

def load_data(data_parameters):
    """Dataset Loader

    This function loads the training and testing datasets.
    TODO: Will need to define if all the training data is loaded as bulk or individually!

    Args:
        data_parameters (dict): Dictionary containing relevant information for the datafiles.
        data_parameters = {
41
42
43
44
45
            'data_directory': 'path/to/directory'
            'train_data_file': 'training_data'
            'train_output_targets': 'training_targets'
            'test_data_file': 'testing_data'
            'test_target_file': 'testing_targets'
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
        }

    Returns:
        train_data (dataset object): Pytorch map-style dataset object, mapping indices to training data samples.
        test_data (dataset object): Pytorch map-style dataset object, mapping indices to testing data samples.

    Raises:
        None

    """
    print("Data is loading...")
    train_data, test_data = get_datasets(data_parameters)
    print("Data has loaded!")
    print("Training dataset size is {}".format(len(train_data)))
    print("Testing dataset size is {}".format(len(test_data)))

    return train_data, test_data
63

64
65
def train(data_parameters, training_parameters, network_parameters, misc_parameters):
    """Training Function
66
    
67
    This function trains a given model using the provided training data.
68
69
70
71
72
73
    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:
74
75
76
77
78
79
80
        data_parameters (dict): Dictionary containing relevant information for the datafiles.
        data_parameters = {
            'data_directory': 'path/to/directory'
            'train_data_file': 'training_data'
            'train_output_targets': 'training_targets'
            'test_data_file': 'testing_data'
            'test_target_file': 'testing_targets'
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
81
        }
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

        training_parameters(dict): Dictionary containing relevant hyperparameters for training the network.
        training_parameters = {
            'training_batch_size': 5
            'test_batch_size: 5
            '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'
100
        }
101
102
103

        network_parameters (dict): Contains information relevant parameters 
        network_parameters= {
104
105
106
107
108
109
110
111
112
113
114
115
116
            'kernel_heigth': 5
            'kernel_width': 5
            'kernel_classification': 1
            'input_channels': 1
            'output_channels': 64
            'convolution_stride': 1
            'dropout': 0.2
            'pool_kernel_size': 2
            'pool_stride': 2
            'up_mode': 'upconv'
            'number_of_classes': 1
        }

117
118
119
120
121
122
123
124
125
        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'
        }

126
127
128
129
130
131
132
133
134
135
136
    Returns:
        None

    Raises:
        None
    """

    train_data, test_data = load_data(data_parameters)

    train_loader = data.DataLoader(
        dataset= train_data,
137
        batch_size= training_parameters['training_batch_size'],
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        shuffle= True,
        num_workers= 4,
        pin_memory= True
    )

    test_loader = data.DataLoader(
        dataset= test_data,
        batch_size= training_parameters['test_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:
        BrainMapperModel = BrainMapperUNet(network_parameters)

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
    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, test_loader)

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

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

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def evaluate_score(data_parameters, training_parameters, network_parameters, misc_parameters, evaluation_parameters):
    """Mapping Score Evaluator

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

    Args:
        data_parameters (dict): Dictionary containing relevant information for the datafiles.
        data_parameters = {
            'data_directory': 'path/to/directory'
            'train_data_file': 'training_data'
            'train_output_targets': 'training_targets'
            'test_data_file': 'testing_data'
            'test_target_file': 'testing_targets'
        }

        training_parameters(dict): Dictionary containing relevant hyperparameters for training the network.
        training_parameters = {
            'training_batch_size': 5
            'test_batch_size: 5
            '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'
        }

        network_parameters (dict): Contains information relevant parameters 
        network_parameters= {
            'kernel_heigth': 5
            'kernel_width': 5
            'kernel_classification': 1
            'input_channels': 1
            'output_channels': 64
            'convolution_stride': 1
            'dropout': 0.2
            'pool_kernel_size': 2
            'pool_stride': 2
            'up_mode': 'upconv'
            'number_of_classes': 1
        }
230

231
232
233
234
235
236
237
238
239
240
241
242
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
272
273
274
        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'
        }

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

    Returns:
        None

    Raises:
        None
    """

    logWriter = LogWriter(number_of_classes= network_parameters['number_of_classes'],
                        logs_directory= misc_parameters['logs_directory'], 
                        experiment_name= training_parameters['experiment_name']
                        )

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

    average_dice_score = 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'],
275
                                                        LogWriter= logWriter
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
                                                        )

    logWriter.close()

def evaluate_mapping():
    """
    Function which maps an entire volume
    """

    # Need to load all the relevant parameters

    # Assuming I perform the split on multiple axes, I need to load the different paths

    # After loading the different paths, evaluate:
    #   1) either on one path
    #   2) on two+ paths
292
293
294
    pass

def delete_files():
295
296
    """ Function which clears contents (like experiments or logs)
    """
297
298
299
300
    pass

if __name__ == '__main__':
    pass