David310/Detect_AI-generated_Image
4
1import numpy as np2import torch3 4 5class EarlyStopping:6 """Early stops the training if validation loss doesn't improve after a given patience."""7 def __init__(self, patience=1, verbose=False, delta=0):8 """9 Args:10 patience (int): How long to wait after last time validation loss improved.11 Default: 712 verbose (bool): If True, prints a message for each validation loss improvement. 13 Default: False14 delta (float): Minimum change in the monitored quantity to qualify as an improvement.15 Default: 016 """17 self.patience = patience18 self.verbose = verbose19 self.counter = 020 self.best_score = None21 self.early_stop = False22 self.score_max = -np.Inf23 self.delta = delta24 25 def __call__(self, score, model):26 if self.best_score is None:27 self.best_score = score28 self.save_checkpoint(score, model)29 elif score < self.best_score - self.delta:30 self.counter += 131 print(f'EarlyStopping counter: {self.counter} out of {self.patience}')32 if self.counter >= self.patience:33 self.early_stop = True34 else:35 self.best_score = score36 self.save_checkpoint(score, model)37 self.counter = 038 39 def save_checkpoint(self, score, model):40 '''Saves model when validation loss decrease.'''41 if self.verbose:42 print(f'Validation accuracy increased ({self.score_max:.6f} --> {score:.6f}). Saving model ...')43 model.save_networks('best')44 self.score_max = score