Created
August 17, 2020 15:35
-
-
Save sinecode/df13c3110be2e6f7bab8de294f756227 to your computer and use it in GitHub Desktop.
Python class that implements the Early Stopping method to prevent overfitting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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