一、核心类
class EarlyStopping:# YOLOv5 simple early stopperdef __init__(self, patience=30):self.best_fitness = 0.0 # i.e. mAPself.best_epoch = 0self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stopself.possible_stop = False # possible stop may occur next epochdef __call__(self, epoch, fitness):#fitness最佳参数,if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of trainingself.best_epoch = epochself.best_fitness = fitnessdelta = epoch - self.best_epoch # epochs without improvement 当前epoch与最优epoch的差值,大于patience则提前结束 重点self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epochstop = delta >= self.patience # stop training if patience exceededif stop:LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. 'f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n'f'To update EarlyStopping(patience={self.patience}) pass a new patience value, 'f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.')return stop
二、创建对象
stopper, stop = EarlyStopping(patience=opt.patience), False
三、提前结束判断
...for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------callbacks.run('on_train_epoch_start')model.train().....#最佳参数判断fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]stop = stopper(epoch=epoch, fitness=fi) # early stop check....if stop:break # must break all DDP ranks