I'm using tf.estimator
in TensorFlow 1.4 and tf.estimator.train_and_evaluate
is great but I need early stopping. What's the prefered way of adding that?
I assume there is some tf.train.SessionRunHook
somewhere for this. I saw that there was an old contrib package with a ValidationMonitor
that seemed to have early stopping, but it doesn't seem to be around anymore in 1.4. Or will the preferred way in the future be to rely on tf.keras
(with which early stopping is really easy) instead of tf.estimator/tf.layers/tf.data
, perhaps?
Another option that doesn't use hooks is to create a
tf.contrib.learn.Experiment
(which seems, even though in contrib, to also support the newtf.estimator.Estimator
).Then train via the (apparently experimental) method
continuous_train_and_eval
with appropriately customizedcontinuous_eval_predicate_fn
.According to the tensorflow docu, the
continuous_eval_predicate_fn
isand called with the
eval_results
from the last evaluation run. For early stopping, use a customized function that keeps as state the current best result and a counter and returnsFalse
when the condition for early stopping is reached.Note added: This approach would be use deprecated methods w/ tensorflow 1.7 (all of tf.contrib.learn is deprecated from that version onwards: https://www.tensorflow.org/api_docs/python/tf/contrib/learn )
Good news!
tf.estimator
now has early stopping support on master and it looks like it will be in 1.10.First, you must name the loss to make it available to the early stopping call. If your loss variable is named "loss" in the estimator, the line
right beneath it will work.
Then, create a hook with this code.
this compares an exponentially smoothed loss validation with its lowest value, and if it is higher by tolerance, it stops training. If it stops too early, raising tolerance and smoothing will make it stop later. Keep smoothing below one, or it will never stop.
You can replace the logic in after_run with something else if you want to stop based on a different condition.
Now, add this hook to the evaluation spec. Your code should look something like this:
Important note: The function, run_context.request_stop() is broken in the train_and_evaluate call, and doesn't stop training. So, I raised a value error to stop training. So you have to wrap the train_and_evaluate call in a try catch block like this:
if you don't do this, the code will crash with an error when training stops.
Yes, there is
tf.train.StopAtStepHook
:You can also extend it and implement your own stopping strategy based on the step results.