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