1# Copyright 2017 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 DecodeLibsvm op.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import print_function 20 21import numpy as np 22 23from tensorflow.contrib.libsvm.python.ops import libsvm_ops 24from tensorflow.python.framework import dtypes 25from tensorflow.python.ops import sparse_ops 26from tensorflow.python.platform import test 27 28 29class DecodeLibsvmOpTest(test.TestCase): 30 31 def testBasic(self): 32 with self.cached_session() as sess: 33 content = [ 34 "1 1:3.4 2:0.5 4:0.231", "1 2:2.5 3:inf 5:0.503", 35 "2 3:2.5 2:nan 1:0.105" 36 ] 37 sparse_features, labels = libsvm_ops.decode_libsvm( 38 content, num_features=6) 39 features = sparse_ops.sparse_tensor_to_dense( 40 sparse_features, validate_indices=False) 41 42 self.assertAllEqual(labels.get_shape().as_list(), [3]) 43 44 features, labels = sess.run([features, labels]) 45 self.assertAllEqual(labels, [1, 1, 2]) 46 self.assertAllClose( 47 features, [[0, 3.4, 0.5, 0, 0.231, 0], [0, 0, 2.5, np.inf, 0, 0.503], 48 [0, 0.105, np.nan, 2.5, 0, 0]]) 49 50 def testNDimension(self): 51 with self.cached_session() as sess: 52 content = [["1 1:3.4 2:0.5 4:0.231", "1 1:3.4 2:0.5 4:0.231"], 53 ["1 2:2.5 3:inf 5:0.503", "1 2:2.5 3:inf 5:0.503"], 54 ["2 3:2.5 2:nan 1:0.105", "2 3:2.5 2:nan 1:0.105"]] 55 sparse_features, labels = libsvm_ops.decode_libsvm( 56 content, num_features=6, label_dtype=dtypes.float64) 57 features = sparse_ops.sparse_tensor_to_dense( 58 sparse_features, validate_indices=False) 59 60 self.assertAllEqual(labels.get_shape().as_list(), [3, 2]) 61 62 features, labels = sess.run([features, labels]) 63 self.assertAllEqual(labels, [[1, 1], [1, 1], [2, 2]]) 64 self.assertAllClose( 65 features, [[[0, 3.4, 0.5, 0, 0.231, 0], [0, 3.4, 0.5, 0, 0.231, 0]], [ 66 [0, 0, 2.5, np.inf, 0, 0.503], [0, 0, 2.5, np.inf, 0, 0.503] 67 ], [[0, 0.105, np.nan, 2.5, 0, 0], [0, 0.105, np.nan, 2.5, 0, 0]]]) 68 69 70if __name__ == "__main__": 71 test.main() 72