From cce5dc36d10050f5043f411edccf30d00cff5693 Mon Sep 17 00:00:00 2001 From: Haifeng Jin Date: Fri, 18 Aug 2023 22:13:43 +0000 Subject: [PATCH 1/2] add the test --- keras_core/layers/preprocessing/rescaling_test.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/keras_core/layers/preprocessing/rescaling_test.py b/keras_core/layers/preprocessing/rescaling_test.py index 6bdf61cff..2852204c6 100644 --- a/keras_core/layers/preprocessing/rescaling_test.py +++ b/keras_core/layers/preprocessing/rescaling_test.py @@ -2,6 +2,7 @@ import pytest import tensorflow as tf +from keras_core import backend from keras_core import layers from keras_core import testing @@ -73,3 +74,13 @@ def test_tf_data_compatibility(self): ds = tf.data.Dataset.from_tensor_slices(x).batch(3).map(layer) for output in ds.take(1): output.numpy() + + def test_rescaling_with_channels_first_and_vector_scale(self): + config = backend.image_data_format() + backend.set_image_data_format("channels_first") + layer = layers.Rescaling( + scale=[1.0 / 255, 1.5 / 255, 2.0 / 255], offset=0.5 + ) + x = np.random.random((2, 3, 10, 10)) * 255 + layer(x) + backend.set_image_data_format(config) From 7a6cb2968c6cd90189ffbb36dc9cdee0a82390ba Mon Sep 17 00:00:00 2001 From: Haifeng Jin Date: Fri, 18 Aug 2023 22:13:53 +0000 Subject: [PATCH 2/2] add the fix --- keras_core/layers/preprocessing/rescaling.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/keras_core/layers/preprocessing/rescaling.py b/keras_core/layers/preprocessing/rescaling.py index 50c90c23d..8772ce741 100644 --- a/keras_core/layers/preprocessing/rescaling.py +++ b/keras_core/layers/preprocessing/rescaling.py @@ -1,3 +1,4 @@ +from keras_core import backend from keras_core.api_export import keras_core_export from keras_core.layers.preprocessing.tf_data_layer import TFDataLayer @@ -40,6 +41,14 @@ def call(self, inputs): dtype = self.compute_dtype scale = self.backend.cast(self.scale, dtype) offset = self.backend.cast(self.offset, dtype) + scale_shape = self.backend.core.shape(scale) + if ( + len(scale_shape) > 0 + and backend.image_data_format() == "channels_first" + ): + scale = self.backend.numpy.reshape( + scale, scale_shape + (1,) * (3 - len(scale_shape)) + ) return self.backend.cast(inputs, dtype) * scale + offset def compute_output_shape(self, input_shape):