Skip to content

Instantly share code, notes, and snippets.

@sinecode
Created August 17, 2020 15:35
Show Gist options
  • Save sinecode/df13c3110be2e6f7bab8de294f756227 to your computer and use it in GitHub Desktop.
Save sinecode/df13c3110be2e6f7bab8de294f756227 to your computer and use it in GitHub Desktop.
Python class that implements the Early Stopping method to prevent overfitting
"""
Implementation of the Early stopping method.
Usage:
>>> es = EarlyStopping(patience=2)
>>> es.early_stop
False
>>> es(2)
>>> es.early_stop
False
>>> es(3)
>>> es.early_stop
False
>>> es(2.5)
>>> es.early_stop
False
>>> es(4)
>>> es.early_stop
True
"""
import numpy as np
class EarlyStopping:
def __init__(self, patience, delta=0):
self.patience = patience
self.delta = delta
self.best_value = np.inf
self.counter = 0
self.early_stop = False
def __call__(self, value):
if value + self.delta >= self.best_value:
if self.counter == self.patience:
self.early_stop = True
else:
self.counter += 1
else:
self.counter = 0
self.best_value = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment