[735bb5]: / src / training / base.py

Download this file

329 lines (277 with data), 11.0 kB

  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
152
153
154
155
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
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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# Base Dependencies
# -----------------
import numpy as np
from abc import ABC, abstractmethod
from os.path import join as pjoin
from pathlib import Path
from typing import Dict, Optional, Union, List
# Package Dependencies
# --------------------
from .config import PLExperimentConfig, ALExperimentConfig
from .utils import compute_metrics
# Local Dependencies
# ------------------
from models.relation_collection import RelationCollection
from utils import ddi_binary_relation
# 3rd-Party Dependencies
# ----------------------
import torch
from sklearn.metrics import accuracy_score
from sklearn.utils.class_weight import compute_class_weight
from torch.utils.data import Dataset
# Constants
# ---------
from constants import CHECKPOINTS_CACHE_DIR, DATASETS
# BaseTrainer
# -----------
class BaseTrainer(ABC):
def __init__(
self,
dataset: str,
train_dataset: Union[RelationCollection, Dataset],
test_dataset: Union[RelationCollection, Dataset],
relation_type: Optional[str] = None,
):
"""
Args:
dataset (str): name of the dataset, e.g., "n2c2".
train_dataset (Dataset): train split of the dataset.
test_dataset (Dataset): test split of the dataset.
relation_type (str, optional): relation type. Defaults to None.
Raises:
ValueError: if the name dataset provided is not supported
"""
if dataset not in DATASETS:
raise ValueError("unsupported dataset '{}'".format(dataset))
self.dataset = dataset
self.relation_type = relation_type
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# datasets
self.train_dataset = train_dataset
self.test_dataset = test_dataset
# get total number of instances, tokens and characters
if isinstance(self.train_dataset, RelationCollection):
self.n_instances = self.train_dataset.n_instances
self.n_tokens = self.train_dataset.n_tokens
self.n_characters = self.train_dataset.n_characters
else:
self.n_instances = len(self.train_dataset)
self.n_tokens = self.train_dataset["seq_length"].sum().item()
self.n_characters = self.train_dataset["char_length"].sum().item()
@property
@abstractmethod
def method_name(self) -> str:
pass
@property
@abstractmethod
def method_name_pretty(self) -> str:
pass
@property
def use_cuda(self) -> bool:
return self.device.type == "cuda"
@property
def metrics_average(self) -> str:
if self.dataset == "n2c2":
avg = "binary"
else:
avg = "micro"
return avg
@property
def num_classes(self) -> int:
if self.dataset == "n2c2":
n = 2
else:
n = 5
return n
@property
def pl_checkpoint_path(self):
"""Pasive Learning checkpoints directory path"""
directory = Path(
pjoin(CHECKPOINTS_CACHE_DIR, "pl", self.method_name, self.dataset)
)
if self.relation_type:
directory = Path(pjoin(directory, self.relation_type))
if not directory.is_dir():
directory.mkdir(parents=True, exist_ok=False)
return directory
@property
def al_checkpoint_path(self):
"""Active Learning checkpoints directory path"""
directory = Path(
pjoin(CHECKPOINTS_CACHE_DIR, "al", self.method_name, self.dataset)
)
if self.relation_type:
directory = Path(pjoin(directory, self.relation_type))
if not directory.is_dir():
directory.mkdir(parents=True, exist_ok=False)
return directory
# Instance Methods
# ----------------
@abstractmethod
def train_passive_learning(
self, config: PLExperimentConfig, verbose: bool = True, logging: bool = True
):
"""Trains the model using Passive Learning"""
raise NotImplementedError()
@abstractmethod
def train_active_learning(
self,
query_strategy: str,
config: ALExperimentConfig,
verbose: bool = True,
logging: bool = True,
):
"""Trains the model using Active Learning"""
raise NotImplementedError()
def print_info_passive_learning(self) -> None:
"""Prints information about the Passive Learning training process"""
print(f"\n\n**** {self.method_name_pretty} - Train Passive Learning ****")
print(f" - Dataset: {self.dataset}")
if self.relation_type:
print(f" - Relation type: {self.relation_type}")
def print_info_active_learning(
self, q_strategy: str, pool_size: int, init_q_size: int, q_size: int
) -> None:
"""Prints information about the Active Learning training process"""
print(f"\n\n**** {self.method_name_pretty} - Train Active Learning ****")
print(f" - Dataset: {self.dataset}")
if self.relation_type:
print(f" - Relation type: {self.relation_type}")
print(f" - Strategy = {q_strategy}")
print(f" - Pool size = {pool_size}")
print(f" - Initial query size = {init_q_size}")
print(f" - Query size = {q_size}")
def compute_class_weights(self, labels: list) -> Optional[torch.Tensor]:
"""Computes the class weights for the given labels"""
if len(np.unique(labels)) == self.num_classes:
class_weights = compute_class_weight(
class_weight="balanced",
classes=np.array(range(self.num_classes)),
y=labels,
)
class_weights = torch.from_numpy(class_weights).float().to(self.device)
else:
class_weights = None
return class_weights
def compute_init_q_size(self, config: ALExperimentConfig) -> int:
"""Computes the initial pool size for the given configuration"""
return min(
config.max_query_size,
int(round(config.initial_pool_perc * self.n_instances)),
)
def compute_q_size(self, config: ALExperimentConfig) -> int:
"""Computes the query size for the given configuration"""
return min(
config.max_query_size,
int(round(config.query_size_perc * self.n_instances)),
)
def compute_al_steps(self, config: ALExperimentConfig) -> int:
"""Computes the number of active learning steps for the given configuration"""
query_size = self.compute_q_size(config)
return int(round(self.n_instances * config.max_annotation / query_size)) - 1
def compute_step_accuracy(self, y_true: list, y_pred: list) -> float:
"""Computes the accuracy for the given step"""
return accuracy_score(y_true, y_pred, normalize=True)
def compute_metrics(
self,
y_true: list,
y_pred: list,
labels: Optional[List[str]] = None,
pos_label: int = 1,
) -> Dict:
"""Computes metrics
Args:
y_true (list): list of ground truths
y_pred (list): list of predicted values
labels (Optional[List[str]], optional): list of labels. Defaults to None.
pos_label (int, optional): positive label. Defaults to 1.
Returns:
Dict: precision, recall and F1-score
"""
if self.dataset == "n2c2":
metrics = self.compute_metrics_n2c2(y_true, y_pred, labels, pos_label)
else: # ddi
metrics = self.compute_metrics_ddi(y_true, y_pred, labels, pos_label)
return metrics
def compute_metrics_n2c2(
self,
y_true: list,
y_pred: list,
labels: Optional[List[str]] = None,
pos_label: int = 1,
):
metrics = {}
# accuracy
metrics["acc"] = accuracy_score(y_true=y_true, y_pred=y_pred, normalize=True)
avg_metrics = compute_metrics(
y_true=y_true, y_pred=y_pred, average=self.metrics_average, pos_label=1
)
for key, value in avg_metrics.items():
metrics[key] = value
return metrics
def compute_metrics_ddi(
self,
y_true: list,
y_pred: list,
labels: Optional[List[str]] = None,
pos_label: int = 1,
):
metrics = {}
# accuracy
metrics["acc"] = accuracy_score(y_true=y_true, y_pred=y_pred, normalize=True)
# macro
relevant_classes = [1, 2, 3, 4]
relevant_indices = np.isin(y_true, relevant_classes)
micro_metrics = compute_metrics(
y_true=y_true[relevant_indices],
y_pred=y_pred[relevant_indices],
average="micro",
)
for key, value in micro_metrics.items():
metrics[key] = value
# ddi: "Detection"
y_true_binary = list(map(lambda x: ddi_binary_relation(x), y_true))
y_pred_binary = list(map(lambda x: ddi_binary_relation(x), y_pred))
detection_metrics = compute_metrics(
y_true=y_true_binary, y_pred=y_pred_binary, average="binary"
)
for key, value in detection_metrics.items():
metrics["detect_" + key] = value
# ddi: per class
per_class_metrics = compute_metrics(
y_true=y_true, y_pred=y_pred, average=None, labels=[0, 1, 2, 3, 4]
)
for key, values in per_class_metrics.items():
for i, value in enumerate(values):
if labels:
class_name = labels[i]
else:
class_name = str(i)
metrics["class_" + key + "_" + class_name] = value
return metrics
# Class methods
# --------------
@classmethod
def print_al_iteration_metrics(cls, step: int, metrics: Dict[str, float]):
print("\n** Iteration {} - Metrics **".format(step), flush=True)
for key, value in metrics.items():
print(" - {} = {}".format(key, value), flush=True)
print("")
@classmethod
def print_val_metrics(cls, epoch: int, metrics: Dict[str, float]):
print("\n** Epoch {} - Validation set - Metrics **".format(epoch), flush=True)
for key, value in metrics.items():
print(" - {} = {}".format(key, value), flush=True)
print("")
@classmethod
def print_train_metrics(cls, metrics: Dict[str, float]):
print("\n** Training set - Metrics **", flush=True)
for key, value in metrics.items():
print(" - {} = {}".format(key, value), flush=True)
print("")
@classmethod
def print_test_metrics(cls, metrics: Dict[str, float]):
print("\n** Test set - Metrics **", flush=True)
for key, value in metrics.items():
print(" - {} = {}".format(key, value), flush=True)
print("")