diff --git a/keras/backend/common/variables_test.py b/keras/backend/common/variables_test.py index 42bd4d45524..a188f954bef 100644 --- a/keras/backend/common/variables_test.py +++ b/keras/backend/common/variables_test.py @@ -238,7 +238,7 @@ def test_variable_numpy(self): self.assertAllClose(v.numpy(), np.array([1, 2, 3])) @pytest.mark.skipif( - backend.backend() != "tf", + backend.backend() != "tensorflow", reason="Tests for MirroredVariable under tf backend", ) def test_variable_numpy_scalar(self): diff --git a/keras/layers/preprocessing/discretization.py b/keras/layers/preprocessing/discretization.py index 005109c745b..ca5eb255a5e 100644 --- a/keras/layers/preprocessing/discretization.py +++ b/keras/layers/preprocessing/discretization.py @@ -235,6 +235,8 @@ def call(self, inputs): dtype=self.compute_dtype, backend_module=self.backend, ) + if self.sparse: + return tf.sparse.from_dense(outputs) return outputs def get_config(self): diff --git a/keras/layers/preprocessing/discretization_test.py b/keras/layers/preprocessing/discretization_test.py index 490ff9fa4da..8677282de7f 100644 --- a/keras/layers/preprocessing/discretization_test.py +++ b/keras/layers/preprocessing/discretization_test.py @@ -1,6 +1,7 @@ import os import numpy as np +import pytest from absl.testing import parameterized from tensorflow import data as tf_data @@ -11,7 +12,7 @@ from keras.saving import saving_api -class DicretizationTest(testing.TestCase, parameterized.TestCase): +class DiscretizationTest(testing.TestCase, parameterized.TestCase): def test_discretization_basics(self): self.run_layer_test( layers.Discretization, @@ -125,6 +126,55 @@ def test_saving(self): model = saving_api.load_model(fpath) self.assertAllClose(layer(ref_input), ref_output) - def test_sparse_inputs(self): - # TODO - pass + @parameterized.parameters( + [ + ( + "one_hot", + [[-1.0, 0.2, 0.7, 1.2]], + [ + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] + ], + ), + ( + "multi_hot", + [[[-1.0], [0.2], [0.7], [1.2]]], + [ + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] + ], + ), + ( + "count", + [[-1.0], [0.2], [0.7], [1.2]], + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + ), + ] + ) + @pytest.mark.skipif( + backend.backend() != "tensorflow", + reason="Sparse tensor only works in TensorFlow", + ) + def test_sparse_output(self, output_mode, input_array, expected_output): + from keras.utils.module_utils import tensorflow as tf + + x = np.array(input_array) + layer = layers.Discretization( + bin_boundaries=[0.0, 0.5, 1.0], sparse=True, output_mode=output_mode + ) + output = layer(x) + self.assertTrue(isinstance(output, tf.SparseTensor)) + self.assertAllClose(output, np.array(expected_output))