File size: 4,773 Bytes
232c308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import os
import torch
import wandb
from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score, confusion_matrix

def save_model(model, config):
    """
    Saves the given model to the specified directory with a filename that includes
    the model's name, F1 score, and training step.

    Args:
        model (torch.nn.Module): The model to be saved.
        config (dict): Configuration dictionary containing:
            - 'Test_F1' (float): The F1 score from testing.
            - 'name' (str): The base name for the model file.
            - 'global_step' (int): The current training step.
            - 'save_dir' (str): Directory where the model will be saved.
    """
    # Convert F1 score to percentage
    f1_percentage = config['Test_F1'] * 100

    # Create a filename with model name, F1 score, and training step
    filename = "{}_F1_{:.2f}_step_{}.pkl".format(
        config['name'],
        f1_percentage,
        config['global_step']
    )

    # Construct the full path for saving the model
    model_save_path = os.path.join(config['save_dir'], filename)

    # Save the model state_dict using PyTorch's save function
    torch.save({
        'global_step': config['global_step'],
        'model_state_dict': model.state_dict(),
        'Test_F1': config['Test_F1']
    }, model_save_path)
    print("Saved model to {}".format(model_save_path))
    
    if wandb.run is not None:
        wandb.save(model_save_path)


def get_learning_rate(optimizer):
    """
    Retrieves the current learning rate from the optimizer.

    Args:
        optimizer (torch.optim.Optimizer): The optimizer from which to extract the learning rate.

    Returns:
        float: The current learning rate.

    Raises:
        ValueError: If the optimizer has no parameter groups.
    """
    if len(optimizer.param_groups) > 0:
        # Return the learning rate of the first parameter group
        return optimizer.param_groups[0]['lr']
    else:
        raise ValueError('No trainable parameters found in the optimizer.')


def move_tensor_to_device(tensor, use_gpu=False):
    """
    Moves a tensor to GPU or CPU based on the specified flag.

    Args:
        tensor (torch.Tensor): The tensor to move.
        use_gpu (bool, optional): If True, move the tensor to GPU. Otherwise, move to CPU. Defaults to False.

    Returns:
        torch.Tensor: The tensor on the specified device.
    """
    if use_gpu:
        # Move tensor to GPU asynchronously
        return tensor.cuda(non_blocking=True)
    else:
        # Move tensor to CPU
        return tensor.cpu()


def calculate_classification_metrics(predictions, targets, average_method='macro'):
    """
    Calculates various classification metrics based on predictions and true targets.

    Args:
        predictions (array-like): Predicted class labels.
        targets (array-like): True class labels.
        average_method (str, optional): Method to average the metrics. Defaults to 'macro'.

    Returns:
        tuple: A tuple containing:
            - accuracy (float): Accuracy score.
            - f1 (float): F1 score.
            - precision (float): Precision score.
            - recall (float): Recall score.
            - confusion_mat (numpy.ndarray): Confusion matrix.
    """
    # Compute the confusion matrix
    confusion_mat = confusion_matrix(targets, predictions)
    confusion_mat = confusion_mat.astype('int')

    # Calculate F1 score
    f1 = f1_score(targets, predictions, average=average_method)

    # Calculate precision score
    precision = precision_score(targets, predictions, average=average_method)

    # Calculate recall score
    recall = recall_score(targets, predictions, average=average_method)

    # Calculate accuracy score
    accuracy = accuracy_score(targets, predictions)

    return accuracy, f1, precision, recall, confusion_mat


class AverageMeter:
    """
    Computes and stores the average and current value of a metric.
    Useful for tracking metrics like loss or accuracy during training.
    """

    def __init__(self):
        """
        Initializes the AverageMeter by resetting all metrics.
        """
        self.reset()

    def reset(self):
        """
        Resets all metrics to their initial state.
        """
        self.current = 0
        self.average = 0
        self.total = 0
        self.count = 0

    def update(self, value, n=1):
        """
        Updates the metrics with a new value.

        Args:
            value (float): The new value to incorporate.
            n (int, optional): The number of occurrences of the value. Defaults to 1.
        """
        self.current = value
        self.total += value * n
        self.count += n
        self.average = self.total / self.count