Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/keras/src/optimizers/legacy/adadelta.py: 36%
44 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 2018 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 numpy as np
18import tensorflow.compat.v2 as tf
20from keras.src import backend_config
21from keras.src.optimizers.legacy import optimizer_v2
23# isort: off
24from tensorflow.python.util.tf_export import keras_export
27@keras_export(
28 "keras.optimizers.legacy.Adadelta",
29 v1=["keras.optimizers.Adadelta", "keras.optimizers.legacy.Adadelta"],
30)
31class Adadelta(optimizer_v2.OptimizerV2):
32 r"""Optimizer that implements the Adadelta algorithm.
34 Adadelta optimization is a stochastic gradient descent method that is based
35 on adaptive learning rate per dimension to address two drawbacks:
37 - The continual decay of learning rates throughout training.
38 - The need for a manually selected global learning rate.
40 Adadelta is a more robust extension of Adagrad that adapts learning rates
41 based on a moving window of gradient updates, instead of accumulating all
42 past gradients. This way, Adadelta continues learning even when many updates
43 have been done. Compared to Adagrad, in the original version of Adadelta you
44 don't have to set an initial learning rate. In this version, the initial
45 learning rate can be set, as in most other Keras optimizers.
47 Args:
48 learning_rate: Initial value for the learning rate:
49 either a floating point value,
50 or a `tf.keras.optimizers.schedules.LearningRateSchedule` instance.
51 Note that `Adadelta` tends to benefit from higher initial learning rate
52 values compared to other optimizers.
53 To match the exact form in the original paper, use 1.0.
54 Defaults to `0.001`.
55 rho: A `Tensor` or a floating point value. The decay rate.
56 epsilon: Small floating point value used to maintain numerical stability.
57 name: Optional name prefix for the operations created when applying
58 gradients. Defaults to `"Adadelta"`.
59 **kwargs: keyword arguments. Allowed arguments are `clipvalue`,
60 `clipnorm`, `global_clipnorm`.
61 If `clipvalue` (float) is set, the gradient of each weight
62 is clipped to be no higher than this value.
63 If `clipnorm` (float) is set, the gradient of each weight
64 is individually clipped so that its norm is no higher than this value.
65 If `global_clipnorm` (float) is set the gradient of all weights is
66 clipped so that their global norm is no higher than this value.
68 Reference:
69 - [Zeiler, 2012](http://arxiv.org/abs/1212.5701)
70 """
72 _HAS_AGGREGATE_GRAD = True
74 def __init__(
75 self,
76 learning_rate=0.001,
77 rho=0.95,
78 epsilon=1e-7,
79 name="Adadelta",
80 **kwargs
81 ):
82 super().__init__(name, **kwargs)
83 self._set_hyper("learning_rate", kwargs.get("lr", learning_rate))
84 self._set_hyper("decay", self._initial_decay)
85 self._set_hyper("rho", rho)
86 self.epsilon = epsilon or backend_config.epsilon()
88 def _create_slots(self, var_list):
89 # Separate for-loops to respect the ordering of slot variables from v1.
90 for v in var_list:
91 self.add_slot(v, "accum_grad")
92 for v in var_list:
93 self.add_slot(v, "accum_var")
95 def _prepare_local(self, var_device, var_dtype, apply_state):
96 super()._prepare_local(var_device, var_dtype, apply_state)
97 apply_state[(var_device, var_dtype)].update(
98 dict(
99 epsilon=tf.convert_to_tensor(self.epsilon, var_dtype),
100 rho=tf.identity(self._get_hyper("rho", var_dtype)),
101 )
102 )
104 def set_weights(self, weights):
105 params = self.weights
106 # Override set_weights for backward compatibility of Keras V1 optimizer
107 # since it does not include iteration at head of the weight list. Set
108 # iteration to 0.
109 if len(params) == len(weights) + 1:
110 weights = [np.array(0)] + weights
111 super().set_weights(weights)
113 def _resource_apply_dense(self, grad, var, apply_state=None):
114 var_device, var_dtype = var.device, var.dtype.base_dtype
115 coefficients = (apply_state or {}).get(
116 (var_device, var_dtype)
117 ) or self._fallback_apply_state(var_device, var_dtype)
119 accum_grad = self.get_slot(var, "accum_grad")
120 accum_var = self.get_slot(var, "accum_var")
121 return tf.raw_ops.ResourceApplyAdadelta(
122 var=var.handle,
123 accum=accum_grad.handle,
124 accum_update=accum_var.handle,
125 lr=coefficients["lr_t"],
126 rho=coefficients["rho"],
127 epsilon=coefficients["epsilon"],
128 grad=grad,
129 use_locking=self._use_locking,
130 )
132 def _resource_apply_sparse(self, grad, var, indices, apply_state=None):
133 var_device, var_dtype = var.device, var.dtype.base_dtype
134 coefficients = (apply_state or {}).get(
135 (var_device, var_dtype)
136 ) or self._fallback_apply_state(var_device, var_dtype)
138 accum_grad = self.get_slot(var, "accum_grad")
139 accum_var = self.get_slot(var, "accum_var")
140 return tf.raw_ops.ResourceSparseApplyAdadelta(
141 var=var.handle,
142 accum=accum_grad.handle,
143 accum_update=accum_var.handle,
144 lr=coefficients["lr_t"],
145 rho=coefficients["rho"],
146 epsilon=coefficients["epsilon"],
147 grad=grad,
148 indices=indices,
149 use_locking=self._use_locking,
150 )
152 def get_config(self):
153 config = super().get_config()
154 config.update(
155 {
156 "learning_rate": self._serialize_hyperparameter(
157 "learning_rate"
158 ),
159 "decay": self._initial_decay,
160 "rho": self._serialize_hyperparameter("rho"),
161 "epsilon": self.epsilon,
162 }
163 )
164 return config