data_logging_utils.py 8.45 KB
Newer Older
1
2
3
4
"""Data Logging Functions

Description:

5
    This folder contains several functions which, either on their own or included in larger pieces of software, perform data logging tasks.
6

7
8
9
10
11
Usage:

    To use content from this folder, import the functions and instantiate them as you wish to use them:

        from utils.data_logging_utils import function_name
12
13
14

"""

15
import os
16
import matplotlib
17
18
19
import matplotlib.pyplot as plt
import shutil
import logging
20
import numpy as np
21
import re
22
from textwrap import wrap
23
import torch
24
25
26
27
28

# The SummaryWriter class provides a high-level API to create an event file in a given directory and add summaries and events to it.
# More here: https://tensorboardx.readthedocs.io/en/latest/tensorboard.html
from tensorboardX import SummaryWriter

29
30
import utils.data_evaluation_utils as evaluation

31
32
plt.axis('scaled')

33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class LogWriter():

    """Log Writer class for the BrainMapper U-net.

    This class contains the pytorch implementation of the several logging functions required for the BrainMapper project.
    These functions are designed to keep track of progress during training, and also aid debugging.

    Args:
        number_of_classes (int): Number of classes
        logs_directory (str): Directory for outputing training logs
        experiment_name (str): Name of the experiment
        use_last_checkpoint (bool): Flag for loading the previous checkpoint
        labels (arr): Vector/Array of labels (if applicable)
        confusion_matrix_cmap (class): Colour Map to be used for the Conusion Matrix
    """

50
51
    def __init__(self, number_of_classes, logs_directory, experiment_name, use_last_checkpoint=False, labels=None, confusion_matrix_cmap=plt.cm.Blues):

52
        self.number_of_classes = number_of_classes
53
54
55
56
        training_logs_directory = os.path.join(
            logs_directory, experiment_name, "train")
        testing_logs_directory = os.path.join(
            logs_directory, experiment_name, "test")
57
58
59
60
61
62
63
64
65

        # If the logs directory exist, we clear their contents to allow new logs to be created
        if not use_last_checkpoint:
            if os.path.exists(training_logs_directory):
                shutil.rmtree(training_logs_directory)
            if os.path.exists(testing_logs_directory):
                shutil.rmtree(testing_logs_directory)

        self.log_writer = {
66
67
            'train': SummaryWriter(logdir=training_logs_directory),
            'test:': SummaryWriter(logdir=testing_logs_directory)
68
69
70
71
72
73
        }

        self.confusion_matrix_color_map = confusion_matrix_cmap

        self.current_iteration = 1

74
75
76
        if labels is not None:
            self.labels = self.labels_generator(labels)
        else:
77
            self.labels = ['rsfMRI']
78
79

        self.logger = logging.getLogger()
80
81
        file_handler = logging.FileHandler(
            "{}/{}.log".format(os.path.join(logs_directory, experiment_name), "console_logs"))
82
83
        self.logger.addHandler(file_handler)

84
85
86
87
88
89
90
91
92
93
94
    def labels_generator(self, labels):
        """ Label Generator Function

        This function processess an input array of labels.

        Args:
            labels (arr): Vector/Array of labels (if applicable)

        Returns:
            label_classes (list): List of processed labels
        """
95
96
97
98
99

        label_classes = []

        for label in labels:

