<jupyter_start><jupyter_text>Early stopping callback  stop if objective function is below a certain threshold<jupyter_code>from mango import Tuner

param_dict = dict(x=range(-10, 10))

def objfunc(p_list):
    return [p['x'] ** 2 for p in p_list]

def early_stop(results):
    '''
        stop if best objective is below 2
        results: dict (same keys as dict returned by tuner.minimize/maximize)
    '''
    return results['best_objective'] <= 2

config = dict(early_stopping=early_stop)

tuner = Tuner(param_dict, objfunc, conf_dict=config)
results = tuner.minimize()
results<jupyter_output><empty_output><jupyter_text>stop if objective function does not improve for n iterations<jupyter_code>from mango import Tuner

param_dict = dict(x=range(-10, 10))

def objfunc(p_list):
    return [p['x'] ** 2 for p in p_list]
    

def early_stop(results):
    '''
        stop if best objective does not improve for 2 iterations
        results: dict (same keys as dict returned by tuner.minimize/maximize)
    '''
    current_best = results['best_objective']
    patience_window = results['objective_values'][-3:]
    return min(patience_window) > current_best

config = dict(early_stopping=early_stop)

tuner = Tuner(param_dict, objfunc, conf_dict=config)
results = tuner.minimize()
results<jupyter_output><empty_output><jupyter_text>stop if objective function does not improve for n secs<jupyter_code>import time
import numpy as np

from mango import Tuner

param_dict = dict(x=range(-10, 10))

def objfunc(p_list):
    time.sleep(0.5)
    return [p['x'] ** 2 for p in p_list]
    

class context:
    previous_best = -1.0
    previous_best_time = None
    min_improvement_secs = 0.1
    

def early_stop(results):
    '''
        stop if objective does not improve for 0.1 seconds
    '''
    current_best = results['best_objective']
    current_time = time.time()
    

    if current_best == context.previous_best and \
            (current_time - context.previous_best_time > context.min_improvement_secs):
        print("no improvement in %f seconds: stopping early." % context.min_improvement_secs)
        return True
        
    context.previous_best = current_best
    context.previous_best_time = current_time

    return False

config = dict(early_stopping=early_stop)

tuner = Tuner(param_dict, objfunc, conf_dict=config)
results = tuner.minimize()
results<jupyter_output><empty_output>