2021-04-21 12:51:34 +00:00
|
|
|
import torch
|
2021-04-21 17:16:57 +00:00
|
|
|
import torchmetrics
|
2021-04-29 15:05:41 +00:00
|
|
|
from prototorch.components import LabeledComponents
|
2021-05-04 18:56:16 +00:00
|
|
|
from prototorch.functions.activations import get_activation
|
2021-04-21 12:51:34 +00:00
|
|
|
from prototorch.functions.competitions import wtac
|
2021-05-06 16:42:06 +00:00
|
|
|
from prototorch.functions.distances import (euclidean_distance, omega_distance,
|
2021-05-17 15:00:23 +00:00
|
|
|
sed)
|
2021-05-12 14:36:22 +00:00
|
|
|
from prototorch.functions.helper import get_flat
|
2021-05-11 11:26:13 +00:00
|
|
|
from prototorch.functions.losses import glvq_loss, lvq1_loss, lvq21_loss
|
2021-04-21 12:51:34 +00:00
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
from .abstract import (AbstractPrototypeModel, PrototypeImageModel,
|
|
|
|
SiamesePrototypeModel)
|
2021-05-12 14:36:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class GLVQ(AbstractPrototypeModel):
|
|
|
|
"""Generalized Learning Vector Quantization."""
|
|
|
|
|
|
|
|
|
|
|
|
from .abstract import AbstractPrototypeModel, PrototypeImageModel
|
2021-04-29 15:05:41 +00:00
|
|
|
|
2021-04-21 12:51:34 +00:00
|
|
|
|
2021-04-29 15:05:41 +00:00
|
|
|
class GLVQ(AbstractPrototypeModel):
|
2021-04-21 12:51:34 +00:00
|
|
|
"""Generalized Learning Vector Quantization."""
|
2021-04-21 19:59:19 +00:00
|
|
|
def __init__(self, hparams, **kwargs):
|
2021-04-21 12:51:34 +00:00
|
|
|
super().__init__()
|
2021-04-27 13:38:57 +00:00
|
|
|
|
2021-04-21 19:59:19 +00:00
|
|
|
self.save_hyperparameters(hparams)
|
2021-04-27 13:38:57 +00:00
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
self.distance_fn = kwargs.get("distance_fn", euclidean_distance)
|
2021-05-11 14:13:00 +00:00
|
|
|
self.optimizer = kwargs.get("optimizer", torch.optim.Adam)
|
2021-05-12 14:36:22 +00:00
|
|
|
prototype_initializer = kwargs.get("prototype_initializer", None)
|
2021-05-11 14:13:00 +00:00
|
|
|
|
2021-04-27 13:38:57 +00:00
|
|
|
# Default Values
|
2021-05-04 18:56:16 +00:00
|
|
|
self.hparams.setdefault("transfer_function", "identity")
|
|
|
|
self.hparams.setdefault("transfer_beta", 10.0)
|
2021-04-27 13:38:57 +00:00
|
|
|
|
2021-04-29 15:05:41 +00:00
|
|
|
self.proto_layer = LabeledComponents(
|
2021-05-11 14:13:00 +00:00
|
|
|
distribution=self.hparams.distribution,
|
2021-05-12 14:36:22 +00:00
|
|
|
initializer=prototype_initializer)
|
2021-04-27 13:38:57 +00:00
|
|
|
|
2021-05-04 18:56:16 +00:00
|
|
|
self.transfer_function = get_activation(self.hparams.transfer_function)
|
2021-04-21 17:16:57 +00:00
|
|
|
self.train_acc = torchmetrics.Accuracy()
|
2021-04-21 12:51:34 +00:00
|
|
|
|
2021-05-11 11:26:13 +00:00
|
|
|
self.loss = glvq_loss
|
|
|
|
|
2021-04-21 12:51:34 +00:00
|
|
|
@property
|
|
|
|
def prototype_labels(self):
|
2021-05-06 16:42:06 +00:00
|
|
|
return self.proto_layer.component_labels.detach().cpu()
|
2021-04-21 19:35:52 +00:00
|
|
|
|
2021-04-21 12:51:34 +00:00
|
|
|
def forward(self, x):
|
2021-04-29 15:05:41 +00:00
|
|
|
protos, _ = self.proto_layer()
|
2021-05-17 15:00:23 +00:00
|
|
|
dis = self.distance_fn(x, protos)
|
2021-04-21 12:51:34 +00:00
|
|
|
return dis
|
|
|
|
|
2021-05-03 11:20:49 +00:00
|
|
|
def training_step(self, train_batch, batch_idx, optimizer_idx=None):
|
2021-04-21 12:51:34 +00:00
|
|
|
x, y = train_batch
|
|
|
|
dis = self(x)
|
2021-04-29 15:05:41 +00:00
|
|
|
plabels = self.proto_layer.component_labels
|
2021-05-11 11:26:13 +00:00
|
|
|
mu = self.loss(dis, y, prototype_labels=plabels)
|
2021-05-04 18:56:16 +00:00
|
|
|
batch_loss = self.transfer_function(mu,
|
|
|
|
beta=self.hparams.transfer_beta)
|
|
|
|
loss = batch_loss.sum(dim=0)
|
2021-04-29 21:37:22 +00:00
|
|
|
|
|
|
|
# Compute training accuracy
|
2021-04-21 17:16:57 +00:00
|
|
|
with torch.no_grad():
|
|
|
|
preds = wtac(dis, plabels)
|
2021-05-06 16:02:01 +00:00
|
|
|
|
|
|
|
self.train_acc(preds.int(), y.int())
|
2021-04-29 21:37:22 +00:00
|
|
|
# `.int()` because FloatTensors are assumed to be class probabilities
|
2021-04-21 12:51:34 +00:00
|
|
|
|
2021-04-29 21:37:22 +00:00
|
|
|
# Logging
|
|
|
|
self.log("train_loss", loss)
|
|
|
|
self.log("acc",
|
|
|
|
self.train_acc,
|
|
|
|
on_step=False,
|
|
|
|
on_epoch=True,
|
|
|
|
prog_bar=True,
|
|
|
|
logger=True)
|
|
|
|
|
|
|
|
return loss
|
2021-04-21 17:16:57 +00:00
|
|
|
|
2021-04-21 12:51:34 +00:00
|
|
|
def predict(self, x):
|
2021-04-27 12:35:17 +00:00
|
|
|
# model.eval() # ?!
|
2021-04-21 12:51:34 +00:00
|
|
|
with torch.no_grad():
|
|
|
|
d = self(x)
|
2021-04-29 15:05:41 +00:00
|
|
|
plabels = self.proto_layer.component_labels
|
2021-04-21 12:51:34 +00:00
|
|
|
y_pred = wtac(d, plabels)
|
2021-05-13 13:22:01 +00:00
|
|
|
return y_pred
|
2021-04-21 12:51:34 +00:00
|
|
|
|
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
class SiameseGLVQ(SiamesePrototypeModel, GLVQ):
|
2021-04-27 12:35:17 +00:00
|
|
|
"""GLVQ in a Siamese setting.
|
|
|
|
|
|
|
|
GLVQ model that applies an arbitrary transformation on the inputs and the
|
|
|
|
prototypes before computing the distances between them. The weights in the
|
|
|
|
transformation pipeline are only learned from the inputs.
|
2021-04-29 21:37:22 +00:00
|
|
|
|
2021-04-27 12:35:17 +00:00
|
|
|
"""
|
|
|
|
def __init__(self,
|
|
|
|
hparams,
|
2021-05-17 15:00:23 +00:00
|
|
|
backbone=torch.nn.Identity(),
|
|
|
|
both_path_gradients=False,
|
2021-04-27 12:35:17 +00:00
|
|
|
**kwargs):
|
|
|
|
super().__init__(hparams, **kwargs)
|
2021-05-17 15:00:23 +00:00
|
|
|
self.backbone = backbone
|
|
|
|
self.both_path_gradients = both_path_gradients
|
|
|
|
self.distance_fn = kwargs.get("distance_fn", sed)
|
2021-05-03 11:20:49 +00:00
|
|
|
|
2021-04-27 12:35:17 +00:00
|
|
|
def forward(self, x):
|
2021-04-29 15:05:41 +00:00
|
|
|
protos, _ = self.proto_layer()
|
2021-04-27 12:35:17 +00:00
|
|
|
latent_x = self.backbone(x)
|
2021-05-17 15:00:23 +00:00
|
|
|
self.backbone.requires_grad_(self.both_path_gradients)
|
|
|
|
latent_protos = self.backbone(protos)
|
|
|
|
self.backbone.requires_grad_(True)
|
|
|
|
dis = self.distance_fn(latent_x, latent_protos)
|
2021-04-27 12:35:17 +00:00
|
|
|
return dis
|
|
|
|
|
2021-04-29 21:37:22 +00:00
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
class GRLVQ(SiamesePrototypeModel, GLVQ):
|
2021-05-06 16:42:06 +00:00
|
|
|
"""Generalized Relevance Learning Vector Quantization."""
|
|
|
|
def __init__(self, hparams, **kwargs):
|
|
|
|
super().__init__(hparams, **kwargs)
|
|
|
|
self.relevances = torch.nn.parameter.Parameter(
|
|
|
|
torch.ones(self.hparams.input_dim))
|
2021-05-17 15:00:23 +00:00
|
|
|
self.distance_fn = kwargs.get("distance_fn", sed)
|
2021-05-06 16:42:06 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def relevance_profile(self):
|
|
|
|
return self.relevances.detach().cpu()
|
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
def backbone(self, x):
|
|
|
|
"""Namespace hook for the visualization callbacks to work."""
|
|
|
|
return x @ torch.diag(self.relevances)
|
2021-05-06 16:42:06 +00:00
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
def forward(self, x):
|
|
|
|
protos, _ = self.proto_layer()
|
|
|
|
dis = omega_distance(x, protos, torch.diag(self.relevances))
|
|
|
|
return dis
|
2021-05-06 16:42:06 +00:00
|
|
|
|
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
class GMLVQ(SiamesePrototypeModel, GLVQ):
|
2021-04-29 21:37:22 +00:00
|
|
|
"""Generalized Matrix Learning Vector Quantization."""
|
|
|
|
def __init__(self, hparams, **kwargs):
|
|
|
|
super().__init__(hparams, **kwargs)
|
2021-05-17 15:00:23 +00:00
|
|
|
self.backbone = torch.nn.Linear(self.hparams.input_dim,
|
|
|
|
self.hparams.latent_dim,
|
|
|
|
bias=False)
|
|
|
|
self.distance_fn = kwargs.get("distance_fn", sed)
|
2021-05-09 18:53:31 +00:00
|
|
|
|
2021-05-07 13:24:47 +00:00
|
|
|
@property
|
|
|
|
def omega_matrix(self):
|
2021-05-17 15:00:23 +00:00
|
|
|
return self.backbone.weight.detach().cpu()
|
2021-05-07 13:24:47 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def lambda_matrix(self):
|
2021-05-17 15:00:23 +00:00
|
|
|
omega = self.backbone.weight # (latent_dim, input_dim)
|
2021-05-10 12:09:25 +00:00
|
|
|
lam = omega.T @ omega
|
2021-05-07 13:24:47 +00:00
|
|
|
return lam.detach().cpu()
|
|
|
|
|
|
|
|
def show_lambda(self):
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
title = "Lambda matrix"
|
|
|
|
plt.figure(title)
|
|
|
|
plt.title(title)
|
|
|
|
plt.imshow(self.lambda_matrix, cmap="gray")
|
|
|
|
plt.axis("off")
|
|
|
|
plt.colorbar()
|
|
|
|
plt.show(block=True)
|
|
|
|
|
2021-04-29 21:37:22 +00:00
|
|
|
def forward(self, x):
|
|
|
|
protos, _ = self.proto_layer()
|
2021-05-12 14:36:22 +00:00
|
|
|
x, protos = get_flat(x, protos)
|
2021-05-17 15:00:23 +00:00
|
|
|
latent_x = self.backbone(x)
|
|
|
|
latent_protos = self.backbone(protos)
|
|
|
|
dis = self.distance_fn(latent_x, latent_protos)
|
2021-04-29 21:37:22 +00:00
|
|
|
return dis
|
|
|
|
|
2021-05-04 13:11:16 +00:00
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
class LVQMLN(SiamesePrototypeModel, GLVQ):
|
2021-04-29 21:37:22 +00:00
|
|
|
"""Learning Vector Quantization Multi-Layer Network.
|
|
|
|
|
|
|
|
GLVQ model that applies an arbitrary transformation on the inputs, BUT NOT
|
|
|
|
on the prototypes before computing the distances between them. This of
|
|
|
|
course, means that the prototypes no longer live the input space, but
|
|
|
|
rather in the embedding space.
|
|
|
|
|
|
|
|
"""
|
2021-05-17 15:00:23 +00:00
|
|
|
def __init__(self, hparams, backbone=torch.nn.Identity(), **kwargs):
|
2021-04-29 21:37:22 +00:00
|
|
|
super().__init__(hparams, **kwargs)
|
2021-05-17 15:00:23 +00:00
|
|
|
self.backbone = backbone
|
|
|
|
|
|
|
|
self.distance_fn = kwargs.get("distance_fn", sed)
|
2021-04-29 21:37:22 +00:00
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
latent_protos, _ = self.proto_layer()
|
|
|
|
latent_x = self.backbone(x)
|
2021-05-17 15:00:23 +00:00
|
|
|
dis = self.distance_fn(latent_x, latent_protos)
|
2021-04-29 21:37:22 +00:00
|
|
|
return dis
|
|
|
|
|
2021-05-17 15:00:23 +00:00
|
|
|
|
|
|
|
class LVQ1(GLVQ):
|
|
|
|
"""Learning Vector Quantization 1."""
|
|
|
|
def __init__(self, hparams, **kwargs):
|
|
|
|
super().__init__(hparams, **kwargs)
|
|
|
|
self.loss = lvq1_loss
|
|
|
|
self.optimizer = torch.optim.SGD
|
|
|
|
|
|
|
|
|
|
|
|
class LVQ21(GLVQ):
|
|
|
|
"""Learning Vector Quantization 2.1."""
|
|
|
|
def __init__(self, hparams, **kwargs):
|
|
|
|
super().__init__(hparams, **kwargs)
|
|
|
|
self.loss = lvq21_loss
|
|
|
|
self.optimizer = torch.optim.SGD
|
|
|
|
|
|
|
|
|
|
|
|
class ImageGLVQ(PrototypeImageModel, GLVQ):
|
|
|
|
"""GLVQ for training on image data.
|
|
|
|
|
|
|
|
GLVQ model that constrains the prototypes to the range [0, 1] by clamping
|
|
|
|
after updates.
|
|
|
|
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class ImageGMLVQ(PrototypeImageModel, GMLVQ):
|
|
|
|
"""GMLVQ for training on image data.
|
|
|
|
|
|
|
|
GMLVQ model that constrains the prototypes to the range [0, 1] by clamping
|
|
|
|
after updates.
|
|
|
|
|
|
|
|
"""
|
|
|
|
pass
|