100
101
102
103
            label_class = re.sub(
                r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', label)
            label_class = ['\n'.join(wrap(element, 40))
                           for element in label_class]
104
105
106
            label_classes.append(label_class)

        return label_classes
107

108
109
110
111
112
113
114
115
116
    def log(self, message):
        """Log function

        This function logs a message in the logger.

        Args:
            message (str): Message to be logged
        """

117
        self.logger.info(msg=message)
118

119
    def loss_per_iteration(self, loss_per_iteration, batch_index, iteration):
120
        """Log of loss / iteration
121

122
123
124
125
126
        This function records the loss for every iteration.

        Args:
            loss_per_iteration (torch.tensor): Value of loss for every iteration step
            batch_index (int): Index of current batch
127
            iteration (int): Current iteration value
128
129
        """

130
131
132
133
        print("Loss for Iteration {} is: {}".format(
            batch_index, loss_per_iteration))
        self.log_writer['train'].add_scalar(
            'loss / iteration', loss_per_iteration, iteration)
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

    def loss_per_epoch(self, losses, phase, epoch):
        """Log function

        This function records the loss for every epoch.

        Args:
            losses (list): Values of all the losses recorded during the training epoch
            phase (str): Current run mode or phase
            epoch (int): Current epoch value
        """

        if phase == 'train':
            loss = losses[-1]
        else:
            loss = np.mean(losses)

        print("Loss for Epoch {} of {} is: {}".format(epoch, phase, loss))
152
        self.log_writer[phase].add_scalar('loss / iteration', loss, epoch)
153

154
155
    # Currently, no confusion matrix is required
    # TODO: add a confusion matrix per epoch and confusion matrix plot functions if required
156

157
158
159
160
    def dice_score_per_epoch(self, phase, outputs, correct_labels, epoch):
        """Function calculating dice score for each epoch

        This function computes the dice score for each epoch.
161

162
        Args:
163
164
165
166
            phase (str): Current run mode or phase
            outputs (torch.tensor): Tensor of all the network outputs (Y-hat)
            correct_labels (torch.tensor): Output ground-truth labelled data (Y)
            epoch (int): Current epoch value
167
168
        """

169
170
171
        print("Dice Score is being calculated...", end='', flush=True)
        dice_score = evaluation.dice_score_calculator(
            outputs, correct_labels, self.number_of_classes)
172
        mean_dice_score = torch.mean(dice_score)
173
174
        self.plot_dice_score(
            dice_score, phase, plot_name='dice_score_per_epoch', title='Dice Score', epochs=epoch)
175
        print("Dice Score calculated successfully")
176
        return mean_dice_score.item()
177

178
    def plot_dice_score(self, dice_score, phase, plot_name, title, epochs=None):
179
        """Function plotting dice score for multiple epochs
180

181
        This function plots the dice score for each epoch.
182

183
184
185
186
187
188
189
190
        Args:
            dice_score (torch.tensor): Dice score value for each class
            phase (str): Current run mode or phase
            plot_name (str): Caption name for later refference
            title (str): Plot title
            epoch (int): Current epoch value
        """

191
        figure = matplotlib.figure.Figure()  # Might add some arguments here later
192
193
194
195
196
        ax = figure.add_subplot(1, 1, 1)
        ax.set_xlabel(title)
        ax.xaxis.set_label_position('top')
        ax.bar(np.arange(self.number_of_classes), dice_score)
        ax.set_xticks(np.arange(self.number_of_classes))
197
198
199
200
201
202

        if self.labels is None:
            pass
        else:
            ax.set_xticklabels(self.labels)
            ax.xaxis.tick_bottom()
203

204
        if epochs:
205
206
            self.log_writer[phase].add_figure(
                plot_name + '/' + phase, figure, global_step=epochs)
207
208
        else:
            self.log_writer[phase].add_figure(plot_name + '/' + phase, figure)
209

210
    # Currently, also no need for an evaluation box plot
211

212
213
214
215
216
217
218
219
220
221
222
223
    def sample_image_per_epoch(self, prediction, ground_truth, phase, epoch):
        """Function plotting mirrored images

        This function plots a predicted and a grond truth images side-by-side.

        Args:
            prediction (torch.tensor): Predicted image after passing throught the network
            ground_truth (torch.tensor): Labelled ground truth image
            phase (str): Current run mode or phase
            epoch (int): Current epoch value
        """

224
225
        print("Sample Image is being loaded...", end='', flush=True)
        figure, ax = plt.subplots(nrows=len(prediction), ncols=2)
226
227
228
229
230
231
232
233
234
235
236

        for i in range(len(prediction)):
            ax[i][0].imshow(prediction[i])
            ax[i][0].set_title("Predicted Image")
            ax[i][0].axis('off')

            ax[i][1].imshow(ground_truth[i])
            ax[i][1].set_title('Ground Truth Image')
            ax[i][1].axis('off')

        figure.set_tight_layout()
237
238
        self.log_writer[phase].add_figure(
            'sample_prediction/'+phase, figure, epoch)
239
240

        print("Sample Image successfully loaded!")
241
242

    def close(self):
Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
243
244
245
246
        """Close the log writer

        This function closes the two log writers.
        """
247

Andrei-Claudiu Roibu's avatar
Andrei-Claudiu Roibu committed
248
        self.log_writer['train'].close()
249
        self.log_writer['test'].close()