data_logging_utils.py 4.95 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
"""Data Logging Functions

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

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

"""

15
16
17
18
import os
import matplotlib.pyplot as plt
import shutil
import logging
19
import numpy as np
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

# 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

plt.axis('scaled')

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

    Returns:
        None

    Raises:
        None
    """

    def __init__(self, number_of_classes, logs_directory, experiment_name, use_last_checkpoint=False, labels=None, confusion_matrix_cmap= plt.cm.Blues):
        
        self.number_of_classes = number_of_classes
        training_logs_directory = os.path.join(logs_directory, experiment_name, "train")
        testing_logs_directory = os.path.join(logs_directory, experiment_name, "test")

        # 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 = {
            'train': SummaryWriter(logdir= training_logs_directory),
            'test:': SummaryWriter(logdir= testing_logs_directory)
        }

        self.confusion_matrix_color_map = confusion_matrix_cmap

        self.current_iteration = 1

        self.labels = self.labels_generator(labels)

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

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    def log(self, message):
        """Log function

        This function logs a message in the logger.

        Args:
            message (str): Message to be logged

        Returns:
            None

        Raises:
            None
        """

        self.logger.info(msg= message)
93

94
95
    def loss_per_iteration(self, loss_per_iteration, batch_index, current_iteration):
        """Log of loss / iteration
96

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
        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
            current_iteartion (int): Current iteration value

        Returns:
            None

        Raises:
            None
        """

        print("Loss for Iteration {} is: {}".format(batch_index, loss_per_iteration))
        self.log_writer['train'].add_scalar(tag= 'loss / iteration', loss_per_iteration, current_iteration)

    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

        Returns:
            None

        Raises:
            None
        """

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

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

    def confusion_matrix_per_epoch(self):
140
141
142
        """Log function

        This function logs a message in the logger.
143

144
145
146
147
148
149
150
151
152
153
154
155
        Args:
            message (str): Message to be logged

        Returns:
            None

        Raises:
            None
        """


        
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    def plot_confusion_matrix(self):
        pass

    def dice_score_per_epoch(self):
        pass

    def plot_dice_score(self):
        pass

    def plot_evaluation_box(self):
        pass

    def sample_image_per_epoch(self):
        pass

    def graph(self):
        pass

    def close(self):
        pass

    def labels_generator(self):
178
        return pass