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