-
Notifications
You must be signed in to change notification settings - Fork 613
/
Copy pathtime_stopping.py
66 lines (54 loc) · 2.21 KB
/
time_stopping.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Callback that stops training when a specified amount of time has passed."""
import datetime
import time
from typeguard import typechecked
import tensorflow as tf
from tensorflow.keras.callbacks import Callback
@tf.keras.utils.register_keras_serializable(package="Addons")
class TimeStopping(Callback):
"""Stop training when a specified amount of time has passed.
Args:
seconds: maximum amount of time before stopping.
Defaults to 86400 (1 day).
verbose: verbosity mode. Defaults to 0.
"""
@typechecked
def __init__(self, seconds: int = 86400, verbose: int = 0):
super().__init__()
self.seconds = seconds
self.verbose = verbose
self.stopped_epoch = None
def on_train_begin(self, logs=None):
self.stopping_time = time.time() + self.seconds
def on_epoch_end(self, epoch, logs={}):
if time.time() >= self.stopping_time:
self.model.stop_training = True
self.stopped_epoch = epoch
def on_train_end(self, logs=None):
if self.stopped_epoch is not None and self.verbose > 0:
formatted_time = datetime.timedelta(seconds=self.seconds)
msg = "Timed stopping at epoch {} after training for {}".format(
self.stopped_epoch + 1, formatted_time
)
print(msg)
def get_config(self):
config = {
"seconds": self.seconds,
"verbose": self.verbose,
}
base_config = super().get_config()
return {**base_config, **config}