|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn as nn |
| 5 | +import torch.nn.functional as F |
| 6 | +from torch import LongTensor, Tensor |
| 7 | + |
| 8 | +from quaterion.loss.group_loss import GroupLoss |
| 9 | +from quaterion.utils import l2_norm |
| 10 | + |
| 11 | + |
| 12 | +class CenterLoss(GroupLoss): |
| 13 | + """ |
| 14 | + Center Loss as defined in the paper "A Discriminative Feature Learning Approach |
| 15 | + for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf) |
| 16 | + It aims to minimize the intra-class variations while keeping the features of |
| 17 | + different classes separable. |
| 18 | +
|
| 19 | + Args: |
| 20 | + embedding_size: Output dimension of the encoder. |
| 21 | + num_groups: Number of groups (classes) in the dataset. |
| 22 | + lambda_c: A regularization parameter that controls the contribution of the center loss. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, embedding_size: int, num_groups: int, lambda_c: Optional[float] = 0.5 |
| 27 | + ): |
| 28 | + super(GroupLoss, self).__init__() |
| 29 | + self.num_groups = num_groups |
| 30 | + self.centers = nn.Parameter(torch.randn(num_groups, embedding_size)) |
| 31 | + self.lambda_c = lambda_c |
| 32 | + |
| 33 | + nn.init.xavier_uniform_(self.centers) |
| 34 | + |
| 35 | + def forward(self, embeddings: Tensor, groups: LongTensor) -> Tensor: |
| 36 | + """ |
| 37 | + Compute the Center Loss value. |
| 38 | +
|
| 39 | + Args: |
| 40 | + embeddings: shape (batch_size, vector_length) - Output embeddings from the encoder. |
| 41 | + groups: shape (batch_size,) - Group (class) ids associated with embeddings. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + Tensor: loss value. |
| 45 | + """ |
| 46 | + embeddings = l2_norm(embeddings, 1) |
| 47 | + |
| 48 | + # Gather the center for each embedding's corresponding group |
| 49 | + centers_batch = self.centers.index_select(0, groups) |
| 50 | + |
| 51 | + # Calculate the distance between embeddings and their respective class centers |
| 52 | + loss = F.mse_loss(embeddings, centers_batch) |
| 53 | + |
| 54 | + # Scale the loss by the regularization parameter |
| 55 | + loss *= self.lambda_c |
| 56 | + |
| 57 | + return loss |
0 commit comments