/tensorflow/python/training/gradient_descent_test.py

https://gitlab.com/hrishikeshvganu/tensorflow
Python | 169 lines | 126 code | 14 blank | 29 comment | 16 complexity | fbb8dd88c3634b29039016d67982fe6e MD5 | raw file
  1. # Copyright 2015 Google Inc. 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. """Functional test for GradientDescent."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import numpy as np
  20. import tensorflow as tf
  21. class GradientDescentOptimizerTest(tf.test.TestCase):
  22. def testBasic(self):
  23. for dtype in [tf.half, tf.float32]:
  24. with self.test_session():
  25. var0 = tf.Variable([1.0, 2.0], dtype=dtype)
  26. var1 = tf.Variable([3.0, 4.0], dtype=dtype)
  27. grads0 = tf.constant([0.1, 0.1], dtype=dtype)
  28. grads1 = tf.constant([0.01, 0.01], dtype=dtype)
  29. sgd_op = tf.train.GradientDescentOptimizer(3.0).apply_gradients(zip(
  30. [grads0, grads1], [var0, var1]))
  31. tf.initialize_all_variables().run()
  32. # Fetch params to validate initial values
  33. self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval())
  34. self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval())
  35. # Run 1 step of sgd
  36. sgd_op.run()
  37. # Validate updated params
  38. self.assertAllCloseAccordingToType(
  39. [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval())
  40. self.assertAllCloseAccordingToType(
  41. [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval())
  42. def testTensorLearningRate(self):
  43. for dtype in [tf.half, tf.float32]:
  44. with self.test_session():
  45. var0 = tf.Variable([1.0, 2.0], dtype=dtype)
  46. var1 = tf.Variable([3.0, 4.0], dtype=dtype)
  47. grads0 = tf.constant([0.1, 0.1], dtype=dtype)
  48. grads1 = tf.constant([0.01, 0.01], dtype=dtype)
  49. lrate = tf.constant(3.0)
  50. sgd_op = tf.train.GradientDescentOptimizer(lrate).apply_gradients(zip(
  51. [grads0, grads1], [var0, var1]))
  52. tf.initialize_all_variables().run()
  53. # Fetch params to validate initial values
  54. self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval())
  55. self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval())
  56. # Run 1 step of sgd
  57. sgd_op.run()
  58. # Validate updated params
  59. self.assertAllCloseAccordingToType(
  60. [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval())
  61. self.assertAllCloseAccordingToType(
  62. [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval())
  63. def testFloat64(self):
  64. with self.test_session():
  65. opt = tf.train.GradientDescentOptimizer(3.0)
  66. # compute_gradients.
  67. values = [1.0, 3.0]
  68. good_vars = [tf.Variable([v]) for v in values]
  69. bad_loss = tf.constant(2.0, tf.float64, name="bad_loss")
  70. self.assertRaisesRegexp(
  71. ValueError, r"Invalid type.*float64.*bad_loss.*expected.*float32",
  72. opt.compute_gradients, bad_loss, good_vars)
  73. bad_vars = [
  74. tf.Variable(np.array([v], np.float64), name="bad_var")
  75. for v in values
  76. ]
  77. self.assertRaisesRegexp(
  78. ValueError, r"Invalid type.*float64.*bad_var.*expected.*float32",
  79. opt.compute_gradients, tf.cast(bad_vars[0] + bad_vars[1], tf.float32),
  80. bad_vars)
  81. opt.compute_gradients(good_vars[0] + good_vars[1], good_vars)
  82. # apply_gradients.
  83. bad_grads = [
  84. tf.constant([0.1], dtype=np.float64, name="bad_grad"),
  85. tf.constant([0.01])
  86. ]
  87. self.assertRaisesRegexp(
  88. ValueError, r"Invalid type.*float64.*bad_grad.*expected.*float32",
  89. opt.apply_gradients, zip(bad_grads, good_vars))
  90. good_grads = [tf.constant([0.01]), tf.constant([0.02])]
  91. self.assertRaisesRegexp(
  92. ValueError, r"Invalid type.*float64.*bad_var.*expected.*float32",
  93. opt.apply_gradients, zip(good_grads, bad_vars))
  94. opt.apply_gradients(zip(good_grads, good_vars))
  95. def testGradWrtRef(self):
  96. for dtype in [tf.half, tf.float32]:
  97. with self.test_session():
  98. opt = tf.train.GradientDescentOptimizer(3.0)
  99. values = [1.0, 3.0]
  100. vars_ = [tf.Variable([v], dtype=dtype) for v in values]
  101. grads_and_vars = opt.compute_gradients(vars_[0].ref() + vars_[1], vars_)
  102. tf.initialize_all_variables().run()
  103. for grad, _ in grads_and_vars:
  104. self.assertAllCloseAccordingToType([1.0], grad.eval())
  105. def testWithGlobalStep(self):
  106. for dtype in [tf.half, tf.float32]:
  107. with self.test_session():
  108. global_step = tf.Variable(0, trainable=False)
  109. var0 = tf.Variable([1.0, 2.0], dtype=dtype)
  110. var1 = tf.Variable([3.0, 4.0], dtype=dtype)
  111. grads0 = tf.constant([0.1, 0.1], dtype=dtype)
  112. grads1 = tf.constant([0.01, 0.01], dtype=dtype)
  113. sgd_op = tf.train.GradientDescentOptimizer(3.0).apply_gradients(
  114. zip([grads0, grads1], [var0, var1]),
  115. global_step=global_step)
  116. tf.initialize_all_variables().run()
  117. # Fetch params to validate initial values
  118. self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval())
  119. self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval())
  120. # Run 1 step of sgd
  121. sgd_op.run()
  122. # Validate updated params and global_step
  123. self.assertAllCloseAccordingToType(
  124. [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval())
  125. self.assertAllCloseAccordingToType(
  126. [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval())
  127. self.assertAllCloseAccordingToType(1, global_step.eval())
  128. def testSparseBasic(self):
  129. for dtype in [tf.half, tf.float32]:
  130. with self.test_session():
  131. var0 = tf.Variable([[1.0], [2.0]], dtype=dtype)
  132. var1 = tf.Variable([[3.0], [4.0]], dtype=dtype)
  133. grads0 = tf.IndexedSlices(
  134. tf.constant([0.1], shape=[1, 1], dtype=dtype),
  135. tf.constant([0]),
  136. tf.constant([2, 1]))
  137. grads1 = tf.IndexedSlices(
  138. tf.constant([0.01], shape=[1, 1], dtype=dtype),
  139. tf.constant([1]),
  140. tf.constant([2, 1]))
  141. sgd_op = tf.train.GradientDescentOptimizer(3.0).apply_gradients(
  142. zip([grads0, grads1], [var0, var1]))
  143. tf.initialize_all_variables().run()
  144. # Fetch params to validate initial values
  145. self.assertAllCloseAccordingToType([[1.0], [2.0]], var0.eval())
  146. self.assertAllCloseAccordingToType([[3.0], [4.0]], var1.eval())
  147. # Run 1 step of sgd
  148. sgd_op.run()
  149. # Validate updated params
  150. self.assertAllCloseAccordingToType(
  151. [[1.0 - 3.0 * 0.1], [2.0]], var0.eval())
  152. self.assertAllCloseAccordingToType(
  153. [[3.0], [4.0 - 3.0 * 0.01]], var1.eval())
  154. if __name__ == "__main__":
  155. tf.test.main()