Home | History | Annotate | Download | only in kernel_tests
      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.kernels.sparse_op."""
     16 
     17 from __future__ import absolute_import
     18 from __future__ import division
     19 from __future__ import print_function
     20 
     21 import numpy as np
     22 
     23 from tensorflow.python.framework import dtypes
     24 from tensorflow.python.ops import array_ops
     25 from tensorflow.python.ops import sparse_ops
     26 from tensorflow.python.platform import test
     27 
     28 
     29 def _SparseToDense(sparse_indices,
     30                    output_size,
     31                    sparse_values,
     32                    default_value,
     33                    validate_indices=True):
     34   return sparse_ops.sparse_to_dense(
     35       sparse_indices,
     36       output_size,
     37       sparse_values,
     38       default_value=default_value,
     39       validate_indices=validate_indices)
     40 
     41 
     42 class SparseToDenseTest(test.TestCase):
     43 
     44   def testInt(self):
     45     with self.test_session(use_gpu=False):
     46       tf_ans = _SparseToDense([1, 3], [5], 1, 0).eval()
     47     np_ans = np.array([0, 1, 0, 1, 0]).astype(np.int32)
     48     self.assertAllClose(np_ans, tf_ans)
     49 
     50   def testFloat(self):
     51     with self.test_session(use_gpu=False):
     52       tf_ans = _SparseToDense([1, 3], [5], 1.0, 0.0).eval()
     53     np_ans = np.array([0, 1, 0, 1, 0]).astype(np.float32)
     54     self.assertAllClose(np_ans, tf_ans)
     55 
     56   def testString(self):
     57     with self.test_session(use_gpu=False):
     58       tf_ans = _SparseToDense([1, 3], [5], "a", "b").eval()
     59     np_ans = np.array(["b", "a", "b", "a", "b"]).astype(np.string_)
     60     self.assertAllEqual(np_ans, tf_ans)
     61 
     62   def testSetValue(self):
     63     with self.test_session(use_gpu=False):
     64       tf_ans = _SparseToDense([1, 3], [5], [1, 2], -1).eval()
     65     np_ans = np.array([-1, 1, -1, 2, -1]).astype(np.int32)
     66     self.assertAllClose(np_ans, tf_ans)
     67 
     68   def testSetSingleValue(self):
     69     with self.test_session(use_gpu=False):
     70       tf_ans = _SparseToDense([1, 3], [5], 1, -1).eval()
     71     np_ans = np.array([-1, 1, -1, 1, -1]).astype(np.int32)
     72     self.assertAllClose(np_ans, tf_ans)
     73 
     74   def test2d(self):
     75     # pylint: disable=bad-whitespace
     76     with self.test_session(use_gpu=False):
     77       tf_ans = _SparseToDense([[1, 3], [2, 0]], [3, 4], 1, -1).eval()
     78     np_ans = np.array([[-1, -1, -1, -1],
     79                        [-1, -1, -1,  1],
     80                        [ 1, -1, -1, -1]]).astype(np.int32)
     81     self.assertAllClose(np_ans, tf_ans)
     82 
     83   def testZeroDefault(self):
     84     with self.test_session():
     85       x = sparse_ops.sparse_to_dense(2, [4], 7).eval()
     86       self.assertAllEqual(x, [0, 0, 7, 0])
     87 
     88   def test3d(self):
     89     with self.test_session(use_gpu=False):
     90       tf_ans = _SparseToDense([[1, 3, 0], [2, 0, 1]], [3, 4, 2], 1, -1).eval()
     91     np_ans = np.ones((3, 4, 2), dtype=np.int32) * -1
     92     np_ans[1, 3, 0] = 1
     93     np_ans[2, 0, 1] = 1
     94     self.assertAllClose(np_ans, tf_ans)
     95 
     96   def testBadShape(self):
     97     with self.test_session():
     98       with self.assertRaisesWithPredicateMatch(ValueError, "must be rank 1"):
     99         _SparseToDense([1, 3], [[5], [3]], 1, -1)
    100 
    101   def testBadValue(self):
    102     with self.test_session():
    103       dense = _SparseToDense([1, 3], [5], [[5], [3]], -1)
    104       with self.assertRaisesOpError(
    105           r"sparse_values has incorrect shape \[2,1\], "
    106           r"should be \[\] or \[2\]"):
    107         dense.eval()
    108 
    109   def testBadNumValues(self):
    110     with self.test_session():
    111       dense = _SparseToDense([1, 3], [5], [1, 2, 3], -1)
    112       with self.assertRaisesOpError(
    113           r"sparse_values has incorrect shape \[3\], should be \[\] or \[2\]"):
    114         dense.eval()
    115 
    116   def testBadDefault(self):
    117     with self.test_session():
    118       dense = _SparseToDense([1, 3], [5], [1, 2], [0])
    119       with self.assertRaisesOpError("default_value should be a scalar"):
    120         dense.eval()
    121 
    122   def testOutOfBoundsIndicesWithWithoutValidation(self):
    123     with self.test_session():
    124       dense = _SparseToDense(
    125           sparse_indices=[[1], [10]],
    126           output_size=[5],
    127           sparse_values=[-1.0, 1.0],
    128           default_value=0.0)
    129       with self.assertRaisesOpError(
    130           r"indices\[1\] = \[10\] is out of bounds: need 0 <= index < \[5\]"):
    131         dense.eval()
    132       # Disable checks, the allocation should still fail.
    133       with self.assertRaisesOpError("out of bounds"):
    134         dense_without_validation = _SparseToDense(
    135             sparse_indices=[[1], [10]],
    136             output_size=[5],
    137             sparse_values=[-1.0, 1.0],
    138             default_value=0.0,
    139             validate_indices=False)
    140         dense_without_validation.eval()
    141 
    142   def testRepeatingIndicesWithWithoutValidation(self):
    143     with self.test_session():
    144       dense = _SparseToDense(
    145           sparse_indices=[[1], [1]],
    146           output_size=[5],
    147           sparse_values=[-1.0, 1.0],
    148           default_value=0.0)
    149       with self.assertRaisesOpError(r"indices\[1\] = \[1\] is repeated"):
    150         dense.eval()
    151       # Disable checks
    152       dense_without_validation = _SparseToDense(
    153           sparse_indices=[[1], [1]],
    154           output_size=[5],
    155           sparse_values=[-1.0, 1.0],
    156           default_value=0.0,
    157           validate_indices=False)
    158       dense_without_validation.eval()
    159 
    160   def testUnsortedIndicesWithWithoutValidation(self):
    161     with self.test_session():
    162       dense = _SparseToDense(
    163           sparse_indices=[[2], [1]],
    164           output_size=[5],
    165           sparse_values=[-1.0, 1.0],
    166           default_value=0.0)
    167       with self.assertRaisesOpError(r"indices\[1\] = \[1\] is out of order"):
    168         dense.eval()
    169       # Disable checks
    170       dense_without_validation = _SparseToDense(
    171           sparse_indices=[[2], [1]],
    172           output_size=[5],
    173           sparse_values=[-1.0, 1.0],
    174           default_value=0.0,
    175           validate_indices=False)
    176       dense_without_validation.eval()
    177 
    178   def testShapeInferenceKnownShape(self):
    179     with self.test_session(use_gpu=False):
    180       indices = array_ops.placeholder(dtypes.int64)
    181 
    182       shape = [4, 5, 6]
    183       output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)
    184       self.assertEqual(output.get_shape(), [4, 5, 6])
    185 
    186       shape = array_ops.placeholder(dtypes.int64, shape=(3,))
    187       output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)
    188       self.assertEqual(output.get_shape().as_list(), [None, None, None])
    189 
    190   def testShapeInferenceUnknownShape(self):
    191     with self.test_session(use_gpu=False):
    192       indices = array_ops.placeholder(dtypes.int64)
    193       shape = array_ops.placeholder(dtypes.int64)
    194       output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)
    195       self.assertEqual(output.get_shape().ndims, None)
    196 
    197 
    198 if __name__ == "__main__":
    199   test.main()
    200