Source code for unilvq.common.early_stopper

#!/usr/bin/env python
# Created by "Thieu" at 07:20, 13/05/2025 ----------%
#       Email: nguyenthieu2102@gmail.com            %                                                    
#       Github: https://github.com/thieu1995        %                         
# --------------------------------------------------%

[docs]class EarlyStopper: """ A utility class for implementing early stopping in training processes to prevent overfitting. Attributes: - patience (int): Number of consecutive epochs to tolerate no improvement before stopping. - epsilon (float): Minimum loss improvement threshold to reset the patience counter. - counter (int): Tracks the number of epochs without sufficient improvement. - min_loss (float): Keeps track of the minimum observed loss. """ def __init__(self, patience=1, epsilon=0.01): """ Initialize the EarlyStopper with specified patience and epsilon. Parameters: - patience (int): Maximum number of epochs without improvement before stopping. - epsilon (float): Minimum loss reduction to reset the patience counter. """ self.patience = patience self.epsilon = epsilon self.counter = 0 self.min_loss = float('inf')
[docs] def early_stop(self, loss): """ Checks if training should be stopped based on the current loss. Parameters: - loss (float): The current loss value for the epoch. Returns: - bool: True if training should stop, False otherwise. """ if loss < self.min_loss: # Loss has improved; reset counter and update min_loss self.min_loss = loss self.counter = 0 elif loss > (self.min_loss + self.epsilon): # Loss did not improve sufficiently; increment counter self.counter += 1 if self.counter >= self.patience: return True return False