def early_stop(metrics, steps, min_improvement=0, higher_is_better=False):
  """Early stopping condition.

  Args:
    metrics: A list of metric values.
    steps: Consider the improvement over this many steps.
    min_improvement: Continue if the metric improved less than this value:
    higher_is_better: Whether a higher value is better for this metric.

  Returns:
    A boolean.
  """
  if len(metrics) < steps + 1:
    return False

  def _did_improve(ref, new):
    # Returns True if new is improving on ref.
    if higher_is_better:
      return new > ref + min_improvement
    else:
      return new < ref - min_improvement

  ref_metric = metrics[-steps - 1]
  for metric in metrics[-steps:]:
    if _did_improve(ref_metric, metric):
      return False
  return True