Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix channels_first format bug for rescaling layer #792

Merged
merged 2 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions keras_core/layers/preprocessing/rescaling.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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):
Expand Down
11 changes: 11 additions & 0 deletions keras_core/layers/preprocessing/rescaling_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)