Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/keras/src/optimizers/adadelta.py: 29%
45 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
1# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""Adadelta optimizer implementation."""
17import tensorflow.compat.v2 as tf
19from keras.src.optimizers import optimizer
20from keras.src.saving.object_registration import register_keras_serializable
22# isort: off
23from tensorflow.python.util.tf_export import keras_export
26@register_keras_serializable()
27@keras_export(
28 "keras.optimizers.experimental.Adadelta",
29 "keras.optimizers.Adadelta",
30 "keras.dtensor.experimental.optimizers.Adadelta",
31 v1=[],
32)
33class Adadelta(optimizer.Optimizer):
34 r"""Optimizer that implements the Adadelta algorithm.
36 Adadelta optimization is a stochastic gradient descent method that is based
37 on adaptive learning rate per dimension to address two drawbacks:
39 - The continual decay of learning rates throughout training.
40 - The need for a manually selected global learning rate.
42 Adadelta is a more robust extension of Adagrad that adapts learning rates
43 based on a moving window of gradient updates, instead of accumulating all
44 past gradients. This way, Adadelta continues learning even when many updates
45 have been done. Compared to Adagrad, in the original version of Adadelta you
46 don't have to set an initial learning rate. In this version, the initial
47 learning rate can be set, as in most other Keras optimizers.
49 Args:
50 learning_rate: Initial value for the learning rate: either a floating
51 point value, or a `tf.keras.optimizers.schedules.LearningRateSchedule`
52 instance. Defaults to 0.001. Note that `Adadelta` tends to benefit from
53 higher initial learning rate values compared to other optimizers. To
54 match the exact form in the original paper, use 1.0.
55 rho: A `Tensor` or a floating point value. The decay rate. Defaults to
56 0.95.
57 epsilon: Small floating point value used to maintain numerical stability.
58 Defaults to 1e-7.
59 {{base_optimizer_keyword_args}}
61 Reference:
62 - [Zeiler, 2012](http://arxiv.org/abs/1212.5701)
63 """
65 def __init__(
66 self,
67 learning_rate=0.001,
68 rho=0.95,
69 epsilon=1e-7,
70 weight_decay=None,
71 clipnorm=None,
72 clipvalue=None,
73 global_clipnorm=None,
74 use_ema=False,
75 ema_momentum=0.99,
76 ema_overwrite_frequency=None,
77 jit_compile=True,
78 name="Adadelta",
79 **kwargs
80 ):
81 super().__init__(
82 weight_decay=weight_decay,
83 clipnorm=clipnorm,
84 clipvalue=clipvalue,
85 global_clipnorm=global_clipnorm,
86 use_ema=use_ema,
87 ema_momentum=ema_momentum,
88 ema_overwrite_frequency=ema_overwrite_frequency,
89 jit_compile=jit_compile,
90 name=name,
91 **kwargs
92 )
93 self._learning_rate = self._build_learning_rate(learning_rate)
94 self.rho = rho
95 self.epsilon = epsilon
97 def build(self, var_list):
98 super().build(var_list)
99 if hasattr(self, "_built") and self._built:
100 return
101 self._built = True
102 self._accumulated_grads = []
103 self._accumulated_delta_vars = []
104 for var in var_list:
105 self._accumulated_grads.append(
106 self.add_variable_from_reference(var, "accumulated_grad")
107 )
108 self._accumulated_delta_vars.append(
109 self.add_variable_from_reference(var, "accumulated_delta_var")
110 )
112 def update_step(self, grad, variable):
113 """Update step given gradient and the associated model variable."""
114 lr = tf.cast(self.learning_rate, variable.dtype)
116 var_key = self._var_key(variable)
117 rho = self.rho
118 accumulated_grad = self._accumulated_grads[self._index_dict[var_key]]
119 accumulated_delta_var = self._accumulated_delta_vars[
120 self._index_dict[var_key]
121 ]
123 def rms(x):
124 return tf.sqrt(x + self.epsilon)
126 if isinstance(grad, tf.IndexedSlices):
127 # Sparse gradients.
128 accumulated_grad.assign_add((rho - 1) * accumulated_grad)
129 accumulated_grad.scatter_add(
130 tf.IndexedSlices(
131 (1 - rho) * tf.square(grad.values), grad.indices
132 )
133 )
134 delta_var = (
135 -rms(accumulated_delta_var) * grad / rms(accumulated_grad)
136 )
137 accumulated_delta_var.assign(
138 rho * accumulated_delta_var + (1 - rho) * delta_var * delta_var
139 )
140 else:
141 # Dense gradients.
142 accumulated_grad.assign(
143 rho * accumulated_grad + (1 - rho) * grad * grad
144 )
145 delta_var = (
146 -rms(accumulated_delta_var) * grad / rms(accumulated_grad)
147 )
148 accumulated_delta_var.assign(
149 rho * accumulated_delta_var + (1 - rho) * delta_var * delta_var
150 )
151 variable.assign_add(lr * delta_var)
153 def get_config(self):
154 config = super().get_config()
156 config.update(
157 {
158 "learning_rate": self._serialize_hyperparameter(
159 self._learning_rate
160 ),
161 "rho": self.rho,
162 "epsilon": self.epsilon,
163 }
164 )
165 return config
168Adadelta.__doc__ = Adadelta.__doc__.replace(
169 "{{base_optimizer_keyword_args}}", optimizer.base_optimizer_keyword_args
170)