prototorch_models/prototorch/models/probabilistic.py

72 lines
2.4 KiB
Python
Raw Normal View History

2021-05-25 18:26:15 +00:00
"""Probabilistic GLVQ methods"""
import torch
2021-06-01 21:39:06 +00:00
from prototorch.functions.competitions import stratified_min, stratified_sum
2021-05-31 15:56:45 +00:00
from prototorch.functions.losses import log_likelihood_ratio_loss, robust_soft_loss
2021-06-01 15:44:10 +00:00
from prototorch.functions.transforms import gaussian
2021-05-25 18:26:15 +00:00
from .glvq import GLVQ
2021-06-01 21:39:06 +00:00
class CELVQ(GLVQ):
"""Cross-Entropy Learning Vector Quantization."""
def __init__(self, hparams, **kwargs):
super().__init__(hparams, **kwargs)
self.loss = torch.nn.CrossEntropyLoss()
def shared_step(self, batch, batch_idx, optimizer_idx=None):
x, y = batch
out = self._forward(x) # [None, num_protos]
plabels = self.proto_layer.component_labels
probs = -1.0 * stratified_min(out, plabels) # [None, num_classes]
batch_loss = self.loss(probs, y.long())
loss = batch_loss.sum(dim=0)
return out, loss
2021-05-28 15:13:06 +00:00
class ProbabilisticLVQ(GLVQ):
2021-05-31 15:56:45 +00:00
def __init__(self, hparams, rejection_confidence=0.0, **kwargs):
2021-05-25 18:26:15 +00:00
super().__init__(hparams, **kwargs)
2021-05-28 15:13:06 +00:00
self.conditional_distribution = gaussian
self.rejection_confidence = rejection_confidence
2021-05-25 18:26:15 +00:00
def forward(self, x):
distances = self._forward(x)
conditional = self.conditional_distribution(distances,
self.hparams.variance)
2021-06-01 15:44:10 +00:00
prior = (1. / self.num_prototypes) * torch.ones(self.num_prototypes)
2021-05-25 18:26:15 +00:00
posterior = conditional * prior
2021-06-01 15:44:10 +00:00
plabels = self.proto_layer._labels
y_pred = stratified_sum(posterior, plabels)
2021-05-25 18:26:15 +00:00
return y_pred
2021-06-01 15:44:10 +00:00
def predict(self, x):
y_pred = self.forward(x)
confidence, prediction = torch.max(y_pred, dim=1)
prediction[confidence < self.rejection_confidence] = -1
return prediction
2021-05-25 18:26:15 +00:00
def training_step(self, batch, batch_idx, optimizer_idx=None):
X, y = batch
out = self.forward(X)
plabels = self.proto_layer.component_labels
2021-05-28 15:13:06 +00:00
batch_loss = -self.loss_fn(out, y, plabels)
2021-05-25 18:26:15 +00:00
loss = batch_loss.sum(dim=0)
return loss
2021-05-28 15:13:06 +00:00
class LikelihoodRatioLVQ(ProbabilisticLVQ):
2021-05-31 15:56:45 +00:00
"""Learning Vector Quantization based on Likelihood Ratios."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.loss_fn = log_likelihood_ratio_loss
2021-05-28 15:13:06 +00:00
class RSLVQ(ProbabilisticLVQ):
2021-05-31 15:56:45 +00:00
"""Robust Soft Learning Vector Quantization."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.loss_fn = robust_soft_loss