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| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytorch_lightning as pl
|
| 6 |
+
import torchmetrics
|
| 7 |
+
from torchmetrics.classification import F1Score, AUROC
|
| 8 |
+
import torch
|
| 9 |
+
import transformers
|
| 10 |
+
from transformers import AutoModel
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, '..')
|
| 17 |
+
|
| 18 |
+
from . import utils
|
| 19 |
+
from . import metrics
|
| 20 |
+
|
| 21 |
+
logging.basicConfig(
|
| 22 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 23 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 24 |
+
level=logging.INFO)
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ProtoModule(pl.LightningModule):
|
| 30 |
+
|
| 31 |
+
def __init__(self,
|
| 32 |
+
pretrained_model,
|
| 33 |
+
num_classes,
|
| 34 |
+
label_order_path,
|
| 35 |
+
use_sigmoid=False,
|
| 36 |
+
use_cuda=True,
|
| 37 |
+
lr_prototypes=5e-2,
|
| 38 |
+
lr_features=2e-6,
|
| 39 |
+
lr_others=2e-2,
|
| 40 |
+
num_training_steps=5000,
|
| 41 |
+
num_warmup_steps=1000,
|
| 42 |
+
loss='BCE',
|
| 43 |
+
save_dir='output',
|
| 44 |
+
use_attention=True,
|
| 45 |
+
dot_product=False,
|
| 46 |
+
normalize=None,
|
| 47 |
+
final_layer=False,
|
| 48 |
+
reduce_hidden_size=None,
|
| 49 |
+
use_prototype_loss=False,
|
| 50 |
+
prototype_vector_path=None,
|
| 51 |
+
attention_vector_path=None,
|
| 52 |
+
eval_buckets=None,
|
| 53 |
+
seed=7
|
| 54 |
+
):
|
| 55 |
+
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.label_order_path = label_order_path
|
| 58 |
+
|
| 59 |
+
self.loss = loss
|
| 60 |
+
self.normalize = normalize
|
| 61 |
+
self.lr_features = lr_features
|
| 62 |
+
self.lr_prototypes = lr_prototypes
|
| 63 |
+
self.lr_others = lr_others
|
| 64 |
+
self.use_sigmoid = use_sigmoid
|
| 65 |
+
self.use_cuda = use_cuda
|
| 66 |
+
|
| 67 |
+
self.use_attention = use_attention
|
| 68 |
+
self.dot_product = dot_product
|
| 69 |
+
|
| 70 |
+
self.num_training_steps = num_training_steps
|
| 71 |
+
self.num_warmup_steps = num_warmup_steps
|
| 72 |
+
self.save_dir = save_dir
|
| 73 |
+
self.num_classes = num_classes
|
| 74 |
+
|
| 75 |
+
self.final_layer = final_layer
|
| 76 |
+
self.use_prototype_loss = use_prototype_loss
|
| 77 |
+
self.prototype_vector_path = prototype_vector_path
|
| 78 |
+
self.eval_buckets = eval_buckets
|
| 79 |
+
|
| 80 |
+
# ARCHITECTURE SETUP #
|
| 81 |
+
|
| 82 |
+
from pytorch_lightning import seed_everything
|
| 83 |
+
seed_everything(seed)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# define distance measure
|
| 87 |
+
self.pairwise_dist = nn.PairwiseDistance(p=2)
|
| 88 |
+
|
| 89 |
+
# load BERT
|
| 90 |
+
self.bert = AutoModel.from_pretrained(pretrained_model)
|
| 91 |
+
|
| 92 |
+
# freeze BERT layers if lr_features == 0
|
| 93 |
+
if lr_features == 0:
|
| 94 |
+
for param in self.bert.parameters():
|
| 95 |
+
param.requires_grad = False
|
| 96 |
+
|
| 97 |
+
# define hidden size
|
| 98 |
+
self.hidden_size = self.bert.config.hidden_size
|
| 99 |
+
self.reduce_hidden_size = reduce_hidden_size is not None
|
| 100 |
+
if self.reduce_hidden_size:
|
| 101 |
+
self.reduce_hidden_size = True
|
| 102 |
+
self.bert_hidden_size = self.bert.config.hidden_size
|
| 103 |
+
self.hidden_size = reduce_hidden_size
|
| 104 |
+
|
| 105 |
+
# initialize linear layer for dim reduction
|
| 106 |
+
# reset the seed to make sure linear layer is the same as in preprocessing
|
| 107 |
+
pl.utilities.seed.seed_everything(seed=seed)
|
| 108 |
+
self.linear = nn.Linear(self.bert_hidden_size, self.hidden_size)
|
| 109 |
+
|
| 110 |
+
# load prototype vectors
|
| 111 |
+
if prototype_vector_path is not None:
|
| 112 |
+
prototype_vectors, self.num_prototypes_per_class = self.load_prototype_vectors(prototype_vector_path)
|
| 113 |
+
else:
|
| 114 |
+
prototype_vectors = torch.rand((self.num_classes, self.hidden_size))
|
| 115 |
+
self.num_prototypes_per_class = torch.ones(self.num_classes)
|
| 116 |
+
self.prototype_vectors = nn.Parameter(prototype_vectors, requires_grad=True)
|
| 117 |
+
|
| 118 |
+
self.prototype_to_class_map = self.build_prototype_to_class_mapping(self.num_prototypes_per_class)
|
| 119 |
+
self.num_prototypes = self.prototype_to_class_map.shape[0]
|
| 120 |
+
|
| 121 |
+
# load attention vectors
|
| 122 |
+
if attention_vector_path is not None:
|
| 123 |
+
attention_vectors = self.load_attention_vectors(attention_vector_path)
|
| 124 |
+
else:
|
| 125 |
+
attention_vectors = torch.rand((self.num_classes, self.hidden_size))
|
| 126 |
+
self.attention_vectors = nn.Parameter(attention_vectors, requires_grad=True)
|
| 127 |
+
|
| 128 |
+
if self.final_layer:
|
| 129 |
+
self.final_linear = self.build_final_layer()
|
| 130 |
+
|
| 131 |
+
# EVALUATION SETUP #
|
| 132 |
+
|
| 133 |
+
# setup metrics
|
| 134 |
+
self.train_metrics = self.setup_metrics()
|
| 135 |
+
|
| 136 |
+
# initialise metrics for evaluation on test set
|
| 137 |
+
# self.all_metrics = {**self.train_metrics, **self.setup_extensive_metrics()}
|
| 138 |
+
self.all_metrics = {**self.train_metrics}
|
| 139 |
+
|
| 140 |
+
self.save_hyperparameters()
|
| 141 |
+
logger.info("Finished init.")
|
| 142 |
+
|
| 143 |
+
def build_final_layer(self):
|
| 144 |
+
prototype_identity_matrix = torch.zeros(self.num_prototypes, self.num_classes)
|
| 145 |
+
|
| 146 |
+
for j in range(len(prototype_identity_matrix)):
|
| 147 |
+
prototype_identity_matrix[j, self.prototype_to_class_map[j]] = 1.0 / self.num_prototypes_per_class[
|
| 148 |
+
self.prototype_to_class_map[j]]
|
| 149 |
+
|
| 150 |
+
if self.use_cuda:
|
| 151 |
+
prototype_identity_matrix = prototype_identity_matrix.cuda()
|
| 152 |
+
|
| 153 |
+
return nn.Parameter(prototype_identity_matrix.double(), requires_grad=True)
|
| 154 |
+
|
| 155 |
+
def load_prototype_vectors(self, prototypes_per_class_path):
|
| 156 |
+
prototypes_per_class = torch.load(prototypes_per_class_path)
|
| 157 |
+
|
| 158 |
+
# store the number of prototypes for each class
|
| 159 |
+
num_prototypes_per_class = torch.tensor([len(prototypes_per_class[key]) for key in prototypes_per_class])
|
| 160 |
+
|
| 161 |
+
with open(self.label_order_path) as label_order_file:
|
| 162 |
+
ordered_labels = label_order_file.read().split(" ")
|
| 163 |
+
|
| 164 |
+
# get dimension from any of the stored vectors
|
| 165 |
+
vector_dim = len(list(prototypes_per_class.values())[0][0])
|
| 166 |
+
|
| 167 |
+
stacked_prototypes_per_class = [
|
| 168 |
+
prototypes_per_class[label] if label in prototypes_per_class else [np.random.rand(vector_dim)]
|
| 169 |
+
for label in ordered_labels]
|
| 170 |
+
|
| 171 |
+
prototype_matrix = torch.tensor([val for sublist in stacked_prototypes_per_class for val in sublist])
|
| 172 |
+
|
| 173 |
+
return prototype_matrix, num_prototypes_per_class
|
| 174 |
+
|
| 175 |
+
def build_prototype_to_class_mapping(self, num_prototypes_per_class):
|
| 176 |
+
return torch.arange(num_prototypes_per_class.shape[0]).repeat_interleave(num_prototypes_per_class.long(),
|
| 177 |
+
dim=0)
|
| 178 |
+
|
| 179 |
+
def load_attention_vectors(self, attention_vectors_path):
|
| 180 |
+
attention_vectors = torch.load(attention_vectors_path, map_location=self.device)
|
| 181 |
+
|
| 182 |
+
return attention_vectors
|
| 183 |
+
|
| 184 |
+
def setup_metrics(self):
|
| 185 |
+
self.f1 = F1Score(task="multilabel", num_labels=self.num_classes, threshold=0.269)
|
| 186 |
+
self.auroc_micro = AUROC(task="multilabel", num_labels=self.num_classes, average="micro")
|
| 187 |
+
self.auroc_macro = AUROC(task="multilabel", num_labels=self.num_classes, average="macro")
|
| 188 |
+
|
| 189 |
+
return {"auroc_micro": self.auroc_micro,
|
| 190 |
+
"auroc_macro": self.auroc_macro,
|
| 191 |
+
"f1": self.f1}
|
| 192 |
+
|
| 193 |
+
def setup_extensive_metrics(self):
|
| 194 |
+
self.pr_curve = metrics.PR_AUC(num_classes=self.num_classes)
|
| 195 |
+
|
| 196 |
+
extensive_metrics = {"pr_curve": self.pr_curve}
|
| 197 |
+
|
| 198 |
+
if self.eval_buckets:
|
| 199 |
+
buckets = self.eval_buckets
|
| 200 |
+
|
| 201 |
+
self.prcurve_0 = metrics.PR_AUCPerBucket(bucket=buckets["<5"],
|
| 202 |
+
num_classes=self.num_classes,
|
| 203 |
+
compute_on_step=False)
|
| 204 |
+
|
| 205 |
+
self.prcurve_1 = metrics.PR_AUCPerBucket(bucket=buckets["5-10"],
|
| 206 |
+
num_classes=self.num_classes,
|
| 207 |
+
compute_on_step=False)
|
| 208 |
+
|
| 209 |
+
self.prcurve_2 = metrics.PR_AUCPerBucket(bucket=buckets["11-50"],
|
| 210 |
+
num_classes=self.num_classes,
|
| 211 |
+
compute_on_step=False)
|
| 212 |
+
|
| 213 |
+
self.prcurve_3 = metrics.PR_AUCPerBucket(bucket=buckets["51-100"],
|
| 214 |
+
num_classes=self.num_classes,
|
| 215 |
+
compute_on_step=False)
|
| 216 |
+
|
| 217 |
+
self.prcurve_4 = metrics.PR_AUCPerBucket(bucket=buckets["101-1K"],
|
| 218 |
+
num_classes=self.num_classes,
|
| 219 |
+
compute_on_step=False)
|
| 220 |
+
|
| 221 |
+
self.prcurve_5 = metrics.PR_AUCPerBucket(bucket=buckets[">1K"],
|
| 222 |
+
num_classes=self.num_classes,
|
| 223 |
+
compute_on_step=False)
|
| 224 |
+
|
| 225 |
+
self.auroc_macro_0 = metrics.FilteredAUROCPerBucket(bucket=buckets["<5"],
|
| 226 |
+
num_classes=self.num_classes,
|
| 227 |
+
compute_on_step=False,
|
| 228 |
+
average="macro")
|
| 229 |
+
self.auroc_macro_1 = metrics.FilteredAUROCPerBucket(bucket=buckets["5-10"],
|
| 230 |
+
num_classes=self.num_classes,
|
| 231 |
+
compute_on_step=False,
|
| 232 |
+
average="macro")
|
| 233 |
+
self.auroc_macro_2 = metrics.FilteredAUROCPerBucket(bucket=buckets["11-50"],
|
| 234 |
+
num_classes=self.num_classes,
|
| 235 |
+
compute_on_step=False,
|
| 236 |
+
average="macro")
|
| 237 |
+
self.auroc_macro_3 = metrics.FilteredAUROCPerBucket(bucket=buckets["51-100"],
|
| 238 |
+
num_classes=self.num_classes,
|
| 239 |
+
compute_on_step=False,
|
| 240 |
+
average="macro")
|
| 241 |
+
self.auroc_macro_4 = metrics.FilteredAUROCPerBucket(bucket=buckets["101-1K"],
|
| 242 |
+
num_classes=self.num_classes,
|
| 243 |
+
compute_on_step=False,
|
| 244 |
+
average="macro")
|
| 245 |
+
self.auroc_macro_5 = metrics.FilteredAUROCPerBucket(bucket=buckets[">1K"],
|
| 246 |
+
num_classes=self.num_classes,
|
| 247 |
+
compute_on_step=False,
|
| 248 |
+
average="macro")
|
| 249 |
+
|
| 250 |
+
bucket_metrics = {"pr_curve_0": self.prcurve_0,
|
| 251 |
+
"pr_curve_1": self.prcurve_1,
|
| 252 |
+
"pr_curve_2": self.prcurve_2,
|
| 253 |
+
"pr_curve_3": self.prcurve_3,
|
| 254 |
+
"pr_curve_4": self.prcurve_4,
|
| 255 |
+
"pr_curve_5": self.prcurve_5,
|
| 256 |
+
"auroc_macro_0": self.auroc_macro_0,
|
| 257 |
+
"auroc_macro_1": self.auroc_macro_1,
|
| 258 |
+
"auroc_macro_2": self.auroc_macro_2,
|
| 259 |
+
"auroc_macro_3": self.auroc_macro_3,
|
| 260 |
+
"auroc_macro_4": self.auroc_macro_4,
|
| 261 |
+
"auroc_macro_5": self.auroc_macro_5}
|
| 262 |
+
|
| 263 |
+
extensive_metrics = {**extensive_metrics, **bucket_metrics}
|
| 264 |
+
|
| 265 |
+
return extensive_metrics
|
| 266 |
+
|
| 267 |
+
def configure_optimizers(self):
|
| 268 |
+
joint_optimizer_specs = [{'params': self.prototype_vectors, 'lr': self.lr_prototypes},
|
| 269 |
+
{'params': self.attention_vectors, 'lr': self.lr_others},
|
| 270 |
+
{'params': self.bert.parameters(), 'lr': self.lr_features}]
|
| 271 |
+
|
| 272 |
+
if self.final_layer:
|
| 273 |
+
joint_optimizer_specs.append({'params': self.final_linear, 'lr': self.lr_prototypes})
|
| 274 |
+
|
| 275 |
+
if self.reduce_hidden_size:
|
| 276 |
+
joint_optimizer_specs.append({'params': self.linear.parameters(), 'lr': self.lr_others})
|
| 277 |
+
|
| 278 |
+
optimizer = torch.optim.AdamW(joint_optimizer_specs)
|
| 279 |
+
|
| 280 |
+
lr_scheduler = transformers.get_linear_schedule_with_warmup(
|
| 281 |
+
optimizer=optimizer,
|
| 282 |
+
num_warmup_steps=self.num_warmup_steps,
|
| 283 |
+
num_training_steps=self.num_training_steps
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
return [optimizer], [lr_scheduler]
|
| 287 |
+
|
| 288 |
+
def on_train_start(self):
|
| 289 |
+
self.logger.log_hyperparams(self.hparams)
|
| 290 |
+
|
| 291 |
+
def training_step(self, batch, batch_idx):
|
| 292 |
+
targets = torch.tensor(batch['targets'], device=self.device)
|
| 293 |
+
|
| 294 |
+
if self.use_prototype_loss:
|
| 295 |
+
if batch_idx == 0:
|
| 296 |
+
self.prototype_loss = self.calculate_prototype_loss()
|
| 297 |
+
self.log('prototype_loss', self.prototype_loss, on_epoch=True)
|
| 298 |
+
|
| 299 |
+
logits, _ = self(batch)
|
| 300 |
+
|
| 301 |
+
if self.loss == "BCE":
|
| 302 |
+
train_loss = torch.nn.functional.binary_cross_entropy_with_logits(logits, target=targets.float())
|
| 303 |
+
else:
|
| 304 |
+
train_loss = torch.nn.MultiLabelSoftMarginLoss()(input=torch.sigmoid(logits), target=targets)
|
| 305 |
+
|
| 306 |
+
self.log('train_loss', train_loss, on_epoch=True)
|
| 307 |
+
|
| 308 |
+
if self.use_prototype_loss:
|
| 309 |
+
total_loss = train_loss + self.prototype_loss
|
| 310 |
+
else:
|
| 311 |
+
total_loss = train_loss
|
| 312 |
+
|
| 313 |
+
return total_loss
|
| 314 |
+
|
| 315 |
+
def forward(self, batch):
|
| 316 |
+
attention_mask = batch["attention_masks"]
|
| 317 |
+
input_ids = batch["input_ids"]
|
| 318 |
+
token_type_ids = batch["token_type_ids"]
|
| 319 |
+
|
| 320 |
+
if attention_mask.device != self.device:
|
| 321 |
+
attention_mask = attention_mask.to(self.device)
|
| 322 |
+
input_ids = input_ids.to(self.device)
|
| 323 |
+
token_type_ids = token_type_ids.to(self.device)
|
| 324 |
+
|
| 325 |
+
bert_output = self.bert(input_ids=input_ids,
|
| 326 |
+
attention_mask=attention_mask,
|
| 327 |
+
token_type_ids=token_type_ids)
|
| 328 |
+
|
| 329 |
+
bert_vectors = bert_output.last_hidden_state
|
| 330 |
+
|
| 331 |
+
if self.reduce_hidden_size:
|
| 332 |
+
# apply linear layer to reduce token vector dimension
|
| 333 |
+
token_vectors = self.linear(bert_vectors)
|
| 334 |
+
else:
|
| 335 |
+
token_vectors = bert_vectors
|
| 336 |
+
|
| 337 |
+
if self.normalize is not None:
|
| 338 |
+
token_vectors = nn.functional.normalize(token_vectors, p=2, dim=self.normalize)
|
| 339 |
+
|
| 340 |
+
metadata = None
|
| 341 |
+
if self.use_attention:
|
| 342 |
+
|
| 343 |
+
attention_mask_from_tokens = utils.attention_mask_from_tokens(attention_mask, batch["tokens"])
|
| 344 |
+
|
| 345 |
+
weighted_samples_per_class, attention_per_token_and_class = self.calculate_token_class_attention(
|
| 346 |
+
token_vectors,
|
| 347 |
+
self.attention_vectors,
|
| 348 |
+
mask=attention_mask_from_tokens)
|
| 349 |
+
|
| 350 |
+
if self.normalize is not None:
|
| 351 |
+
weighted_samples_per_class = nn.functional.normalize(weighted_samples_per_class, p=2,
|
| 352 |
+
dim=self.normalize)
|
| 353 |
+
|
| 354 |
+
if self.use_cuda:
|
| 355 |
+
weighted_samples_per_class = weighted_samples_per_class.cuda()
|
| 356 |
+
self.num_prototypes_per_class = self.num_prototypes_per_class.cuda()
|
| 357 |
+
|
| 358 |
+
weighted_samples_per_prototype = weighted_samples_per_class.repeat_interleave(
|
| 359 |
+
self.num_prototypes_per_class
|
| 360 |
+
.long(), dim=1)
|
| 361 |
+
|
| 362 |
+
if self.dot_product:
|
| 363 |
+
score_per_prototype = torch.einsum('bs,abs->ab', self.prototype_vectors,
|
| 364 |
+
weighted_samples_per_prototype)
|
| 365 |
+
else:
|
| 366 |
+
score_per_prototype = -self.pairwise_dist(self.prototype_vectors.T,
|
| 367 |
+
weighted_samples_per_prototype.permute(0, 2, 1))
|
| 368 |
+
|
| 369 |
+
metadata = attention_per_token_and_class, weighted_samples_per_prototype
|
| 370 |
+
|
| 371 |
+
else:
|
| 372 |
+
score_per_prototype = -torch.cdist(token_vectors.mean(dim=1), self.prototype_vectors)
|
| 373 |
+
|
| 374 |
+
logits = self.get_logits_per_class(score_per_prototype)
|
| 375 |
+
|
| 376 |
+
return logits, metadata
|
| 377 |
+
|
| 378 |
+
def calculate_token_class_attention(self, batch_samples, class_attention_vectors, mask=None):
|
| 379 |
+
if class_attention_vectors.device != batch_samples.device:
|
| 380 |
+
class_attention_vectors = class_attention_vectors.to(batch_samples.device)
|
| 381 |
+
|
| 382 |
+
score_per_token_and_class = torch.einsum('ikj,mj->imk', batch_samples, class_attention_vectors)
|
| 383 |
+
|
| 384 |
+
if mask is not None:
|
| 385 |
+
expanded_mask = mask.unsqueeze(dim=1).expand(mask.size(0), class_attention_vectors.size(0), mask.size(1))
|
| 386 |
+
|
| 387 |
+
expanded_mask = F.pad(input=expanded_mask,
|
| 388 |
+
pad=(0, score_per_token_and_class.shape[2] - expanded_mask.shape[2]),
|
| 389 |
+
mode='constant', value=0)
|
| 390 |
+
|
| 391 |
+
score_per_token_and_class = score_per_token_and_class.masked_fill(
|
| 392 |
+
(expanded_mask == 0),
|
| 393 |
+
float('-inf'))
|
| 394 |
+
|
| 395 |
+
if self.use_sigmoid:
|
| 396 |
+
attention_per_token_and_class = torch.sigmoid(score_per_token_and_class) / \
|
| 397 |
+
score_per_token_and_class.shape[2]
|
| 398 |
+
else:
|
| 399 |
+
attention_per_token_and_class = F.softmax(score_per_token_and_class, dim=2)
|
| 400 |
+
|
| 401 |
+
class_weighted_tokens = torch.einsum('ikjm,ikj->ikjm',
|
| 402 |
+
batch_samples.unsqueeze(dim=1).expand(batch_samples.size(0),
|
| 403 |
+
self.num_classes,
|
| 404 |
+
batch_samples.size(1),
|
| 405 |
+
batch_samples.size(2)),
|
| 406 |
+
attention_per_token_and_class)
|
| 407 |
+
|
| 408 |
+
weighted_samples_per_class = class_weighted_tokens.sum(dim=2)
|
| 409 |
+
|
| 410 |
+
return weighted_samples_per_class, attention_per_token_and_class
|
| 411 |
+
|
| 412 |
+
def get_logits_per_class(self, score_per_prototype):
|
| 413 |
+
if self.final_layer:
|
| 414 |
+
if score_per_prototype.device != self.final_linear.device:
|
| 415 |
+
score_per_prototype = score_per_prototype.to(self.final_linear.device)
|
| 416 |
+
|
| 417 |
+
return torch.matmul(score_per_prototype, self.final_linear)
|
| 418 |
+
|
| 419 |
+
else:
|
| 420 |
+
batch_size = score_per_prototype.shape[0]
|
| 421 |
+
|
| 422 |
+
fill_vector = torch.full((batch_size, self.num_classes, self.num_prototypes), fill_value=float("-inf"),
|
| 423 |
+
dtype=score_per_prototype.dtype)
|
| 424 |
+
if self.use_cuda:
|
| 425 |
+
fill_vector = fill_vector.cuda()
|
| 426 |
+
self.prototype_to_class_map = self.prototype_to_class_map.cuda()
|
| 427 |
+
|
| 428 |
+
group_logits_by_class = fill_vector.scatter_(1,
|
| 429 |
+
self.prototype_to_class_map.unsqueeze(0).repeat(batch_size,
|
| 430 |
+
1).unsqueeze(
|
| 431 |
+
1),
|
| 432 |
+
score_per_prototype.unsqueeze(1))
|
| 433 |
+
|
| 434 |
+
max_logits_per_class = torch.max(group_logits_by_class, dim=2).values
|
| 435 |
+
return max_logits_per_class
|
| 436 |
+
|
| 437 |
+
def calculate_prototype_loss(self):
|
| 438 |
+
prototype_loss = 100 / torch.tensor([torch.cdist(
|
| 439 |
+
self.prototype_vectors[(self.prototype_to_class_map == i).nonzero().flatten()][:1],
|
| 440 |
+
self.prototype_vectors[(self.prototype_to_class_map == i).nonzero().flatten()][1:]).min() for i in
|
| 441 |
+
range(self.num_classes) if
|
| 442 |
+
len((self.prototype_to_class_map == i).nonzero()) > 1]).sum()
|
| 443 |
+
return prototype_loss
|
| 444 |
+
|
| 445 |
+
def validation_step(self, batch, batch_idx):
|
| 446 |
+
with torch.no_grad():
|
| 447 |
+
targets = torch.tensor(batch['targets'], device=self.device)
|
| 448 |
+
|
| 449 |
+
logits, _ = self(batch)
|
| 450 |
+
|
| 451 |
+
for metric_name in self.train_metrics:
|
| 452 |
+
metric = self.train_metrics[metric_name]
|
| 453 |
+
metric(torch.sigmoid(logits), targets)
|
| 454 |
+
|
| 455 |
+
def validation_epoch_end(self, outputs) -> None:
|
| 456 |
+
for metric_name in self.train_metrics:
|
| 457 |
+
metric = self.train_metrics[metric_name]
|
| 458 |
+
self.log(f"val/{metric_name}", metric.compute())
|
| 459 |
+
metric.reset()
|
| 460 |
+
|
| 461 |
+
def test_step(self, batch, batch_idx):
|
| 462 |
+
with torch.no_grad():
|
| 463 |
+
targets = torch.tensor(batch['targets'], device=self.device)
|
| 464 |
+
|
| 465 |
+
logits, _ = self(batch)
|
| 466 |
+
preds = torch.sigmoid(logits)
|
| 467 |
+
|
| 468 |
+
for metric_name in self.all_metrics:
|
| 469 |
+
metric = self.all_metrics[metric_name]
|
| 470 |
+
metric(preds, targets)
|
| 471 |
+
|
| 472 |
+
return preds, targets
|
| 473 |
+
|
| 474 |
+
def test_epoch_end(self, outputs) -> None:
|
| 475 |
+
log_dir = self.logger.log_dir
|
| 476 |
+
for metric_name in self.all_metrics:
|
| 477 |
+
metric = self.all_metrics[metric_name]
|
| 478 |
+
value = metric.compute()
|
| 479 |
+
self.log(f"test/{metric_name}", value)
|
| 480 |
+
|
| 481 |
+
with open(os.path.join(log_dir, 'test_metrics.txt'), 'a') as metrics_file:
|
| 482 |
+
metrics_file.write(f"{metric_name}: {value}\n")
|
| 483 |
+
|
| 484 |
+
metric.reset()
|
| 485 |
+
|
| 486 |
+
predictions = torch.cat([out[0] for out in outputs])
|
| 487 |
+
# numpy.save(os.path.join(self.logger.log_dir, "predictions"), predictions)
|
| 488 |
+
|
| 489 |
+
targets = torch.cat([out[1] for out in outputs])
|
| 490 |
+
# numpy.save(os.path.join(self.logger.log_dir, "targets"), targets)
|
| 491 |
+
|
| 492 |
+
pr_auc = metrics.calculate_pr_auc(prediction=predictions, target=targets, num_classes=self.num_classes,
|
| 493 |
+
device=self.device)
|
| 494 |
+
|
| 495 |
+
with open(os.path.join(self.logger.log_dir, 'PR_AUC_score.txt'), 'w') as metrics_file:
|
| 496 |
+
metrics_file.write(f"PR AUC: {pr_auc.cpu().numpy()}\n")
|