• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 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 tensorflow.ops.tf.norm."""
16
17import numpy as np
18
19from tensorflow.python.framework import constant_op
20from tensorflow.python.framework import test_util
21from tensorflow.python.ops import array_ops
22from tensorflow.python.ops import linalg_ops
23from tensorflow.python.platform import test as test_lib
24
25
26def _AddTest(test, test_name, fn):
27  test_name = "_".join(["test", test_name])
28  if hasattr(test, test_name):
29    raise RuntimeError("Test %s defined more than once" % test_name)
30  setattr(test, test_name, fn)
31
32
33class NormOpTest(test_lib.TestCase):
34
35  @test_util.run_v1_only("b/120545219")
36  def testBadOrder(self):
37    matrix = [[0., 1.], [2., 3.]]
38    for ord_ in "fro", -7, -1.1, 0:
39      with self.assertRaisesRegex(ValueError,
40                                  "'ord' must be a supported vector norm"):
41        linalg_ops.norm(matrix, ord=ord_)
42
43    for ord_ in "fro", -7, -1.1, 0:
44      with self.assertRaisesRegex(ValueError,
45                                  "'ord' must be a supported vector norm"):
46        linalg_ops.norm(matrix, ord=ord_, axis=-1)
47
48    for ord_ in "foo", -7, -1.1, 1.1:
49      with self.assertRaisesRegex(ValueError,
50                                  "'ord' must be a supported matrix norm"):
51        linalg_ops.norm(matrix, ord=ord_, axis=[-2, -1])
52
53  @test_util.run_v1_only("b/120545219")
54  def testInvalidAxis(self):
55    matrix = [[0., 1.], [2., 3.]]
56    for axis_ in [], [1, 2, 3], [[1]], [[1], [2]], [3.1415], [1, 1]:
57      error_prefix = ("'axis' must be None, an integer, or a tuple of 2 unique "
58                      "integers")
59      with self.assertRaisesRegex(ValueError, error_prefix):
60        linalg_ops.norm(matrix, axis=axis_)
61
62
63def _GetNormOpTest(dtype_, shape_, ord_, axis_, keep_dims_, use_static_shape_):
64
65  def _CompareNorm(self, matrix):
66    np_norm = np.linalg.norm(matrix, ord=ord_, axis=axis_, keepdims=keep_dims_)
67    with self.cached_session() as sess:
68      if use_static_shape_:
69        tf_matrix = constant_op.constant(matrix)
70        tf_norm = linalg_ops.norm(
71            tf_matrix, ord=ord_, axis=axis_, keepdims=keep_dims_)
72        tf_norm_val = self.evaluate(tf_norm)
73      else:
74        tf_matrix = array_ops.placeholder(dtype_)
75        tf_norm = linalg_ops.norm(
76            tf_matrix, ord=ord_, axis=axis_, keepdims=keep_dims_)
77        tf_norm_val = sess.run(tf_norm, feed_dict={tf_matrix: matrix})
78    self.assertAllClose(np_norm, tf_norm_val, rtol=1e-5, atol=1e-5)
79
80  @test_util.run_v1_only("b/120545219")
81  def Test(self):
82    is_matrix_norm = (isinstance(axis_, tuple) or
83                      isinstance(axis_, list)) and len(axis_) == 2
84    is_fancy_p_norm = np.isreal(ord_) and np.floor(ord_) != ord_
85    if ((not is_matrix_norm and ord_ == "fro") or
86        (is_matrix_norm and is_fancy_p_norm)):
87      self.skipTest("Not supported by neither numpy.linalg.norm nor tf.norm")
88    if ord_ == "euclidean" or (axis_ is None and len(shape) > 2):
89      self.skipTest("Not supported by numpy.linalg.norm")
90    matrix = np.random.randn(*shape_).astype(dtype_)
91    if dtype_ in (np.complex64, np.complex128):
92      matrix += 1j * np.random.randn(*shape_).astype(dtype_)
93    _CompareNorm(self, matrix)
94
95  return Test
96
97# pylint: disable=redefined-builtin
98if __name__ == "__main__":
99  for use_static_shape in False, True:
100    for dtype in np.float32, np.float64, np.complex64, np.complex128:
101      for rows in 2, 5:
102        for cols in 2, 5:
103          for batch in [], [2], [2, 3]:
104            shape = batch + [rows, cols]
105            for ord in "euclidean", "fro", 0.5, 1, 2, np.inf:
106              for axis in [
107                  None, (-2, -1), (-1, -2), -len(shape), 0, len(shape) - 1
108              ]:
109                for keep_dims in False, True:
110                  name = "%s_%s_ord_%s_axis_%s_%s_%s" % (
111                      dtype.__name__, "_".join(map(str, shape)), ord, axis,
112                      keep_dims, use_static_shape)
113                  _AddTest(NormOpTest, "Norm_" + name,
114                           _GetNormOpTest(dtype, shape, ord, axis, keep_dims,
115                                          use_static_shape))
116
117  test_lib.main()
118