• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 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"""Tests for tf upgrader."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20import shutil
21import tempfile
22
23import numpy as np
24import tensorflow as tf
25from tensorflow.python.framework import test_util
26from tensorflow.python.platform import test as test_lib
27
28
29class TestUpgrade(test_util.TensorFlowTestCase):
30  """Test various APIs that have been changed in 1.0.
31
32  This test will not run in current TensorFlow, but did run in 0.11.
33  This file is intended to be converted by a genrule() that uses the converter
34  so that a 1.0 compatible version of this file is generated. That is run as
35  a unit test if the converter is successful.
36  """
37
38  @test_util.run_v1_only("b/120545219")
39  def testArgRenames(self):
40    with self.cached_session():
41
42      a = [[1., 2., 3.], [4., 5., 6.]]
43      b = [[True, False, False], [False, True, True]]
44      dim0 = [1]
45      dim1 = [1]
46
47      self.assertAllEqual(
48          tf.reduce_any(
49              b, reduction_indices=dim0).eval(), [True, True])
50      self.assertAllEqual(
51          tf.reduce_all(
52              b, reduction_indices=[0]).eval(), [False, False, False])
53      self.assertAllEqual(
54          tf.reduce_all(
55              b, reduction_indices=dim1).eval(), [False, False])
56      self.assertAllEqual(
57          tf.reduce_sum(
58              a, reduction_indices=[1]).eval(), [6., 15.])
59      self.assertAllEqual(
60          tf.reduce_sum(
61              a, reduction_indices=[0, 1]).eval(), 21.0)
62      self.assertAllEqual(tf.reduce_sum(a, [0, 1]).eval(), 21.0)
63      self.assertAllEqual(
64          tf.reduce_prod(
65              a, reduction_indices=[1]).eval(), [6., 120.])
66      self.assertAllEqual(
67          tf.reduce_prod(
68              a, reduction_indices=[0, 1]).eval(), 720.0)
69      self.assertAllEqual(tf.reduce_prod(a, [0, 1]).eval(), 720.0)
70      self.assertAllEqual(
71          tf.reduce_mean(
72              a, reduction_indices=[1]).eval(), [2., 5.])
73      self.assertAllEqual(
74          tf.reduce_mean(
75              a, reduction_indices=[0, 1]).eval(), 3.5)
76      self.assertAllEqual(tf.reduce_mean(a, [0, 1]).eval(), 3.5)
77      self.assertAllEqual(
78          tf.reduce_min(
79              a, reduction_indices=[1]).eval(), [1., 4.])
80      self.assertAllEqual(
81          tf.reduce_min(
82              a, reduction_indices=[0, 1]).eval(), 1.0)
83      self.assertAllEqual(tf.reduce_min(a, [0, 1]).eval(), 1.0)
84      self.assertAllEqual(
85          tf.reduce_max(
86              a, reduction_indices=[1]).eval(), [3., 6.])
87      self.assertAllEqual(
88          tf.reduce_max(
89              a, reduction_indices=[0, 1]).eval(), 6.0)
90      self.assertAllEqual(tf.reduce_max(a, [0, 1]).eval(), 6.0)
91      self.assertAllClose(tf.reduce_logsumexp(a, reduction_indices=[1]).eval(),
92                          [3.40760589, 6.40760612])
93      self.assertAllClose(
94          tf.reduce_logsumexp(a, reduction_indices=[0, 1]).eval(),
95          6.45619344711)
96      self.assertAllClose(
97          tf.reduce_logsumexp(a, [0, 1]).eval(), 6.45619344711)
98      self.assertAllEqual(
99          tf.expand_dims([[1, 2], [3, 4]], axis=1).eval(),
100          [[[1, 2]], [[3, 4]]])
101
102  @test_util.run_v1_only("b/120545219")
103  def testArgMinMax(self):
104    with self.cached_session():
105      self.assertAllEqual(
106          tf.argmin([[1, 2, 3], [4, 1, 0]], dimension=1).eval(),
107          [0, 2])
108      self.assertAllEqual(
109          tf.argmin([[1, 2, 3], [4, 1, 0]], dimension=0).eval(),
110          [0, 1, 1])
111      self.assertAllEqual(
112          tf.argmax([[1, 2, 3], [4, 1, 0]], dimension=1).eval(),
113          [2, 0])
114      self.assertAllEqual(
115          tf.argmax([[1, 2, 3], [4, 1, 0]], dimension=0).eval(),
116          [1, 0, 0])
117
118  @test_util.run_v1_only("b/120545219")
119  def testExpandAndSqueeze(self):
120    with self.cached_session():
121
122      # TODO(aselle): sparse_split, sparse_reduce_sum,
123      #  sparse_reduce_sum_sparse, reduce_join
124      a = [[1, 2, 3]]
125      self.assertAllEqual(tf.expand_dims(tf.squeeze(a, [0]), 0).eval(),
126                          a)
127      self.assertAllEqual(tf.squeeze(tf.expand_dims(a, 1), [1]).eval(),
128                          a)
129      self.assertAllEqual(
130          tf.expand_dims(tf.squeeze([[1, 2, 3]], axis=[0]), dim=0).eval(), a)
131      self.assertAllEqual(
132          tf.squeeze(tf.expand_dims([[1, 2, 3]], dim=1), axis=[1]).eval(), a)
133
134      self.assertAllEqual(
135          tf.squeeze(tf.expand_dims([[1, 2, 3]], dim=1), axis=[1]).eval(), a)
136
137  @test_util.run_v1_only("b/120545219")
138  def testArithmeticRenames(self):
139    with self.cached_session() as s:
140      stuff = tf.split(1, 2, [[1, 2, 3, 4], [4, 5, 6, 7]])
141      vals = s.run(stuff)
142      self.assertAllEqual(vals,
143                          [[[1, 2], [4, 5]], [[3, 4], [6, 7]]])
144      self.assertAllEqual(
145          tf.neg(tf.mul(tf.add(1, 2), tf.sub(5, 3))).eval(),
146          -6)
147      self.assertAllEqual(
148          s.run(tf.listdiff([1, 2, 3], [3, 3, 4]))[0], [1, 2])
149      self.assertAllEqual(
150          tf.list_diff([1, 2, 3], [3, 3, 4])[0].eval(), [1, 2])
151      a = [[1., 2., 3.], [4., 5., 6.]]
152      foo = np.where(np.less(a, 2), np.negative(a), a)
153      self.assertAllEqual(
154          tf.select(tf.less(a, 2), tf.neg(a), a).eval(),
155          foo)
156      self.assertAllEqual(
157          tf.complex_abs(tf.constant(3 + 4.j)).eval(),
158          5)
159      #     # TODO(aselle): (tf.batch_*)
160      # ]
161
162  @test_util.run_v1_only("b/120545219")
163  def testBatchAndSvd(self):
164    with self.cached_session():
165      mat = [[1., 2.], [2., 3.]]
166      batched_mat = tf.expand_dims(mat, [0])
167      result = tf.matmul(mat, mat).eval()
168      result_batched = tf.batch_matmul(batched_mat, batched_mat).eval()
169      self.assertAllEqual(result_batched, np.expand_dims(result, 0))
170      self.assertAllEqual(
171          tf.svd(mat, False, True).eval(),
172          tf.svd(mat, compute_uv=False, full_matrices=True).eval())
173
174  @test_util.run_v1_only("b/120545219")
175  def testCrossEntropy(self):
176    # TODO(aselle): Test sparse_softmax_...
177    with self.cached_session():
178      labels = [.8, .5, .2, .1]
179      logits = [.9, .1, .3, .1]
180      self.assertAllEqual(
181          tf.nn.softmax_cross_entropy_with_logits(
182              logits, labels).eval(),
183          tf.nn.softmax_cross_entropy_with_logits(
184              labels=labels, logits=logits).eval())
185      self.assertAllEqual(
186          tf.nn.sigmoid_cross_entropy_with_logits(
187              logits, labels).eval(),
188          tf.nn.sigmoid_cross_entropy_with_logits(
189              labels=labels, logits=logits).eval())
190
191  @test_util.run_v1_only("b/120545219")
192  def testVariables(self):
193    with self.cached_session() as s:
194
195      # make some variables
196      _ = [tf.Variable([1, 2, 3], dtype=tf.float32),
197           tf.Variable([1, 2, 3], dtype=tf.int32)]
198      s.run(tf.global_variables_initializer())
199      _ = [v.name for v in tf.all_variables()]
200      _ = [v.name for v in tf.local_variables()]
201
202  @test_util.run_v1_only("b/120545219")
203  def testSummaries(self):
204    with self.cached_session() as s:
205      var = tf.Variable([1, 2, 3], dtype=tf.float32)
206      s.run(tf.global_variables_initializer())
207      x, y = np.meshgrid(np.linspace(-10, 10, 256), np.linspace(-10, 10, 256))
208      image = np.sin(x**2 + y**2) / np.sqrt(x**2 + y**2) * .5 + .5
209      image = image[None, :, :, None]
210
211      # make a dummy sound
212      freq = 440  # A = 440Hz
213      sampling_frequency = 11000
214      audio = np.sin(2 * np.pi * np.linspace(0, 1, sampling_frequency) * freq)
215      audio = audio[None, :, None]
216      test_dir = tempfile.mkdtemp()
217      # test summaries
218      writer = tf.train.SummaryWriter(test_dir)
219      summaries = [
220          tf.scalar_summary("scalar_var", var[0]),
221          tf.scalar_summary("scalar_reduce_var", tf.reduce_sum(var)),
222          tf.histogram_summary("var_histogram", var),
223          tf.image_summary("sin_image", image),
224          tf.audio_summary("sin_wave", audio, sampling_frequency),
225      ]
226      run_summaries = s.run(summaries)
227      writer.add_summary(s.run(tf.merge_summary(inputs=run_summaries)))
228      # This is redundant, but we want to be able to rewrite the command
229      writer.add_summary(s.run(tf.merge_all_summaries()))
230      writer.close()
231      shutil.rmtree(test_dir)
232
233
234if __name__ == "__main__":
235  test_lib.main()
236